Developing WordPress Themes - Widgets

Widgets are self-contained blocks you can add to widget areas. Similar to how you can add menus to menu areas.

A widget area is thus a location you define in your theme, where the widgets will go.

Widget area are also called 'sidebar' in WordPress, but don't let the name fool you, it can be placed anywhere. So just as we did with menus, we must:

  1. Add the sidebar into the template
  2. Register the sidebar in functions.php

Adding Widget Area to Template

In the relevant template, add the following code, replacing header_bar_area with the machine name of your widget area.

<?php if ( is_active_sidebar( 'header_bar_area' ) ) : ?>
    <?php dynamic_sidebar( 'header_bar_area' ); ?>
<?php endif; ?>

Registering Widgets Areas

Next, we will use register_sidebar() to register our widget areas. This method must be called after the action widgets_init, and so use a hook to run the function.

function brew_register_widgets() {
    register_sidebar( array(
        'name'          => 'Header Bar Area',
        'id'            => 'header_bar_area',
        'before_widget' => '<div>',
        'after_widget'  => '</div>',
        'before_title'  => '<h2 class="rounded">',
        'after_title'   => '</h2>',
    ) );
add_action( 'widgets_init', 'brew_register_widgets' );

Adding Widgets

Themes and plugins can provide widgets for your site. Go to Appearance > Widgets to find all the available widgets. Simply drag them into the Widget Areas and see it appear on your page.

If you enjoyed this article, why not take a look at the rest of the series on Developing WordPress Themes!

comments powered by Disqus