Register sidebar


All developers know the time it takes to code a new website template, and any resource that can help shave off some dev time is well worth using. Starting today, we are rolling out a series of free WordPress developer tools in the form of snippet generators and related resources that will help you create clean code in a matter of seconds. Our first generator spins off custom dynamic sidebars for WordPress – just fill out the fields to get started.

About this tool

This is a custom dynamic sidebar snippet generator that was built with both established front-end developers and first-time theme builders in mind. My goal was to simplify and streamline the widgetization process so that you are just entering in a few bits of information to get clean code that you can use to integrate into your existing WordPress theme templating, or as the basis for building the framework of your next project.

What are custom dynamic sidebars and why should you include them in your theme?


Dynamic sidebars are essentially widget areas that may be used to display widgetized content in many locations around your WordPress website. These “sidebars” (or “asides” in the html markup world; “content buckets” in the marketing world) allow non-developer users to drag-and-drop content blocks into themes. This can allow users to integrate versatile plugins via these widget areas or insert hard-coded, custom widgets.

When WordPress first started, it was the norm for widgets to be used in one sidebar location only, with the same content displayed in the sidebar on each page of a site. However, things have evolved since then and there are now many situations in which you may find yourself needing more than one widget area, sidebar, or content block.

Location-wise, a sidebar is just one of the places you can put widgetized content, so the term “dynamic sidebar” actually refers to dynamic content that can be placed in a variety of locations: headers, footers, secondary sidebars, above or below the page content… a sidebar is just one of those areas that can traditionally house dynamic content.

How to use this WordPress Dynamic Sidebar Snippet Generator tool

This dynamic sidebar snippet generator tool is intended to do the heavy lifting for you, so you don’t have to hand-code these standard code snippets for each project or copy/paste from the WordPress codex, where variables and arrays are often represented but not populated in a way that allows direct input into your theme templating. I hope that it helps established developers from having to custom-code this content time and time again, and that it gives the more novice developer an easy way to get started.

STEPS FOR USING THE GENERATOR


  1. A the top of this page, in General Setup, enter your Theme Slug and Text Domain.
    1. The Theme Slug is used to prefix all functions and variables that could otherwise conflict with another plugin, theme, or with the WordPress core.
    2. The Text Domain is a unique identifier that helps WordPress identify which translatable strings to attribute to your theme vs. ones that may come from a plugin or the WordPress core.
  2. Hop over to Sidebar #1 and click the box next to Activate. This will reveal a new set of fields. The dynamic code blocks below the form will populate with your input as you add it.
    1. Name: Give your sidebar area a name.  This is what will show up on the right side of the page as an available widget area (or sidebar) in Appearance > Widgets, and it typically corresponds to the location of the new widget area. I recommend that it be descriptive and not general.
    2. ID: The ID is a unique key that allows you to display the widget content from this sidebar location as opposed to any other. I recommend that you make this key descriptive. It should contain only letters, numbers, underscores, and hyphens.

    3. Description: This text will appear to users under the sidebar name in Appearance > Widgets. It tends to give users instructions on how to fill out the sidebar location and the purpose of the location.
    4. Class: This parameter is used to attach a class to the sidebar location container on the Appearance > Widgets page. This parameter often causes confusion, as many developers assume it will be displayed in a wrapping HTML tag. Be assured it will not. It only is applied to the sidebar container in the widgets admin page.
    5. Before Widget: This is the opening tag for all widgets added to this dynamic sidebar. I strongly recommend keeping the default ID and classes. Feel free to add additional classes as needed.
    6. After Widget: This is the closing tag for the widget.
    7. Before Title: Opening tag for the title. The default heading is H2.
    8. After Title: This is the closing title tag.
  3. Repeat this for as many sidebars as your template requires.
  4. Copy and paste the code from the first box to register your sidebar(s) in your functions.php file. Then, copy and paste the code from the second box into whichever template you want the widget area(s) to display. If you have created more than one sidebar, you will want to do this for each snippet you generate.

What do the columns in the tool’s form mean?

You will notice four columns to the right of the input fields. Here is their breakdown:


  • Req. – States whether this field is required or not.
  • Valid – Determines whether the field has valid input.
  • Notes – Includes any important notes about field input.
  • Codex – Links to relevant information on the WordPress codex.

Code Snippet Output

Once you have completed filling out the code tool, two types of code snippets will be available to you by scrolling down the page or by selecting the “Code” tab. Here are some notes about how to interpret and use the output in your theme:

Register_sidebar function(s): The first block of code will need to be added to your functions.php file or to a .php file that is called from your funtions.php file. This codes snippet is made up of a few parts. The first line of PHP code looks like this:

add_action( 'widgets_init', 'your_theme_slug_widgets_init' ); 

…and is followed by the opening line of a function that will be prefixed by your theme slug.

