Show sidebar by using custom fields

A sidebar was introduced in WordPress version 2.2. Since then, it has become a popular way of showing extra content and more often than not, themes will have one by default where you can place any widgets you want.

Although very useful, you don’t want your sidebar to be present everywhere. Usually, these bars are shown anywhere but the home page. And there is no such option to easily turn the sidebar on and off.

So, why not make it yourself. In this article, we will show you how to put your sidebar into custom field and call it only for post you want.

Prepare the template:

  1. Open page.php or single.php file
  2. Find the following code: <?php get_sidebar(); ?>
  3. Replace the code with this one:
  4. <?php $sidebar = get_post_meta($post->ID, "sidebar", true);
    get_sidebar($sidebar);
    ?>
    
  5. Save changes
  6. Create a custom template where your sidebar will be
  7. Open the sidebar.php file
  8. Copy everything from sidebar.php and paste into your custom template file
  9. Save changes.

Now you have to open a post or a page where you can find “custom fields” under the Text/Visual Editor. To add a sidebar to that post/page, do the following.

Using the sidebar in custom fields:

  1. Type “sidebar” under the name of your custom field
  2. Type the name of your custom template as a field value

That’s it. If you have left your custom fields empty, your post will be without sidebar while in the other case, your sidebar should load if you have done everything correctly.

START YOUR OWN BLOG

This guide is an introduction to mastering the art of blogging. It provides easy to follow steps to start, maintain, and grow your blog.

Read the guide

Leave a Reply

Your email address will not be published. Required fields are marked *