WordPress – How to add widgets to homepage, siderbar… etc

If you ever wondered how to create a dynamic sidebar in WordPress that would allow you to add widgets from within the WordPress administration, you’ve come to the right place.

Adding widgets to your theme consists only of 3 basic steps:

  1. register a placement within functions.php file
  2. define a placement from within a file where you want your widgets to show, for example sidebar.php, single.php… etc
  3. simply via WordPress admin -> Themes -> Widgets pick the desired widgets 🙂

1. Register a widget placement

To do so, open up your functions.php file and with a function register_sidebar register a placement for your widgets.

The code can be as simple as the one below:

add_action( 'widgets_init', 'my_register_sidebars' );
function my_register_sidebars() {
    register_sidebar(
        array(
            'id' => 'single',
            'name' => __( 'Single article Sidebar' ),
        )
    );
}

You should pay attention to the two keys, i.e. id and name. The ID will identify placement and we will use this ID later on and the name will identify the placement within WordPress administration.

2. Define a placement

Now since we have registered a placement we need to specify in our template files, where we want have our widgets to show.

For example you might want to show some widgets in a footer of the post, so in this case we would open up our single.php file and place there the widget definition code via function dynamic_sidebar().

The code can be as simple as the one below:

<div class="sidebar">
    <?php dynamic_sidebar( 'single' ); ?>
</div>

As the 1st argument of the dynamic_sidebar() function you are to put the ID attribute you chose a while ago.

3. Pick the widgets

Now, simply navigate into the WordPress administration -> Appearance -> Widgets and you should see the placement we defined with the code above.

Now simply choose widgets you need 🙂 .

Choosing widgets

Sources:

Wrapping up

In this quick guide I walked you through how to register a dynamic sidebar in WordPress so as you are able to manage widgets via WordPress administration.

A video tutorial will be available shortly.

Until then,

Yours in coding.

Ivan


Image credits: Image by Dok Sev from Pixabay 

Leave a comment

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