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:

<?php
// 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);
?>