Skip to content

Instantly share code, notes, and snippets.

@colorful-tones
Created June 11, 2013 14:46
Show Gist options
  • Save colorful-tones/5757462 to your computer and use it in GitHub Desktop.
Save colorful-tones/5757462 to your computer and use it in GitHub Desktop.
Conditional sidebar logic for WordPress page. http://stackoverflow.com/questions/10486895/wordpress-conditional-sidebar-section-based-off-of-page-id conditional logic for custom sidebar… place it in page.php or even index.php to replace get_sidebar()
<?php
// make sure any child pages inherit sidebar properties
$ancestors = array_reverse(get_ancestors(get_the_ID(), 'page'));
$top_page = $ancestors ? get_page($ancestors[0]) : get_page(get_the_ID());
/*
check to see if a custom sidebar exists for our page based on
the page's slug, like a page named "About Us" would have sidebar-about-us.php
*/
if(locate_template('sidebar-'.$top_page->post_name.'.php'))
{
get_sidebar($top_page->post_name);
}
// if no custom page sidebar then just display the regular sidebar.php
else
{
get_sidebar();
}
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment