How to add WordPress sidebar

There comes a time in every WordPress developer life when he/she needs to add a sidebar. Don’t be afraid, my friend! It’s not as hard as it sounds like ๐Ÿ™‚

To get that done you need functions.php and as many sidebar-<something unique>.php files as you many sidebars you want. All tucked inside your theme folder.

They all can be empty for now. We’ll fill them out soon.

First, functions.php:

<?php
if ( function_exists(‘register_sidebar’) )
register_sidebar(‘left’);
register_sidebar(‘right’);
?>

It means, you check if there exists function: register_sidebar, if exists, register two of them with names ‘left’ and ‘right’. Names should correspond to ‘<something unique>’ part in your sidebar files.

One can use register_sidebars(2) too, but I like this way better.

Now, sidebar files:

For the sake of your users, check (and add if needed) that you have

<?php if ( function_exists(‘dynamic_sidebar’) && dynamic_sidebar(1) ) : else : ?>
<?php endif; ?>

inside your files. Note: change 1 to 2 in secondย  file and so on.

What it does: it tells WordPress to create dynamic sidebars where your user can input widgets using Appearance -> Widgets functionality from WordPress administration panel.

Now, the last leg of your journey: showing the new sidebar.

Standard files, where you may need to add your sidebar: 404.php, archive.php, archives.php, index.php, page.php, single.php and search.php

<?php get_sidebar(‘right’); ?>

Input the above line where you want that sidebar to show (don’t forget to change ‘right’ to ‘<something unique>’ from your sidebar name).

Then you may need to tweak your existing css, to show this new sidebar. Most often, culpit is ‘width’, sometimes ‘float’ tags from your css file.

And, voila: your new sidebar is up and running.