Declare Multiple Widgetized Areas

Posted on: March 18, 2010 by Chris Coyier

Have a bunch of different areas you wish to declare as a widgetized area? Save repetative code by creating a quick array of their names, then loop through that array calling the register_sidebar() function on each one. Elementary PHP stuff here, but hey, it just saved me quite a few lines of code in a widget-heavy theme I am working on.

if ( function_exists('register_sidebar') ) {

    $allWidgetizedAreas = array("Homepage Left", "Homepage Right", "Sidebar One", "Movies", "Admin");
    
    foreach ($allWidgetizedAreas as $WidgetAreaName) {
    
        register_sidebar(array(
           'name'=> $WidgetAreaName,
           'before_widget' => '<div id="%1$s" class="widget %2$s left half">',
           'after_widget' => '</div>',
           'before_title' => '<h3 class="widgettitle">',
           'after_title' => '</h3>',
        ));
    
    }

}
Thumb for Declare Multiple Widgetized Areas

Let's talk it out, folks.

  1. Greg said on March 18, 2010:

    You know that is a very simple script but a great idea. Nice work. The result is not just saving you lines of code but saving you time which is important.

    #1
  2. I use this type of trick all the time. I’ve wrapped the loop into a function and tucked in to my standard wp lib. I’ve always wondered why more people don’t use a iterative approach in php/wp development. Thanks for sharing. :)

    #2
  3. While this is pretty cool it doesn’t let you add descriptions to your widgetized areas (which we should all be doing). I personally don’t think it’s really functionally usable on a theme without being able to add descriptions to help the end user know what a sidebar is for.

    #3
  4. Chris said on March 22, 2010:

    Okay, I’ll apologize up front for the noob question, but…would I add this script to index.php? Or sidebar.php? Or…? I’m leaning toward index.php but just not sure.

    #4
  5. Chris said on March 22, 2010:

    Oooh…think I found it…functions.php? Now I just have to figure out how to edit widgets!

    #5
  6. Thanks Chris, saved me tons of time.

    #6
  7. Simply in love with all this.

    #7

Comments are closed. If you have something really important to add, contact us. Thank you!