Advertisement
mrwweb

WordPress Page Template-Triggered Sidebars

Feb 13th, 2012
103
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 2.13 KB | None | 0 0
  1. /*
  2. 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.
  3. Snippet by Mark Root-Wiley of MRW Web Design, mrwweb.com
  4. 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!
  5. */
  6.  
  7. // This single line of code goes in your template file to generate the sidebar contents
  8.  
  9. if ( function_exists( 'dynamic_sidebar' ) && dynamic_sidebar( 'template-sidebar-' . get_the_id() ) );
  10.  
  11.  
  12. // 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.)
  13.  
  14. // Use WP_Query to loop through all pages using a certain template file
  15. $my_template_sidebars = new WP_Query( array(
  16.     'post_type' => 'page', // you might want to support custom post types, but I don't
  17.     '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
  18.     'meta_query' => array( array(
  19.         'key' => '_wp_page_template',
  20.         'value' => '[THE NAME OF YOUR TEMPLATE FILE].php',
  21.         'compare' => '='
  22.     )),
  23.     'orderby' => 'title'
  24.     )
  25. );
  26. // the loop using above WP_Query object
  27. if ( $my_template_sidebars->have_posts() ) : while ( $my_template_sidebars->have_posts() ) : $my_template_sidebars->the_post();
  28.  
  29. register_sidebar( array(
  30.         'name' => get_the_title() . ' Sidebar',
  31.         'id'   => 'template-sidebar-' . get_the_ID(),
  32.         'description'   => 'A sidebar for the "' . get_the_title() . '"  page.'
  33.         'before_title' => '<h2 class="widget-title">',
  34.         'after_title' => '</h2>',
  35.         'before_widget' => '<section id="%1$s" class="widget %2$s">', // I put my widgets in an <aside>, each widget as a section
  36.         'after_widget' => '</section>'
  37.     )
  38. );
  39.  
  40. endwhile; endif;
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement