If you have been using WordPress, you probably have noticed that WordPress displays the same sidebar all across the site for most themes unless the designer himself created a custom homepage in which case the sidebar will be displayed on all pages but the homepage. In this article we will share a tutorial that will give you the option to choose a different sidebar to be displayed for each post and page for WordPress. This is an excellent snippet to bookmark for all WordPress theme designer and other users who would like to add this functionality.
This tutorial will combine the use of Custom Fields and the ability to call specific php templates. Therefore this tutorial has a prerequisite:
You must have basic knowledge of HTML and CSS in order for you to create a separate template.
You will need to open your single.php and/or page.php and find the following code:
<?php get_sidebar(); ?>
Replace the above code with this:
<?php $sidebar = get_post_meta($post->ID, “sidebar”, true);
Now when you are writing a post or a page, and you want to display a custom sidebar all you need to do is add the custom field “Sidebar” and include the name of the sidebar file. For example if you insert “wpbpage”, it will display sidebar-wpbpage.php as your sidebar.
You must have the file already in place to call it from a specific post. This trick is mostly used in larger magazine style sites, but it is commonly used for custom pages also. One of the easiest way to start out creating a new sidebar file is copying your sidebar.php codes into this new file and edit/add the codes that you want.
We will be covering a few more sidebar hacks, so stay updated if you want to know more about WordPress Sidebars.
Note: If you want to display this code outside the loop, then you need to see our tutorial on how to display custom fields outside the loop.