Create Widget Area in WordPress Theme

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 Appareance menu under Widgets section if the theme has.

To create widget area add the below code to your 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');
}
  • name: the name of the widget area (title in widget area section)
  • id: the slug of the widget area
  • description: description of the widget area
  • before_widget and after_widget: add extra code right before and after the widgets of the widget area (widgets inside of the widget area not the widget area itself)

After 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 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.

Shopping Cart