20 May 2012 ~ 0 Comments

How to Create a Conditional Sidebar in WordPress

Wordpress allows you to change the ‘template’ based on what is being viewed. You can set a specific piece of content (a page or post) to use a certain template (instead of the default) and then customize it accordingly. Otherwise you can just alter your theme to display a sidebar based on a certain condition. I think the second method is probably easier so I’ll show you how to do that.

Add a Sidebar

To do this, it’s smart to create a configurable sidebar in your theme. Go into your theme’s functions.php file and add something like this:

register_sidebar( array(
'name' => __( 'Diablo 3 Sidebar', 'twentyeleven' ),
'id' => 'diablo3',
'description' => __( 'This sidebar is displayed when Diablo 3 content is being presented', 'twentyeleven' ),
'before_widget' => '<div id="%1$s">',
'after_widget' => '</div>',
'before_title' => '<h3>',
'after_title' => '</h3>'
) );

Now the sidebar is created and you can go to Appearance -> Widgets and add Widgets into this new sidebar. These widgets might be a custom Diablo 3 menu or a custom Diablo 3 ad. It will look like this in the Appearance->Widgets admin menu. You should populate it with some widgets specific to this categories content.

Diablo 3 Sidebar

Display the sidebar based on a specific condition

Next you’ll want to modify your theme so that when it goes to display the default┬ásidebar it says, “which sidebar should I display?” and then displays the one based on … whatever. This will depend greatly on the theme that you’re using. In TwentyEleven the sidebar is generated inside sidebar.php.

The original sidebar.php uses an if statement to display the sidebar, which is called sidebar-1, and if it fails to display it displays the default archive and meta widgets. Above that, I used in_category(‘diablo3’) to determine if the content was in the diablo3 category. If it is, display the diablo3 sidebar with dyanmic_sidebar(‘diablo3’) and then if it was not, execute the default code.

You could use any condition here, you could see if the user is an admin, if the post is X days old, etc. Here is the modified section in sidebar.php (keep in this this is only for the twentyeleven theme).

<div id="secondary" class="widget-area" role="complementary">

<?php if (in_category('diablo3')): ?>

<?php dynamic_sidebar('sidebar-1'); ?>

<?php else: ?>

<?php if ( ! dynamic_sidebar( 'sidebar-1' ) ) : ?>

<aside id="archives" class="widget">
<h3 class="widget-title"><?php _e( 'Archives', 'twentyeleven' ); ?></h3>
<?php wp_get_archives( array( 'type' => 'monthly' ) ); ?>

<aside id="meta" class="widget">
<h3 class="widget-title"><?php _e( 'Meta', 'twentyeleven' ); ?></h3>
<?php wp_register(); ?>
<li><?php wp_loginout(); ?></li>
<?php wp_meta(); ?>

<?php endif; // end sidebar widget area ?>

<?php endif; ?>

</div><!-- #secondary .widget-area -->


Leave a Reply