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
| Parameter | Meaning |
|---|---|
| name | The name shown in the dashboard |
| id | A unique ID, in small letters, used in the code. Never change it later |
| description | Help text in the widgets screen |
| before_widget, after_widget | HTML around each widget. %1$s is the widget ID, %2$s the widget class |
| before_title, after_title | HTML 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:
$ 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.
| Exercises & Assignments |
|---|
| No Content Found. |
| Interview Questions & Answers |
|---|
| No Content Found. |