how to add custom widgets in wordpress theme

    By: Manu
    3 years ago

    In WordPress, we can create widgets and can display posts lists, Tags, Categories, and more content types in different positions on web pages. But if your theme does not have widgets feature enabled then you need to add code in "functions.php" file to display widgets.

    We can add widget feature using this code

    // Adding Widgets to theme
    
        function customWidgets(){
            register_sidebar(array(
                'name'=> 'Sidebar',
                'id'  => 'sidebar1',
                'before_widget'=>'<div class="sidebarWidgetItem">',
                'after_widget'=>'</div>',
                'before_title'=>'<h3>',
                'after_title'=>'</h3>'
            ));
    
        }
    
        add_action('widgets_init','customWidgets');
    

    If you add the above code in functions.php you will be widgets option under the appearance

    And when you click on widgets you should see sidebar area under widgets page

    Now here we can drag and drop available widgets to the sidebar area and then click on save. Then that widget will be added to sidebar. But to display it in front end we need to call sidebar area using id that we used in "functions.php" like this.

    dynamic_sidebar('sidebar1');
    

    For more proper example check video guide to see how step by step we can add widgets in different areas in our theme.