Theme & Front End PHP Beginner

Register a New Widget Area

Add a new sidebar or widget area to a classic theme, ready to fill from Appearance > Widgets.

Tested on WordPress 7.1 PHP 8.3 No plugin needed Updated
functions.php 16 lines
add_action( 'widgets_init', function (): void {
	register_sidebar( [
		'name'          => 'Shop sidebar',
		'id'            => 'nahnu-shop-sidebar',
		'description'   => 'Shown next to products on shop pages.',
		'before_widget' => '<section id="%1$s" class="widget %2$s">',
		'after_widget'  => '</section>',
		'before_title'  => '<h2 class="widget-title">',
		'after_title'   => '</h2>',
	] );
} );

// Then show it in a template file:
// if ( is_active_sidebar( 'nahnu-shop-sidebar' ) ) {
// 	dynamic_sidebar( 'nahnu-shop-sidebar' );
// }

Where to add this

Recommended A code snippets plugin Survives theme changes and is easy to switch off.
Child theme At the end of your child theme's functions.php file.
Must-use plugin As a .php file in wp-content/mu-plugins, starting with <?php.

Always add PHP to a staging site first, or have FTP or file manager access ready, so you can undo it if something goes wrong.

Widget areas let non-developers change part of a page from Appearance → Widgets. If your classic theme doesn’t have one where you need it, this snippet registers a new one.

How it works

register_sidebar() runs on widgets_init and creates the widget area. The before_widget and before_title settings control the HTML around each widget; %1$s and %2$s are replaced with the widget’s id and classes.

To show the widgets, call dynamic_sidebar() with the same id in a template file, such as your child theme’s sidebar or WooCommerce template.

Things to watch

  • Block themes don’t use widget areas. Use template parts in the Site Editor instead.
  • Page builders like Bricks have a Sidebar element that can display any registered widget area.

How to test it

Go to Appearance → Widgets. “Shop sidebar” should be listed.

This website uses cookies to enhance your browsing experience and ensure the site functions properly. By continuing to use this site, you acknowledge and accept our use of cookies.

Accept All Accept Required Only