Skip to content

Instantly share code, notes, and snippets.

@BinaryMoon
Created May 15, 2015 14:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save BinaryMoon/4101493b2bd6215cbcd7 to your computer and use it in GitHub Desktop.
Save BinaryMoon/4101493b2bd6215cbcd7 to your computer and use it in GitHub Desktop.
Dynamically create sidebars based upon page templates being used.
<?php
/**
* Dynamically register sidebar for pages that use specified template
*/
function showcase_register_page_sidebars() {
// Find all pages that use template with dynamic sidebar
// ideally this would be done in the admin only since it's creating an additional query that's not needed on most pages
$query = new WP_Query( array(
'meta_key' => '_wp_page_template',
'meta_value' => 'page-templates/widgets.php',
'post_type' => 'page',
'nopaging' => true,
) );
while ( $query->have_posts() ) {
$query->the_post();
showcase_register_sidebar( showcase_sidebar_id(), get_the_title() );
}
wp_reset_postdata();
}
add_action( 'widgets_init', 'showcase_register_page_sidebars' );
/**
* Get the sidebar id
* can also be used in templates
* eg: dynamic_sidebar( showcase_sidebar_id() )
*
* @param type $id
* @return boolean
*/
function showcase_sidebar_id( $id = null ) {
if ( ! $id ) {
$id = get_the_ID();
}
if ( $id ) {
return sprintf( 'showcase-%d-sidebar', get_the_ID() );
}
return false;
}
/**
* global location for registering widgets
*
* @global type $wp_registered_sidebars
* @param type $id
* @param type $title
*/
function showcase_register_sidebar( $id = null, $title = '' ) {
global $wp_registered_sidebars;
$id = showcase_sidebar_id( $id );
if ( ! isset( $wp_registered_sidebars[ $id ] ) ) {
register_sidebar( array(
'name' => sprintf( __( '%s Sidebar', 'showcase' ), $title ),
'id' => $id,
'description' => sprintf( __( 'Widgets for %s', 'showcase' ), $title ),
'before_widget' => '<div id="%1$s" class="%2$s">',
'after_widget' => '</div>',
'before_title' => '<h3 class="widget-title">',
'after_title' => '</h3>',
) );
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment