How to add a new widget area to a WordPress theme

Written by Published on . Filed under Themes.

How to add a new widget area to a WordPress theme

How to add a new widget area to a WordPress theme

If you’ve used WordPress for almost any length of time at all, you’re probably familiar with widgets and sidebars. Sidebars are just areas of your site, that you can add widgets to. And widgets, are drag-and-drop “modules” that add functionality to your site, from displaying recent posts, to displaying meta data, to pulling RSS feeds.

But how exactly to you add new widget area’s to your theme?

That’s a good question, and partly depends on what theme you are using, but the basics go like this:

1. Register a new sidebar (widget area)

In your theme (or child theme, depending…) add the following code to your functions.php file

/**
 * Register widget area.
 *
 * @link https://developer.wordpress.org/themes/functionality/sidebars/#registering-a-sidebar
 */
function theme_prefix_widgets_init() {
    register_sidebar( array(
        'name'          => esc_html__( 'Custom Sidebar', 'theme_name' ),
        'id'            => 'custom-sidebar',
        'description'   => esc_html__( 'Add widgets here.', 'theme_name' ),
        'before_widget' => '<section id="%1$s" class="widget %2$s">',
        'after_widget'  => '</section>',
        'before_title'  => '<h4 class="widget-title">',
        'after_title'   => '</h4>',
    ) );
}
add_action( 'widgets_init', 'theme_prefix_widgets_init' );

2. Output your newly registered sidebar

Next, you need to add some code to your theme to display the sidebar. This is often done in sidebar.php, but can be placed anywhere you want to display a widget area.

Depending on where, and under what conditions you want to display your sidebar, you may have to add conditional logic. In the below example, we’re simply checking if the sidebar is active, meaning it has widgets placed in it:

<?php if ( is_active_sidebar( 'custom-sidebar' ) ) : ?>
    <aside id="secondary" class="widget-area">
        <?php dynamic_sidebar( 'custom-sidebar' ); ?>
    </aside>
<?php endif; ?>

3. Add widgets to your sidebar

Now that you’ve configured a new sidebar, you can start using it! Log into your WordPress dashboard, and head over to appearance > widgets. From here, you’ll find all of the widgets available on your site. Either drag a widget into your new sidebar, or click to dropdown on the widget, and select the sidebar you’d like to add it to.

Published by Bob Moore

I’m a full stack Web Developer living and working in Madison, WI. I specialize in WordPress development, including plugins, themes, security, performance, and maintenance.

Leave a Reply

Your email address will not be published. Required fields are marked *