How to Display Different Sidebar Widgets for Different Pages in WordPress

On 30 May, 2014 By With 1 Comment

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

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 How to Display Different Sidebar Widgets for Different Pages in Wordpress

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.

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!

Leave a Reply