How to Add a Custom Widget Area to WordPress Themes

How to Add a Custom Widget Area to WordPress Themes? If you are familiar with WordPress themes then you know that a lot of themes have a widgetized sidebar or widget ready. If you visit your site’s Admin Dashboard and head over Appearance, Widgets, you will find the list of available widgets and will be offered to drag and drop them for activating or deactivating. But what if you want to create your custom widget area to display content where you want?

What is Widget?

Widgets allow you to add content blocks to specific sections of your theme easily. Initially, they were added to the themes to generate a simple way for managing the design and structure of the theme.

What is Widget Area?

Widget area is the option of the WordPress we can add our widgets in it to display where we want. You can find the widget area of your theme in the Appearance menu under the Widgets section if the theme has.

To create a widget area add the below code to the “functions.php” file of your theme.

if (!function_exists('hs_init_widget_area')) {
    function hs_init_widget_area()
    {
        register_sidebar(
            array(
                'name' => __('Widget Area: Sidebar', 'hs'),
                'id' => 'hs_sidebar',
                'description' => __('Add your widgets here.', 'hs'),
                'before_widget' => '<section id="%1$s" class="widget %2$s">',
                'after_widget' => '</section>',
            )
        );
    }

    add_action('widgets_init', 'hs_init_widget_area');
}
  • id – a unique identifier of a widget area
  • name – the name of the widget area, which will be displayed in Appearance > Widgets
  • description – a description of the widget area that is displayed within it and visible in Appearance > Widgets
  • class – additional CSS class that can be assigned to the widget area, which will help you customize the widget area with CSS later
  • before_widget – a block of HTML code added before every widget that belongs to the widget area
  • after_widget – a block of HTML code added after every widget that belongs to the widget area
  • before_title – a block of HTML code added before the widget area title when it is displayed
  • after_title – a block of HTML code added after the widget area title when it is displayed

After the creation of the widget area, we should display the widgets of the area in our theme. To do this, add code below to your theme where you want to display like sidebar or before the content of the post and…

<?php if (is_active_sidebar('hs_sidebar')) : ?>
    <div class="sidebar">
        <?php dynamic_sidebar('hs_sidebar'); ?>
    </div>
<?php endif; ?>

In this code, we check if there is any widget inside of the widget area. If there is any widget, then display the content.

Add a Custom Widget Area to Your WordPress with a Plugin

Another simple way of creating and adding custom widgets is presented with practical plugins.

Shopping Cart