Skip to content

Instantly share code, notes, and snippets.

@bradpotter
Last active August 29, 2015 14:21
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bradpotter/aba08b6fee42857ca7d6 to your computer and use it in GitHub Desktop.
Save bradpotter/aba08b6fee42857ca7d6 to your computer and use it in GitHub Desktop.
Register a sidebar for a page that has a page template selected
add_action('widgets_init', 'gpb_register_sidebar');
/**
* Dynamically register sidebar for pages that use specified template
*
*/
function gpb_register_sidebar() {
global $post;
global $wp_registered_sidebars;
// Find all pages that use template with dynamic sidebar
$query = new WP_Query(array(
'meta_key' => '_wp_page_template',
'meta_value' => '^widget-template',
'meta_compare' => 'REGEXP',
'post_type' => 'page',
'nopaging' => true,
'orderby' => 'title',
'order' => 'ASC',
));
while ($query->have_posts()) {
$query->the_post();
$id = "gpb-{$post->ID}-sidebar";
if (!isset($wp_registered_sidebars[$id])) {
register_sidebar( array(
'name' => $post->post_title . ' Sidebar',
'id' => $id,
'description' => 'Sidebar widgets for ' . $post->post_title,
'before_widget' => '<div class="content-widget widget-area"><div class="wrap"><div id="%1$s" class="%2$s">',
'after_widget' => '</div></div></div>',
'before_title' => '<h4 class="widget-title" itemprop="headline">',
'after_title' => '</h4>',
) );
}
}
wp_reset_postdata();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment