Define widget area in post or page

Often when building WordPress sites, you build this standard template which you use in most cases. When doing this, the widget area defined in that template will stay the same.

If you want different widget areas depending on what page or post you’re on, the stupid way to solve this matter would be to build a new template just for the case of the sidebar.

Instead of doing that, add a custom field to each post or page you want to have a different sidebar on. Create a custom field with the name sidebar and set the value to whatever your widget area is called, or create the widget areas using this snippet.

This code goes into your template, and not the functions file.

Code Snippet:

// Check if custom field for sidebar is set
if(get_post_meta($post->ID, "sidebar", true)){
	// If set, save it
	$sidebar = get_post_meta($post->ID, "sidebar", true);
else {
	// If not set, default to your standard sidebar
	$sidebar = 'default-sidebar';

// Now echo your sidebar in your template using the $sidebar variable
<?php dynamic_sidebar($sidebar);

Comments  Leave a Reply

Add a Comment

We're glad you have chosen to leave a comment. Please keep in mind that all comments are moderated according to our privacy policy, and all links are nofollow. Do NOT use keywords in the name field. Let's have a personal and meaningful conversation.

WordPress Launch Checklist

The Ultimate WordPress Launch Checklist

We've compiled all the essential checklist items for your next WordPress website launch into one handy ebook.
Yes, Send Me the Free eBook!