Different Sidebar Content on Different Pages in WordPress

Ok, this is an old one and easy to do these days with free WordPress plugins but here’s an alternative method of having different sidebar content on different pages in WordPress. It involves a little bit of adjusting of the default sidebar.php template file. I’m using the sidebar template from the default Twenty¬†Twelve¬†theme here.

Here’s the edited code:

<?php if ( is_active_sidebar( 'sidebar-1' ) ) : ?>
<div id="secondary" class="widget-area" role="complementary">
<?php if ( is_page('home') ) { echo "Home Page sidebar content'";
} elseif ( is_page('about') ) { echo "About Page sidebar content'";
} elseif ( is_page(contact') ) { echo "Contact Page sidebar content'";
} else { dynamic_sidebar( 'sidebar-1' );
} ?>
</div><!-- #secondary -->
<?php endif; ?>

Basically, what the above code does is tells WordPress via some if/else PHP statements to show different content depending on which page you’re on and if you are not on any of the pages mentioned, just show the default sidebar. The “if is page” bit can be the Page ID, Slug or Full name. I’ve used slugs in the example above. You need to get the spellings exactly right.