WordPress: Using dynamic sidebars instead of page templates

If one of your WordPress pages requires a special sidebar, you can create a special page template for that page. But it can be much more efficient to just create a dynamic sidebar just for this page.

A Trade Show Example

In this example, a “Trade Shows” page requires a sidebar of special advertisers that do not appear on other pages.

Modify the page template with an “if” statement

In the page template where you would normally place the sidebar, in this case, the left sidebar, modify the code to:

if ($page_requested=='trade-shows'){
  echo '<div class="widget-area"  >';
  dynamic_sidebar( 'trade-show-banners' );        
  echo '</div>';
else{  get_sidebar( 'left' );

We substitute the “trade-show-banners” dynamic sidebar for the “left” sidebar where the page is “trade-shows”. You can get the current page_requested by using $_SERVER['REQUEST_URI']).

Create the special widget in functions.php

Before you can use this sidebar, you have to first register it in functions.php.

function my_widgets_init() {
register_sidebar( array(
'name'          => 'Trade show Banners',
'id'            => 'trade-show-banners',
'before_widget' => '<div class="trade-show-sponsor">TRADE SHOW SPONSOR</div><aside id="%1$s" class="widget %2$s">',
'after_widget'  => '<hr/></aside>',
'before_title'  => '<h2 class="widget-title">',
'after_title'   => '</h2>',
) );
add_action( 'widgets_init', 'my_widgets_init' );

Handle the widget in the widgets menu

Add whatever banners or other widgets you need to appear in this special sidebar using the standard “Appearance > Widgets”.

Using this technique, easily create as many special purpose sidebars as you need.

Leave a Reply

Your email address will not be published.