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:
- Open page.php or single.php file
- Find the following code: <?php get_sidebar(); ?>
- Replace the code with this one:
- Save changes
- Create a custom template where your sidebar will be
- Open the sidebar.php file
- Copy everything from sidebar.php and paste into your custom template file
- Save changes.
<?php $sidebar = get_post_meta($post->ID, "sidebar", true); get_sidebar($sidebar); ?>
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:
- Type “sidebar” under the name of your custom field
- 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.