A widget area, also called a sidebar, is a place in your theme where the site owner can drag and drop widgets from Appearance, Widgets. Register it with register_sidebar() and print it with dynamic_sidebar().

Step 1: register the widget area

function lotgrafix_widgets_init() {
    register_sidebar( array(
        'name'          => __( 'Main Sidebar', 'lotgrafix' ),
        'id'            => 'lotgrafix-sidebar',
        'description'   => __( 'Widgets shown on blog pages.', 'lotgrafix' ),
        'before_widget' => '<section id="%1$s" class="widget %2$s">',
        'after_widget'  => '</section>',
        'before_title'  => '<h3 class="widget-title">',
        'after_title'   => '</h3>',
    ) );
}
add_action( 'widgets_init', 'lotgrafix_widgets_init' );

Step 2: print it in your template

Create sidebar.php or place this where you want the widgets to appear.

<?php if ( is_active_sidebar( 'lotgrafix-sidebar' ) ) : ?>
    <aside class="lotgrafix-sidebar">
        <?php dynamic_sidebar( 'lotgrafix-sidebar' ); ?>
    </aside>
<?php endif; ?>

Then load it from any template with get_sidebar();.

Register several areas at once

function lotgrafix_footer_widgets_init() {
    for ( $i = 1; $i <= 3; $i++ ) {
        register_sidebar( array(
            'name'          => sprintf( __( 'Footer Column %d', 'lotgrafix' ), $i ),
            'id'            => 'lotgrafix-footer-' . $i,
            'before_widget' => '<div id="%1$s" class="widget %2$s">',
            'after_widget'  => '</div>',
            'before_title'  => '<h4 class="widget-title">',
            'after_title'   => '</h4>',
        ) );
    }
}
add_action( 'widgets_init', 'lotgrafix_footer_widgets_init' );

Notes

  • The id must be unique and use lowercase letters, numbers, dashes and underscores.
  • The placeholders %1$s and %2$s are replaced with the widget ID and class.
  • Block themes use the Site Editor instead of widget areas, but classic themes still rely on this.
«
»