function your_theme_slug_widgets_init() {  // stuff will go here } 

This function is going to wrap your sidebar registration code and allows you to hook these commands into a specific load-time event using the add_action hook. In this instance, the widgets_init is telling your WordPress site to register and load our new sidebar locations only after all the default WordPress widgets have been registered.


Once you’ve activated a sidebar location on one of the “Sidebar #” tabs, a new block of code will appear within your wrapper function. It should look something like this:

 register_sidebar( array(  'name' => __( 'Sidebar #1 Name', 'your-text-domain' ),  'id' => 'sidebar-1-id',  'description' => __( '', 'your-text-domain' ),  'class' => '',  'before_widget' => '<li id="%1$s" class="widget %2$s">',  	'after_widget' => '</li>',  	'before_title' => '<h2 class="widgettitle">',  	'after_title' => '</h2>',  )); 

This is the function that actually registers your new sidebar location. Once you’ve added this code to your functions.php file, you’ll be able to navigate on your WordPress admin dashboard to Appearance >> Widgets to see your new sidebar listed as a “widgetized” location in one of the two columns on the right side of the page.

Most of the parameters in the array are fairly clear, but at minimum it’s important to be sure that you’ve populated a custom Name and ID. These are the parameters you’ll use to call up and display this sidebar location on your websites public-facing templating. This will be accomplished using the next type of code snippet.


I also strongly suggest that you keep the list item html attributes (ID and class) as they are by default. Adding classes is fine. In fact, it’s a good practice if you plan to style widgets differently depending on the sidebar location, but be sure not to delete or damage the existing classes.

Dynamic_sidebar function(s): The second type of snippet you’ll be provided with is the dynamic_sidebar functions wrapped in some conditional logic. These snippets will tell your WordPress website to check if there are any widgets added to each of the sidebars you’ve registered and, if so, to output the HTML defined by those widgets. Let’s take a look at how one of these should look:

 <?php if ( is_active_sidebar( "sidebar-1-id" ) ) : ?>  <div id="myWrapperID">  	<php dynamic_sidebar( "sidebar-1-id" ); ?>  </div> <?php endif; ?> 

In this case, the sidebar ID is sidebar-1-id. This is just a default value and yours will be something descriptive hopefully like small-sidebar-top or footer-row-left or whatever helps you to identify this sidebar. It will be the same ID that you entered into the register_sidebar function that we discussed above.

You can almost read the logic in this snippet without any knowledge of PHP.


English, it reads, “If there is an Active Sidebar named sidebar-1-id, then proceed to line 2. If not, skip to line 3, which tells us to do nothing.” Line 2 simply tells us, “Display the Dynamic Sidebar: sidebar-1-id.” Pretty easy right? The logic is important, because sometimes you’ll want to conditionally display some additional HTML markup only if the sidebar is active. See the next section for more on this.

Customizing the Dynamic Sidebar Snippet Code

We can extend our example from above by adding some wrapping HTML that will help us style this widget location, but only if there are widgets to display:

<?php if ( is_active_sidebar( "sidebar-1-id" ) ) : ?>  <div id="myWrapperID">  	<?php dynamic_sidebar( "sidebar-1-id" ); ?>  </div> <?php endif; ?> 

You can see that I added a <div> with the ID myWrapperID. This might be a container that we float left or right, add a border to, apply padding to, and/or many other style choices. But we only want these stylistic or structural choices to be applied to our public facing website posts/pages if the sidebar is truly active, meaning if it contains widgets.

This is a very simple example, but I hope it helps to illustrate what’s possible.

Conclusion

We hope this code snippet generator helps you out in your next project. Please drop us a line in the comments and tell us what you think of it. We are rolling out a series of these tools to help you in your project workflow, so please view our related content as well.


www.nimbusthemes.com

Уже очень давно мне режет глаза сайдбар в этом блоге. Решил заняться его оптимизацией и описать проделанную последовательность действий в этой небольшой заметке.

Собственно о какой оптимизации идет речь? Дело в том, что виджеты «Рубрики» и «Архив» в этом блоге по ширине занимают ровно половину сайдбара. Так почему бы не расположить их рядом (а не один под другим, как сейчас было до написания поста), ведь так будет намного проще найти нужную рубрику или посмотреть счетчик посещаемости, потому что не придется прокручивать страницу.

Делаем двойной сайдбар в WordPress

Сказано — сделано. Я помню, что при редактировании темы (то ли переводил что-то, то ли дописывал…) я видел в файле functions.php что-то, связанное с сайдбаром. Вот как выглядит этот код:

Немного покурив описание функции register_sidebar и поигравшись с шаблоном на одном моем тестовом сайте, я понял, что надо делать. Итак, приведенный выше код заменяем на следующий:


После этого в разделе панели управления «Внешний вид» → «Виджеты» появятся два новых виджета с именами «Left Sidebar» и «Right Sidebar». Перетаскиваем на них «Рубрики», «Архив» и «Счетчик». Кстати, важно не забыть выключить плагин WP Super Cache, если он используется в блоге, иначе никаких изменений на сайте не будет видно.

Теперь правим sidebar.php. Вот — что было:

А вот — что стало:

Вслед за основным сайдбаром мы выводим два новых. Определить id сайдбара, который нужно передать функции dynamic_sidebar, очень просто — в соответствии с порядком, в котором сайдбары создаются в functions.php с помощью register_sidebar().

Ширину слоев, в которых будут выведены сайдбары, я установил равной 49%, чтобы между ними осталось пространство. Два сайдбара вплотную друг к другу — это не очень красиво.

По большому счету — это все, но в моем случае пришлось еще поправить таблицу стилей. Смотрим:

Нужно просто закомментировать строку относительно ширины виджетов (.sidebars li ul). Далее — включаем WP Super Cache, очищаем кэш, жмем Ctr+R, чтобы браузер обновил CSS, и смотрим результат. По-моему стало ощутимо удобнее. Надеюсь, в вашем браузере ничего не поползло?

На проделанные телодвижения уходит минут пять. На мой взгляд, основная ценность данного приема состоит в том, что теперь, листая каталоги шаблонов WordPress при создании очередного «серого» проекта, не нужно думать о том, сколько сайдбаров он поддерживает. А если вы работаете дизайнером — вам не нужно ломать голову над тем, сколько сайдбаров делать в шаблоне. Делайте один, а если заказчик окажется недовольным, вы с легкостью добавите еще пол десятка.


Метки: PHP, WordPress, Сайтостроение.

eax.me

Регистрация сайдбара в WordPress. Как добавить сайдбар в WordPress

Вывод сайдбара WordPress происходит по определенному принципу, при помощи вызова в файлах шаблона и регистрации в файле functions.php функцией register_sidebar().

Будьте внимательны, перед регистрацией сайдбара убедитесь что он ранее не был зарегистрирован. При наличии нескольких регистраций с одним и тем же id, возможно возникновение ошибок. Перед редактированием сторонних шаблонов, стоит убедиться что сайдбар не «завязан» к каким-то функционалом шаблона.

Первым делом откроем файл functions.php и напишем функцию регистрации сайдбара:

Вставив этот код в файл functions.php мы зарегистрировали сразу два сайдбара боковых — правый, левый и отдельно сайдбар для футера. Также вы можете регистрировать только один сайдбар или добавить еще по необходимости, к примеру в средину страницы.

Сайдбар зарегистрирован, теперь нужно его вывести в нужном месте. Именно этим мы и займемся далее.

Как добавить sidebar в wordpress тему

Принцип добавления сайдбаров

Если вы пишите тему для своего сайта, и регистрировали сайдбар для виджетов WordPress что бы в нем что-то находилось, тогда смело можете выводить его в нужном месте используя следующий код:

При написании шаблонов на заказ или для стороннего использования, стоит проверять наличие виджетов WordPress, о них можно почитать тут. Возможно пользователь вашей темы откажется от использования сайдбара на сайте и ему ни к чему будут пустые блоки на странице. Для проверки использования виджетов и добавления сайдбара в WordPress тему используют следующее:

Мы проверили существуют ли виджеты в правом сайдбаре и вывели их на странице. По аналогии, заменяя лишь значение ID сайдбара (right-side) на нужный нам, мы сможем вывести все блоки на страницу в необходимом месте.

Куда добавить код для вывода сайдбара в WordPress

Для сайдбаров в вордпресс зарезервирован файл шаблона sidebar.php. Именно в нем в большинстве случаев описывается все необходимое (обертки панелек, условия для вывода на определенных страницах и т.д.)

Если у вас один сайдбар, тогда добавляйте его код в sidebar.php, и подключайте его в нужном месте в файле index.php с помощью функции:

При использовании нескольких сайд баров вам нужно будет создавать дополнительные файлы к примеру sidebar-right.php, sidebar-left.php и sidebar-footer.php.

Поместив необходимый участок кода в нужный файл, подключение к индексному будет происходить следующим образом:

Месторасположение подключения вы выбираете самостоятельно. Значение в скобках должно соответствовать названию файла (sidebar-right.php), выделено жирным.

Как убрать сайдбар в WordPress?

Я детально рассказал как добавить сайдбар в WordPress, теперь пойдем от обратного и начнем удалять. Составлю небольшой план как убрать сайдбар в WordPress (перед редактированием файлов обязательно сделайте их копии и пользуйтесь FTP, не редактируйте с админки):

  • Заходим в папку с темой и открываем следующие файлы functions.php, sidebar.php и index.php;
  • ищем и удаляем регистрацию сайдбара в файле функций, как он выглядит описано выше в статье.
  • переходим к файлу sidebar.php и удаляем вызов боковой колонки (нужно удалить все что связано с dynamic_sidebar(), пример так же есть выше).
  • идем в индексный файл и удаляем подключение файлов сайдбара (get_sidebar()).

Это муторная работа, и для не знающих может быть проблемой, но если вам это действительно нужно, тогда разберетесь.

yrokiwp.ru

Sidebar is a theme feature introduced with WordPress Version 2.2. This is one of the best features in WordPress that gave lot of flexibility in Theme and Dynamic Custom Site Development. Initially, sidebar were used only as a vertical column provided by a theme for displaying information other than the main content of the web page. But now sidebar usages has been expanded dramatically. It can be any part of your WordPress site and it’s an excellent way to display information.

The term Sidebar refers to two different things in WordPress:

  1. Dynamic sidebar: It is a dynamic widgetized area (container) where you can add single or multiple widgets from your WordPress Dashboard (Appearance => Widgets).
  2. Sidebar template: It is a WordPress template which display the content in the sidebar.

Registering a Dynamic WordPress Sidebar

First you need to register your dynamic sidebar to use the sidebar functionality. This part is very important and always use proper code to register your sidebar.

Registering a sidebar or multiple sidebar is fairly simple stuff. Most common approach is to add the register_sidebar( $args ); function with widgets_init() action hook in your theme functions.php file. The code shown below is an example of how to properly register a sidebar in WordPress.

<?php /**  * Register Sidebar  */ function textdomain_register_sidebars() {  	/* Register the primary sidebar. */ 	register_sidebar( 		array( 			'id' => 'unique-sidebar-id', 			'name' => __( 'Sidebar Name', 'textdomain' ), 			'description' => __( 'A short description of the sidebar.', 'textdomain' ), 			'before_widget' => '<aside id="%1$s" class="widget %2$s">', 			'after_widget' => '</aside>', 			'before_title' => '<h3 class="widget-title">', 			'after_title' => '</h3>' 		) 	);  	/* Repeat register_sidebar() code for additional sidebars. */ } add_action( 'widgets_init', 'textdomain_register_sidebars' ); ?> 

Register Sidebars code from Twenty Thirteen Default WordPress Theme functions.php file

/**  * Register two widget areas.  *  * @since Twenty Thirteen 1.0  *  * @return void  */ function twentythirteen_widgets_init() { 	register_sidebar( array( 		'name' => __( 'Main Widget Area', 'twentythirteen' ), 		'id' => 'sidebar-1', 		'description' => __( 'Appears in the footer section of the site.', 'twentythirteen' ), 		'before_widget' => '<aside id="%1$s" class="widget %2$s">', 		'after_widget' => '</aside>', 		'before_title' => '<h3 class="widget-title">', 		'after_title' => '</h3>', 	) );  	register_sidebar( array( 		'name' => __( 'Secondary Widget Area', 'twentythirteen' ), 		'id' => 'sidebar-2', 		'description' => __( 'Appears on posts and pages in the sidebar.', 'twentythirteen' ), 		'before_widget' => '<aside id="%1$s" class="widget %2$s">', 		'after_widget' => '</aside>', 		'before_title' => '<h3 class="widget-title">', 		'after_title' => '</h3>', 	) ); } add_action( 'widgets_init', 'twentythirteen_widgets_init' ); 

Arguments for dynamic_sidebar()

The register_sidebar() function accepts a single parameter named $args. $args is an array of arguments that define how the sidebar and its widgets should be handled.

  1. id: The id argument is the most important argument you can set for your sidebar. This unique ID will be used to assign widgets to a specific sidebar, and to call sidebar in your template. Each ID should be unique to the sidebar and must be in lowercase with no spaces in between. By default, WordPress sets this to sidebar-$i (where $i is a count of the registered sidebars).
  2. name: The name argument is the human-readable label for your sidebar used in the WordPress admin. Don’t make this name random and use proper name that you think best represents the name of your sidebar. It can be internationalized with __() function where the first parameter is the name and second parameter is theme textdomain.
  3. description: The description argument is the human-readable description for your sidebar used in the WordPress admin. It allows you to set a specific description for how the sidebar is used within your theme. This argument defaults to an empty string. It can be internationalized with __() function where the first parameter is the description and second parameter is theme textdomain.
  4. before_widget: The before_widget argument is a wrapper HTML element for widgets assigned to the sidebar. This argument has a couple of things that you should always set with specific code so that plugins can properly use them, which is the id (%1$s) and class (%2$s) attributes.
  5. after_widget: The after_widget argument is a closing wrapper HTML element for widgets assigned to the sidebar. You just need to close off the element you set for the before_widget argument.
  6. before_title: Most widgets display a title if the user sets one. The before_title argument is the opening wrapper HTML element for the sidebar’s widget titles.
  7. after_title: The after_title argument is to close the wrapper HTML element set in the before_title argument.

Displaying Dynamic Sidebars

After completing the process of registering sidebar, you will need to call dynamic_sidebar() function to display it in your WordPress theme. The dynamic_sidebar() function takes a single parameter of $index, which can either be the sidebar’s id or name argument that you have set while registering sidebar. The best and safer was to call sidebar with id argument.

The WordPress Twenty Thirteen theme uses the below code in sidebar-main.php file to display sidebar-1 sidebar. The following code uses a wrapper element so that the sidebar can be easily styled with CSS. Note dynamic_sidebar() can technically be called anywhere within your theme.

<div id="secondary" class="sidebar-container" role="complementary"> 	<div class="widget-area"> 		<?php dynamic_sidebar( 'sidebar-1' ); ?> 	</div><!-- .widget-area --> </div><!-- #secondary --> 

Collapse sidebars without widgets

You can opt to collapse sidebar if the sidebar is inactive (No Widgets in the particular sidebar). For that, you need to use is_active_sidebar() conditional tag to check in the sidebar has any widgets assigned to it or not.

Like the dynamic_sidebar() function used to load the sidebar, is_active_sidebar() accepts a single parameter of $index, which should be the ID of the sidebar you want to check for active widgets.

The WordPress Twenty Thirteen theme uses the below code in sidebar-main.php file to check in the sidebar has any widgets assigned to it. It will display the sidebar-1 only if there is any active widget in it.

<?php if ( is_active_sidebar( 'sidebar-1' ) ) : ?> 	<div id="secondary" class="sidebar-container" role="complementary"> 		<div class="widget-area"> 			<?php dynamic_sidebar( 'sidebar-1' ); ?> 		</div><!-- .widget-area --> 	</div><!-- #secondary --> <?php endif; ?> 

Displaying default sidebar content

Instead of collapse sidebar, you may opt to display default content when a user hasn’t assigned any widgets to a specific sidebar. To check if a dynamic sidebar has any widgets, you would use the is_active_sidebar() conditional tag.

IWith the below code, you can check if the sidebar-1 has widgets. If so, display the widgets. Else, display some custom content.

<?php if ( is_active_sidebar( 'sidebar-1' ) ) : ?> 	<div id="secondary" class="sidebar-container" role="complementary"> 		<div class="widget-area"> 			<?php dynamic_sidebar( 'sidebar-1' ); ?> 		</div><!-- .widget-area --> 	</div><!-- #secondary --> <?php else : ?> 	<!-- Create some custom HTML or call the_widget(). It's up to you. Here we have created custom widget --> 	<aside id="archives" class="widget"> 		<h3 class="widget-title"><?php _e( 'Archives', 'twentythirteen' ); ?></h3> 		<div class="widget-content"> 			<ul> 				<?php wp_get_archives( array( 'type' => 'monthly' ) ); ?> 			</ul> 		</div> 	</aside> <?php endif; ?> 

Sidebar Templates

Sidebar templates are typically a php file where the code for a dynamic sidebar are added. Most of the WordPress theme has a single sidebar template file called sidebar.php. But you have more template files. For example: Twenty Thirteen theme uses two sidebar template files called sidebar.php and sidebar-main.php, where dynamic sidebar sidebar-1 code is added in sidebar-main.php and sidebar-2 code is added in sidebar.php file.

Now, you have to use get_sidebar( $name ); function to loads both of these sidebar templates. In Twenty Thirteen theme used the following functions to load both of the sidebar template.

<?php  //Loading sidebar.php file get_sidebar();  ?>  <?php  //Loading sidebar-main.php file get_sidebar( 'main' ); ?> 

Note

Sidebar templates don’t actually have to display dynamic sidebars. They can technically contain custom-coded content that displays anything. At the same time, you can display a dynamic sidebar in any template file you like.

devotepress.com

WordPress Register Sidebar Function

 <?php register_sidebar( $args ); ?> 

The parameters that this accepts is a array of options.

 <?php $args = array(  'name' => sprintf(__('Sidebar %d'), $i ),  'id' => 'sidebar-$i',  'description' => '',  'before_widget' => '<li id="%1$s" class="widget %2$s">',  'after_widget' => '</li>',  'before_title' => '<h2 class="widgettitle">',  'after_title' => '</h2>' ); ?> 

The options before_widget, after_widget, before_title and after_title all accept HTML tags which will be placed around the sidebar widgets. Below is an example of creating a WordPress main sidebar add the following to your functions.php page.

 if ( function_exists('register_sidebar') ) {  register_sidebar(array(  'name' => 'Main Sidebar',  'before_widget' => '<div id="%1$s" class="widget %2$s clearfix">',  'after_widget' => '</div>',  'before_title' => '<h3 class="widget-title">',  'after_title' => '</h3>',  )); } 

WordPress Dynamic Sidebar Function

Once you sidebar is registered you need to place this in your HTML by using the function dynamic_sidebar().

 <?php dynamic_sidebar( $index ); ?>  

The index parameter is the ID or name you give to your sidebar once it is registered. Add the following to anywhere on your theme you would like the sidebar to appear.

 <ul id="sidebar">  <?php dynamic_sidebar( 'Right Sidebar' ); ?> </ul> 

paulund.co.uk

Why WordPress Sidebars Are Important (And When to Use Them)

Sidebars are incredibly popular elements across all types of websites, not just those built with WordPress. Just like menus and footers, they provide you with a dedicated space that comes in handy in a lot of cases, such as:

  • Adding persistent elements across pages. Sidebars are ideal for adding signup forms, social media links, and other similar elements.
  • Displaying information that doesn’t fit in with the rest of your page. Sidebars enable you to add elements and information that would break the flow of their parent pages.

If you take a look to the right of this post, you’ll see a sidebar of our own. We use it to lead you towards other posts you might be interested in, as well as to showcase our social media links. It’s the perfect complement to a blog post, but it could look out of place elsewhere, such as on the home page, for example.

With a default WordPress installation, we would be stuck either using the same sidebar across all our pages, or none at all. It’s not a deal-breaker, but still, you’ll be happy to know we can remove this limitation easily.

An Introduction to the register_sidebar Function in WordPress

The register_sidebar function does exactly what its name implies. By default, WordPress sets up a single sidebar for your website, but there’s no limit to the number of similar elements you can add. All you have to do is register those sidebars to your theme.

This function tells WordPress to create a record for one or more new sidebars, including unique identifiers for them. To do so, you need to access your theme’s function.php file and add in a few lines of code. In a nutshell, functions.php is a WordPress core file, which enables themes to set up additional functionality through code.

In a minute, we’ll show you the code you need to add to your functions.php file, and tell you how to edit it. If you’re not knowledgeable on how to do this, don’t worry – we’ll guide you through the entire process.

To be clear – there are other ways you can add new sidebars to WordPress, such as by using plugins. However, the manual approach is much more straightforward in this case, as you’ll realize in the next section. Plus, this way your new sidebars won’t disappear if you run into any issues with a particular plugin down the line. With this in mind, let’s get to work.

How to Use the register_sidebar Function in WordPress (2 Ways)

Before we get to work, it’s essential you create a backup of your website. We’re going to edit one of WordPress core files, so you want to have a recent restoration point in case something goes wrong. Let’s talk about how to do it.

A Quick Guide to Backing Up WordPress

If you’re a 000Webhost user, you should already have access to the All-In-One WP Migration plugin, which we set up for all of our websites. This plugin enables you to backup your site, or migrate it to a new location. However, for those of you using other hosting providers, you can still take advantage of the plugin. To install it, head to the Plugins tab within WordPress, click on Add New, then use the search bar to the right to look for the All-In-One WP Migration plugin. When it shows up among the results, click on the Install Now button next to its name:

«>

After a few seconds, the button should read Activate. After clicking on it again and waiting for the process to finish, there should be an All-In-One WP Migration tab on your dashboard. From here, click the Backups tab, and look for the Create Backup button on the next page:

«>

Now, the plugin will ask you to choose where you want to export your backup file to. You can link All-In-One WP Migration to several cloud storage platforms, but for now, choose the File option. This will enable you to download your backup file to your local computer:

«>

The plugin will create a new backup, and when it’s ready, a download link will show up. Click on it, save your backup file somewhere you can remember, and you’re good to go. If you lose track of the file, you can always return to the All-In-One WP >  Backups tab. Inside, you’ll find a list of all your recent backups and you can restore your site to those states by clicking on the Restore button next to your choice:

«>

Remember, you should always have a recent backup of your website – doubly so if you’re going to make any significant changes to it. In most cases, weekly backups should suffice, although sites with a lot of dynamic content will benefit from more frequent backups. With that done, let’s get back to talking about sidebars.

1. Add a Single Sidebar to Your Theme

As we mentioned earlier, you’ll need to access and edit your theme’s functions.php file to add new sidebars to WordPress. To find it, we’re going to use File Transfer Protocol (FTP), which enables us to send data back and forth from your site using a client, such as FileZilla.

To get started, download the client and install it. Now log into your 000Webhost account and go to the Settings > General tab. Inside, you’ll find a section called FTP Details at the top of the screen. You need those credentials to access your website using the FTP client, and they’re not the same as your WordPress username and password:

«>

Keep this tab open and launch FileZilla. You’ll notice several empty fields at the top of the client’s window, corresponding to the credentials under the FTP Details section. Type in your Host Name, Username, and 000Webhost Password, then click on Quickconnect:

«>

Your FTP client will establish a connection to your website, and when it succeeds, two new folders will show up on the lower-right side of the window. The first one should be called public_html, and it’s also known as your WordPress root folder, since it contains all the platform’s core files:

«>

Open the folder and navigate to the wp-content/themes directory. Inside, you’ll find individual folders for each theme installed on your website. Look for the one that corresponds to your active theme and open it. You’ll find more folders and files inside, but we’re looking for functions.php in particular:

«>

Once you locate the file, right-click on it and choose the View/Edit option. Clicking on it will open the file using your default local text editor, enabling you to make changes to it and save them to your server. Every theme’s functions.php file should be different since they include unique features, and you shouldn’t make any changes to code you don’t recognize to avoid breaking key functionality. For now, scroll down to the bottom of the file until you reach a line reading /* That’s all, stop editing! Happy blogging */. Here, you’ll add the following code snippet right above that line:

add_action( 'widgets_init', 'my_new_sidebar' ); function my_new_sidebar() {   $args = array(     'name'          => 'Second Sidebar',     'id'            => 'second-sidebar',     'description'   => 'This is your brand new sidebar.',     'class'         => '',     'before_widget' => '<li id="%1$s" class="widget %2$s">',     'after_widget'  => '</li>',     'before_title'  => '<h2 class="widgettitle">',     'after_title'   => '</h2>'    );   register_sidebar( $args ); }

The code above tells WordPress to register a new sidebar called Second Sidebar. It also sets a new action called my_new_sidebar using the register_sidebar function, which you can spot right at the end of the code.

Aside from registering your new sidebar, the code also sets a description for it, as well as a basic structure, including its title’s format. For now, you can go ahead and replace the following placeholders at your discretion:

  • my_new_sidebar
  • Second Sidebar
  • second_sidebar
  • This is your brand new sidebar.

Keep in mind – you should always use IDs and names you can easily recognize later since you’ll need to identify this sidebar on your Widgets tab later on. When you’re done, you can save the changes to your functions.php file and close it. FileZilla will ask you if you want to update your functions.php file, to which you should answer “Yes”, and you’re good to go. Now open your WordPress dashboard and go to the Appearance > Widgets tab. There should be a new sidebar to the right of the page, which you can customize by adding widgets to it.

Now, you’ll be able to choose which sidebar to use for each page or post. If you want to create additional ones for even more functionality, keep on reading since we’ll teach you how to register several of them simultaneously.

2. Register Multiple New Sidebars at a Time

The process for registering multiple sidebars at once works just the same as with a single one. You’ll need to access your functions.php file and add the following code to it, before the line reading /* That’s all, stop editing! Happy blogging */:

add_action( 'widgets_init', ' my_new_sidebars ' ); function  my_new_sidebars() {   $args = array(     'name'          => 'New Sidebar %d',     'id'            => 'new-sidebar',     'description'   => 'One of my new sidebars.',     'class'         => '',     'before_widget' => '<li id="%1$s" class="widget %2$s">',     'after_widget'  => '</li>',     'before_title'  => '<h2 class="widgettitle">',     'after_title'   => '</h2>'    );   register_sidebar( 3, $args ); }

If you look closely, you’ll notice the bones of the code remain just the same. The only difference lies in a couple of additions to the description and register_sidebar lines. For the former, we added the %d argument, which sets a number for your sidebar’s name that increases for each new one you add.

As for the register_sidebar function, we’re telling it to set up three sidebars at once in this example. You can change the number to anything you want, and as WordPress registers new sidebars, it’ll use ever increasing numbers for their names. The code above should result in three new sidebars, called New Sidebar 1, New Sidebar 2, and New Sidebar 3, respectively.

Once you add the code, just save it and close the functions.php file. Say “Yes” when FileZilla sks if you want to update the copy of the file on your server, and that’s it. You can now find and use your three new sidebars by going to the Appearance > Widgets tab on your dashboard. Happy editing!

Conclusion

WordPress sidebars are versatile. However, the platform doesn’t enable you to set up more than one sidebar at a time by default. This means you’re stuck using the same one for all of your pages or none at all. You can always use a plugin to tackle the issue, but the easier approach is to use the register_sidebar function instead.

With the register_sidebar function, you can set up one or multiple sidebars at a time with a few lines of code. Simply edit your widgets.php file, which you can do via FTP using a client such as FileZilla.

Do you have any questions about how to use the WordPress register_sidebar function? Let’s talk about them in the comments section below?

www.000webhost.com

Регистрация сайдбаров WordPress

Для того, что-бы сайдбары для начала отобразились в админке, нам нужно их зарегистрировать. Другими словами добавить в файл functions.php код:

/**   * Регистрация сайдбаров.   */  function fwbs_widgets_init() {  	register_sidebar( array(  		'name' => __( 'Правая колонка', 'fwbs' ),  		'id' => 'sidebar-1',  		'description' => __( 'Правая боковая колонка', 'fwbs' ),  		'before_widget' => '<aside id="%1$s" class="widget %2$s">',  		'after_widget' => '</aside>',  		'before_title' => '<h4 class="widget-title">',  		'after_title' => '</h4>',  	) );  	  	register_sidebar( array(  		'name' => __( 'Левая колонка', 'fwbs' ),  		'id' => 'sidebar-2',  		'description' => __( 'Левая колонка в футере сайта', 'fwbs' ),  		'before_widget' => '<aside id="%1$s" class="widget %2$s">',  		'after_widget' => '</aside>',  		'before_title' => '<h4 class="widget-title">',  		'after_title' => '</h4>',  	) );  }  add_action( 'widgets_init', 'fwbs_widgets_init' );

Разбираю вышепреведенный код для создания сайдбаров WordPress

Тут не так все сложно, как на первый взгляд кажется.

  • 'name' => __( 'Правая колонка', 'fwbs' ) — название зоны виджетов, можете писать любое название, только аккуратно между скобками, смотрите на скрине видно, где оно выводится;
  • 'id' => 'sidebar-1' — ID уникальный идентификатор, присваиваемый сайдбару, у всех сайдбаров должен быть свой, отличный от других ID;
  • 'description' => __( 'Правая боковая колонка', 'fwbs' ) — описание, аналогично названию зоны виджетов;
  • 'before_widget' => '<aside id="%1$s" class="widget %2$s">' — HTML тег открывающий сайдбар, обозначающий начало зоны сайдбара, плюс к которому присваивается динамически класс widget;
  • 'after_widget' => '</aside>' — закрывающий зону сайдбара HTML тег. Как мы знаем, что все HTML теги, за некоторым исключением должны быть парными (открывающий и закрывающий);
  • 'before_title' => '<h4 class="widget-title">' — заголовок виджета будет обернут в тег H4 с классом <h4 class="widget-title">, можно менять значимость заголовка H1, H2, H3, H4, H5, H6 и присваивать свои классы;
  • 'after_title' => '</h4>' — закрывающий </h4> парный тег для заголовка виджета.

Теперь заходим в адмику, в раздел «виджеты» и смотрим результат. Вот картинка того, что получилось у меня:

Создание сайдбара WordPress

Данным кодом я зарегистрировал две зоны виджетов WordPress, теперь нужно вывести их на экран.

Вывод сайдбаров WordPress

Чтобы вывести сайдбары в любом месте шаблона, логично в нужном месте прописать следующий код:

 <?php if ( is_active_sidebar( 'sidebar-1' ) ) : ?>      <?php dynamic_sidebar( 'sidebar-1' ); ?>     <?php endif; ?>

Немного пояснений по коду:

  • <?php if ( is_active_sidebar( 'sidebar-1' ) ) : ?> — PHP код, который дает команду, если в сайдбаре под id=sidebar-1 находятся виджеты, то его нужно выводить на экран, если виджетов нет, сайдбар не выводится;
  • <?php dynamic_sidebar( 'sidebar-1' ); ?> — PHP код вызывающий сайдбар под id=sidebar-1 в месте, где вы его прописали в коде шаблона.

Но как можно заметить, в шаблонах WordPress код вывода сайдбаров размещают в отдельных файлах sidebar.php, а потом уже выводят контент из файла sidebar.php в нужном месте шаблона. Как мы знаем, что WordPress выводит контент динамически и шаблон сайта состоит из нескольких частей, то одной из его частей является файл sidebar.php Давайте я так и сделаю.

Создание файла sidebar.php

Создайте файл, например sidebar-right.php, задайте ему заголовок, и вставьте в него вышеприведенный код. Все вместе это будет выглядеть таким образом:

<?php  /**   * The sidebar containing the right widget area   */  ?>   <div class="right-sidebar">   <?php if ( is_active_sidebar( 'sidebar-1' ) ) : ?>     <div id="secondary" class="widget-area">   <?php dynamic_sidebar( 'sidebar-1' ); ?>   </div>     <?php endif; ?>   </div>

Как видно из примера, я дополнил код дополнительной HTML разметкой. Теперь, чтобы вывести зону виджетов, в нужном месте остается прописать следующее:

<?php get_sidebar( 'right' ); ?>

Для левой боковой колонки соответственно создается файл sidebar-left.php и в нужном месте шаблона выводим так:

<?php get_sidebar( 'left' ); ?>

Как говорится, найдите в коде одно отличие.

Все, сайдбары созданы, теперь осталось дело за малым, создать для них в шаблоне разметку и прописать стили CSS.

svsites.ru

Everyone who is building WordPress Themes probably implement the widget function in their theme. Code for the widgets is in functions.php. Here a code snippet of the default theme:

  if ( function_exists('register_sidebar') )   register_sidebar(array(   'before_widget' => '<li id="%1$s" class="widget %2$s">',   'after_widget' => '</li>',   'before_title' => '<h2 class="widgettitle">',   'after_title' => '</h2>',   ));  

As we all know, there is the function register_sidebar since version 2.2. My question is: How long do you want to ask if this function exists? The default theme of WordPress 2.7 doesn’t ask, if have_comments (a new template tag of version 2.7) exists, but it asks if register_sidebar exists. I just suppose the developers just forgot it and everybody in the world thinks, that it has to be like that.

Please don’t misunderstand, the query isn’t wrong, but in my opinion just useless in the default theme of version 2.7

Since we are already talking about the register_sidebar and it’s use, the code of a premium theme uses this query even 3 times:

  <?php  if ( function_exists('register_sidebar') )  register_sidebar(array('name'=>'Home Sidebar',  'before_widget' => '<div class="block">',  'after_widget' => '</div><div class="blockfooter"></div>',  'before_title' => '<h3>',  'after_title' => '</h3>',  ));  ?>  <?php  if ( function_exists('register_sidebar') )  register_sidebar(array('name'=>'Post Sidebar',  'before_widget' => '<div class="block">',  'after_widget' => '</div><div class="blockfooter"></div>',  'before_title' => '<h3>',  'after_title' => '</h3>',  ));  ?>  <?php  if ( function_exists('register_sidebar') )  register_sidebar(array('name'=>'Page Sidebar',  'before_widget' => '<div class="block">',  'after_widget' => '</div><div class="blockfooter"></div>',  'before_title' => '<h3>',  'after_title' => '</h3>',  ));  ?>  

This is not really a good example for a premium theme. First, why closing the PHP tag after every function and open it before every function again?
Second, if the function register_sidebar exist in first place, it will also exist the 2nd time
and third, the code is almost identical except the name of the sidebar. That could be done much easier:

  <?php  $sidebars = array('Home Sidebar', 'Post Sidebar', 'Page Sidebar');  foreach($sidebars as $sb) {  	register_sidebar(array('name'=> $sb,  		'before_widget' => '<div class="block">',  		'after_widget' => '</div><div class="blockfooter"></div>',  		'before_title' => '<h3>',  		'after_title' => '</h3>',  	));  }  ?>  

As I said, it’s not wrong and I didn’t mean it as it is a bad way to code, but sometimes you can do it much easier ?

wpengineer.com


You May Also Like

About the Author: admind

Добавить комментарий

Ваш e-mail не будет опубликован. Обязательные поля помечены *

Этот сайт использует Akismet для борьбы со спамом. Узнайте, как обрабатываются ваши данные комментариев.