Friday, July 17, 2015

Wordpress : Adding Multiple Sidebars

Sidebars are great because they allow us to display a lot of useful info, such as related posts, author info, a blog roll, ad spaces and so on. But sidebars can quickly become very busy, and readers may be hard-pressed to find what they’re looking for. So, what about having different sidebars available and displaying the most appropriate one for the post?
The solution.
To apply this hack, duplicate your sidebar.php file and fill it with whatever information we would like to appear. Save the file as sidebar-whatyouwant.php.
Once that’s done, open single.php* file and find the call to theget_sidebar() function:
<?php get_sidebar(); ?>
Replace it with:
<?php $sidebar = get_post_meta($post->ID, "sidebar", true);
get_sidebar($sidebar);
?>
Now when we write a post, create a custom field named sidebar. Set its value as the name of the sidebar that you want to include. For example, if its value isright, WordPress will automatically include sidebar-right.php as a sidebar.

If no custom sidebar field is found, WordPress automatically includes the default sidebar.
*The same can be done with page.php.
This trick is quite simple. The first thing we did was look for a custom field namedsidebar and get its value as a variable. Then, the variable is used as a parameter for the WordPress function get_sidebar(), which allows us to specify a particular file to use as a sidebar.

No comments:

Post a Comment