Multiple Dynamic Sidebars

Filed under code, geek
Tagged as , ,

Sidebar.php

<?
        ###
        # Get page slug
        ###
        $slug = split('/', get_permalink());
        ###
        # Example $slug http://somedomain.com/folder/subfolder/contact-us/
        # we want contact-us so we'll use $slug[5]
        # Array ( 
        #        [0] => http: 
        #        [1] => 
        #        [2] => somedomain.com 
        #        [3] => folder 
        #        [4] => subfolder 
        #        [5] => contact-us 
        #        [6] => )
        ###

        $slug = $slug[5]; ## Change the number to match the last part of the url, see example array above

        ###
        # Check for active sidebar matching page $slug and make sure its not the front page
        ###
        if ( is_active_sidebar( 'sidebar-'.$slug ) && !is_front_page() ) { ?>
            <div id="tertiary" class="widget-area" role="complementary"> 
                <?php dynamic_sidebar( 'sidebar-'.$slug ); ?>
            </div><!-- #tertiary .widget-area -->
        <? } else { ?>
            <div id="tertiary" class="widget-area" role="complementary">
                <?php dynamic_sidebar( 'sidebar-1' ); ?>
            </div><!-- #tertiary .widget-area -->
        <? } ?>

Functions.php

function toolbox_widgets_init() {
    register_sidebar( array(
        'name' => __( 'Sidebar 1', 'toolbox' ),
        'id' => 'sidebar-1',
        'before_widget' => '<aside id="%1$s" class="widget %2$s">',
        'after_widget' => "</aside>",
        'before_title' => '<h1 class="widget-title">',
        'after_title' => '</h1>',
    ) );
 
    register_sidebar( array(
        'name' => __( 'News', 'toolbox' ),
        'id' => 'sidebar-news',
        'description' => __( 'An optional second sidebar area', 'toolbox' ),
        'before_widget' => '<aside id="%1$s" class="widget %2$s">',
        'after_widget' => "</aside>",
        'before_title' => '<h1 class="widget-title">',
        'after_title' => '</h1>',
    ) );
}
add_action( 'widgets_init', 'toolbox_widgets_init' );

This script looks for a sidebar matching the page slug of the current viewed page. Add new sidebars to match the scheme sidebar-SLUG in toolbox_widgets_init then create a post/page with a matching slug. done.

Post a Comment

Your email is never published nor shared. Required fields are marked *

*
*