Adding a new Widget Area to your WordPress Theme

MH - Senior Developer

18/02/20

Here’s a quick one as a reference for developers adding new widget sidebar areas to your WordPress Theme in php. We always forget the syntax and need a good reference for ourselves. Let’s get straight to it.

Create the area in functions.php

If you’re not confident in editing WordPress theme files make a backup of functions.php first! In the functions.php file you need to add a snippet like this:

function themename_widgets_init() {
	register_sidebar(
		array(
			'name' => __('My Widget Area', 'themeName'),
			'id' => 'widgetarea-1',
			'description'   => __( 'Add widgets here to appear in your new area.', 'themeName' ),
			'before_widget' => '<div class = "NewWidgetArea">',
			'after_widget' => '</div>',
			'before_title' => '<h3>',
			'after_title' => '</h3>',
		)
	);
}
add_action( 'widgets_init', 'themename_widgets_init' );

Remember to change ‘themeName’,My Widget Area’ and ‘widgetarea-1’ to meaningful names for your theme. Especially the widget name, as that’s the part that will appear in your dashboard. We often use the underscores theme as boilerplate for our bespoke themes. Underscores already contains a similar function which we can piggyback to keep things neat. Have a snoop around for other calls to “register_sidebar” if you want to do the same.

Render the area in your template

The widget area is active in WordPress now, so let’s render it. Go to the theme file that requires the widgetised area. For us this was in the header but it can be anywhere in your theme!

<?php
    if ( is_active_sidebar( 'widgetarea-1' ) ) {
        ?>
            <div class="new-widget-1">
                <?php dynamic_sidebar( 'widgetarea-1' ); ?>
            </div>
        <?php
    }
?>

Remember to keep those names uniform, ‘widgetarea-1’ needs to match the names you used in the functions.php snippet.

All done. Add your widgets! If you want to learn more you can visit the WordPress Developer Pages. If you need a bespoke WordPress theme for your business don’t hesitate to contact us.