How to create a widget area in your WordPress theme

The following steps detail how to create a new widget area in your WordPress theme.

The widget area will appear under your ‘Appearance’ -> ‘Widgets’ page in the WordPress administration, and you’ll be able to add any widget to the space.

Step 1: Create the widget area

To make the widget area display in the WordPress administration you will need to register it using the ‘widgets_init’ action.

The following code can be used to create a widget area called ‘Below article’. Simply add it to your themes functions.php file, below the opening <?php line.

You can customise the code to control what HTML is included before and after the content and title.

add_action('widgets_init', 'itsg_register_below_article_widget' );
function itsg_register_below_article_widget() {
register_sidebar(array(
        'id' => 'below_article_widget',
        'name' => 'Below article',
        'before_widget' => '<div id="%1$s" class="below-related row widget %2$s"><div class="widget-section">',
        'after_widget' => '</div></div>',
        'before_title' => '<h3 class="widget-title">',
        'after_title' => '</h3>',
    ));
}

Step 2: Insert the widget area in the theme

Now you need to add the widget area to the theme’s template files.

Exactly how to do this depends completely on how your theme has been written.

You will need to add the following code to where you want the widget area to be displayed. This is PHP code – therefore you most probably need to wrap it in an open and close PHP code, e.g. <?php CODE ?>

If the area is already inside the PHP code, you do not need to include these.

<?php dynamic_sidebar('below_article_widget');  ?>

Step 3: Add your widgets to the widget area

Now log into your WordPress administration and add your widgets to the widget area.

If you found the right spot in step 2 the widgets will display correctly.

Note – if you are creating the widget area in the page and post area, or near it – your theme will have a different files for posts and pages. So you will need to repeat step 2 for each of these files. A little bit of trial and error and you’ll find it.

WordPress-CreateWidgetArea1