WordPress Register Sidebar

A sidebar is a widget area in your theme. It does not have to be at the side of the page: header, footer and many other places can be sidebars. You register the area in functions.php, and then show it in a template file.

Register a sidebar

<?php
function tc_register_sidebars() {
	register_sidebar( array(
		'name'          => 'Main Sidebar',
		'id'            => 'sidebar-main',
		'description'   => 'Widgets in this area show on the right of the blog.',
		'before_widget' => '<section id="%1$s" class="widget %2$s">',
		'after_widget'  => '</section>',
		'before_title'  => '<h3 class="widget-title">',
		'after_title'   => '</h3>',
	) );
}
add_action( 'widgets_init', 'tc_register_sidebars' );

The parameters

ParameterMeaning
nameThe name shown in the dashboard
idA unique ID, in small letters, used in the code. Never change it later
descriptionHelp text in the widgets screen
before_widget, after_widgetHTML around each widget. %1$s is the widget ID, %2$s the widget class
before_title, after_titleHTML around the widget title

Show the sidebar in a template

<?php get_header(); ?>
<main>
	<!-- the loop here -->
</main>
<?php get_sidebar(); ?>
<?php get_footer(); ?>

is_active_sidebar() checks if the area has some widgets, so an empty box is not printed. Let us check the registered areas and put a search and a recent posts widget in it:

Terminal output

$ wp sidebar list –fields=name,id
name id
Main Sidebar sidebar-main
Inactive Widgets wp_inactive_widgets
$ curl -s http://example.com/ | grep -c "<aside>"
1
$ wp widget add search sidebar-main 1 –title="Find posts"
Success: Added widget to sidebar.
$ wp widget add recent-posts sidebar-main 2 –title="Latest posts" –number=2
Success: Added widget to sidebar.
$ wp widget list sidebar-main –fields=name,id,position
name id position
search search-1 1
recent-posts recent-posts-1 2
block block-2 3
block block-3 4
block block-4 5
block block-5 6
block block-6 7
$ curl -s http://example.com/ | grep -o 'widget-title">[^<]*'
widget-title">Find posts
widget-title">Latest posts

The first grep -c gave 1, not 0. This is because a fresh WordPress site comes with some default widgets, and WordPress moves them to the first sidebar of a new theme. In the list you can see them after ours (the block items). The last command shows the titles of our two widgets, printed with the HTML we wrote in register_sidebar().

Where to manage it

In a classic theme, the new area appears in Appearance > Widgets. Block themes do not use sidebars, they use template parts, as you see in Block Themes.

Note: Register more than one sidebar when you need different widgets on blog pages, shop pages and the footer. Use an array in register_sidebars( 3, ... ) to make several areas in one call. Next: Register Navigation Menus.

Congratulations! Chapter Finished. Learn more about the similar topics:
Exercises & Assignments
No Content Found.
Interview Questions & Answers
No Content Found.