How to Display Different Sidebar Widgets for Different Pages in WordPress

When working on a custom wordpress theme, you might want to display different sidebar widgets on different pages, assuming you want to a separate information displayed on that sidebar. The usual answer is there’s a plugin for that! Although there is, sometimes it’s better to code it rather than relying on a plugin. Especially if you are learning how to create a theme in WordPress.

Today, we will show how you can display different sidebar widgets for different pages in WordPress, and copy the code to be used in your projects.

I needed this feature since I had a Client that wanted to display different sidebar for different pages on this Custom WordPress Theme, I wanted to make it easy for the Client to use, and it doesn’t rely on plugins too. The requirement is that, the page.php will be used to display different pages, with different sidebar widgets.

Lucky for me, I’ve done this on other themes that I’ve worked on. I’ll share with you the code, and hopefully you can take this further.

First, open your functions.php and create additional sidebars

register_sidebar(array(
      'id' => 'about',
      'name' => 'About Sidebar',
      'description' => 'About sidebar.',
      'before_widget' => '<div id="%1$s" class="widget %2$s">',
      'after_widget' => '</div>',
      'before_title' => '<h4 class="widgettitle">',
      'after_title' => '</h4>',
    ));

Create as many as you need, this is just a sample to you. Paste this into your functions.php and remember the ID of the sidebar.

Check out your dashboard > appearance > widgets and see if your widget is there.

wordpress-sidebar

Next, open page.php and let’s find the get_sidebar hook, and add some code. We will use the is_page conditional statement, you can find more on codex about it.

<?php if ( is_page('about-us') ) { ?>
	<?php dynamic_sidebar('about'); ?>
<?php } elseif (is_page('contact-us') ){ ?>
        <?php dynamic_sidebar('about'); ?>
<?php } ?>

Paste this on your page.php, make sure you get the page-slug right “about-us”. Make sure you put it where the proper div for sidebar, or else you’ll get a broken layout in your theme.

Hope this is helpful, if you think there’s more you need or we can push this more, just put it in the comments below!