Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /*
- This code generates a custom sidebar for each instance of a WordPress page using a particular page template. This is useful if you want certain pages with a specific layout to be controlled partially by widgets. This is particularly useful if you don't know which and how many pages will use that template when building the theme.
- Snippet by Mark Root-Wiley of MRW Web Design, mrwweb.com
- Note: This script works but hasn't been tested on a live, frequently used site yet. Consider it a beta. Use at your own risk and please let me know how it might be improved!
- */
- // This single line of code goes in your template file to generate the sidebar contents
- if ( function_exists( 'dynamic_sidebar' ) && dynamic_sidebar( 'template-sidebar-' . get_the_id() ) );
- // The remaining code goes in your functions.php file to generate the individual sidebars. (It's theme-specific so I'm not putting it in a functionality plugin.)
- // Use WP_Query to loop through all pages using a certain template file
- $my_template_sidebars = new WP_Query( array(
- 'post_type' => 'page', // you might want to support custom post types, but I don't
- 'post_status' => array( 'publish', 'pending', 'draft', 'future', 'private' ), // make sure that pages remain available for widgets even if they're on currently unpublished pages, this list might deserve tweaking in certain instances
- 'meta_query' => array( array(
- 'key' => '_wp_page_template',
- 'value' => '[THE NAME OF YOUR TEMPLATE FILE].php',
- 'compare' => '='
- )),
- 'orderby' => 'title'
- )
- );
- // the loop using above WP_Query object
- if ( $my_template_sidebars->have_posts() ) : while ( $my_template_sidebars->have_posts() ) : $my_template_sidebars->the_post();
- register_sidebar( array(
- 'name' => get_the_title() . ' Sidebar',
- 'id' => 'template-sidebar-' . get_the_ID(),
- 'description' => 'A sidebar for the "' . get_the_title() . '" page.'
- 'before_title' => '<h2 class="widget-title">',
- 'after_title' => '</h2>',
- 'before_widget' => '<section id="%1$s" class="widget %2$s">', // I put my widgets in an <aside>, each widget as a section
- 'after_widget' => '</section>'
- )
- );
- endwhile; endif;
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement