Display WordPress Widgets Conditionally in Particular Pages

By . Filed in Wordpress

If you are using WordPress, you can add additional content in the sidebar using widgets. WordPress, by default, provides a set of widgets for showing post categories, tag clouds, search, and calendar. Following WordPress standard themes like TwentyTen and TwentyTwelve, widgets will be shown in all the pages — homepage, post, page, and archive.

But what if we want to display the widgets only in one particular page. Let’s take a look at our options for this.

Different Sidebar File

A WordPress theme requires sidebar.php file to hold the widgets, and uses get_sidebar() template tag to display the widgets on the pages.

We can create multiple customized sidebar files to display in the theme template files.

For example, let’s say we have a Contact page, and we want to have the sidebar in this page to be different from the sidebar of other pages. In this situation, we can create a new sidebar file, and name it something like sidebar-contact.php.

Then, in the contact template file, we can call our new sidebar, this way.

get_sidebar( 'contact' );

Everything that is added in the Contact sidebar will be displayed in the Contact page, and won’t be displayed in the other pages. That way that we can display widgets that are more related to the page.

Using Conditional Tags

The above method assumed that you have created a custom template for your page. Alternatively, if you haven’t created one, you can use conditional tags.

Below is an example of code that you can add in page.php; this code will show the Contact sidebar in the contact page, while showing regular sidebars for the other pages.

if ( is_page('contact') ) {
	get_sidebar( 'contact' );
} else {
	get_sidebar();
}

Using Jetpack

Alternatively, you can also do it from the back-end admin with Jetpack. In Jetpack, activate the module called Widget Visibility. With this module, we can hide or show widgets for certain pages.

Go to Appearance > Widgets. You should now find a new button added in the widget named Visibility. Click on the button and set the parameters.

In the above example, I have set a widget that will only show in the Contact page. Apart from Pages, you can also select Categories, Tags, and Posts.

We hope this tip can be useful for you and if you have any question regarding this discussion, feel free to ask in the comment box below.

Author:

Thoriq has been dabbling in Web Design for 5 years and appreciates the giving nature of the web design community at large. He loves trying new things in CSS3 and HTML5. Apart from writing on hongkiat.com he also maintains creatiface.

Advertisement

Comments are closed. Contact Us.