How to add sidebar to wordpress theme for widgets – tutorial

In this post you will learn how to add a sidebar to wordpress theme so that you can add widgets to that area.

How to add sidebar to wordpress theme

You will be able to control this theme on the wordpress backend (in widgets panel) and will also learn how to show this sidebar on the front end while developing your theme (or modifying it to add a second sidebar to wordpress theme)

1. Registering your sidebar

We will be adding code for registering our sidebar for the current wordpress theme by adding some code to the functions.php file.

If you don’t have a functions.php file already create one and paste this code in it:

if ( function_exists('register_sidebars') )

Note that I used the number “2” while registering the sidebar. You can change it to any number of sidebars you want for your current wordpress theme.

Save functions.php file. We’re done with it now.

2. Creating sidebar file

Although you can add the sidebar code within your index file too but it’s not a good practice.

Create a separate file named sidebar.php to add sidebar code to it.

If you’re planning to have more than 1 sidebars it’s good to give a descriptive name to them (like sidebar_left.php)

The code that has to be added to the sidebar.php file is this:

<div class="sidebar">
<?php if ( function_exists('dynamic_sidebar') && dynamic_sidebar(2) ) : else : ?>
show this if no widget found for this position
<?php endif; ?>

Lets evaluate this code now.

First we start a div with any class we want. Then a UL (normal html going on, you can figure it out and modify it as you want)

Lets jump to the php part.

In the first line, it checks if dynamic sidebars are available for our wordpress theme. If yes, then it searches for the 2nd sidebar (you can change the name of the sidebar as per requirement).

third, we can anything else we want incase no sidebar is found or no widget is available for this sidebar yet (this is optional btw!)

Thats not all, one step is left!

3. Include sidebar.php to the main files

Once our sidebar.php file is ready, it’s time to call it in our normal theme by including it to the code.

Add this code where you want this sidebar to appear on various files (index.php, single.php, etc)

<?php include (TEMPLATEPATH . '/sidebar.php'); ?>

That’s all! we’re done now. Test your code and confirm it’s working fine.

Let me know if you have any queries or difficulties while adding sidebars to your wordpress theme.

Leave a Reply

Your email address will not be published.