<?php
function my_custom_sidebar() {
register_sidebar([
'name' => 'Footer Widgets',
'id' => 'footer-widgets',
'description' => 'Widgets for the footer area',
'before_widget' => '<section class="footer-widget">',
'after_widget' => '</section>',
'before_title' => '<h3>',
'after_title' => '</h3>'
]);
}
add_action('widgets_init', 'my_custom_sidebar');
?>The register_sidebar function creates a new widget area visible in the WordPress admin under Appearance > Widgets. The 'name' is the label shown, and the 'id' uniquely identifies it. The 'before_widget' and 'after_widget' parameters wrap each widget's output, which is valid HTML here. The function is correctly hooked to 'widgets_init'.
<?php if (is_active_sidebar('sidebar-1')) { dynamic_sidebar('sidebar-1'); } else { echo '<p>No widgets found.</p>'; } ?>
The function is_active_sidebar returns true if the sidebar has widgets. Then dynamic_sidebar outputs the widgets' HTML. If no widgets exist, the fallback message is shown.
The register_sidebar function accepts a single associative array with keys like 'name' and 'id'. Calling it twice with separate arrays registers two sidebars. Passing multiple arrays in one call or positional arguments is invalid.
<?php
function theme_widgets_init() {
register_sidebar([
'name' => 'Blog Sidebar',
'id' => 'blog-sidebar',
'before_widget' => '<div>',
'after_widget' => '</div>',
]);
}
add_action('widgets_init', 'theme_widgets_init');
// In sidebar.php
if (dynamic_sidebar('blog-sidebar')) {
// Widgets displayed
} else {
echo '<p>No widgets found.</p>';
}
?>The code correctly registers the sidebar and calls dynamic_sidebar. If no widgets appear, the most common reason is that no widgets have been assigned to that sidebar in the WordPress admin.
dynamic_sidebar('sidebar-id') instead of hardcoding widget HTML in the template files?dynamic_sidebar outputs whatever widgets the site admin has placed in that sidebar. This makes the theme flexible and customizable without code changes. Hardcoding widget HTML removes this flexibility.