As you start building your own WordPress themes, at some point you are likely going to want to include a sidebar in your design/development. Adding a side bar involves a few lines of code, but is very straightforward. It is also important to note that in the WordPress world, adding a sidebar and creating a widget area are the same thing, so you can use the example code below for both.So lets get started.
the first thing you are going to want to do is open your functions.php page. If you don’t have one, then you will need to create one in the root of your themes directory.Once you have the file open this is the code you want to add:
'name' => ‘Sidebar’,
'id' => ‘sidebar’,
'before_widget' => '',
'after_widget' => '',
Note: If you created a new functions.php page for this, don’t forget to include an opening php tag (<?php ) at the top of the page.
Lets go over the code line by line to make sure you have a good understanding of what you are using.
function function_name($id)- This line is the opening declaration of the function. It also names the function and passes an argument of $id.
register_sidebar( array – This tells WordPress that you want to register a sidebar and are going to pass an array of values.
‘name’ =>’Sidebar’ – this is the name of the sidebar as it will appear in your widget area in the backend of WordPress. you can name it anything you like, I just used ‘Sidebar’ for simplicity sake.
‘id’=> – this is the Sidebar id -it must be all in lowercase, with no spaces.
‘before_widget’=>- this is where you put your code that you want to appear before the widget. For example, you may want the sidebar within an <aside> tag and have some CSS classes added to that tag.
‘after_widget’ => – this is where you would close the tags you opened in the previous line
‘before_title’=>– similar to the before_widget line, this is where you would add any HTML code that you wanted to appear before the title of the widget. Lots of times this is used to add a heading tag to the title
‘after_title’=>- typically used to close the tags opened in “before_title”.
Once you have created the function above, you will then need to add the add_action hook to your code. This tells WordPress that the code is to be executed at this point.
Adding the sidebar to the page
Now that we have that down , we are halfway home. We still need to add the code for the sidebar to appear on our page. Here is what that code looks like.
<?php if (is_active_sidebar('sidebar')):?>
The first line of this block of code looks for the sidebar code and the second line then tells WordPress to display the sidebar with the id of ‘sidebar’.
And just like that you have a sidebar ready to go!If you go to Appearance >> Widgets you should see your new sidebar there waiting to be populated.
Questions? Leave them in the comments section below.