Skip to content
Tutorials Center
My learning

Topics

Lesson 20 of 68 ยท Classic Themes and the Template Hierarchy

Menus, Widgets and Sidebars

Register navigation menus and widget areas in a classic theme, print them with wp_nav_menu and dynamic_sidebar, customize the markup and learn how block widgets differ.

Visitors expect a navigation bar, and site owners expect to change it without touching code. WordPress separates the two jobs. As the theme developer, you register a location ("primary menu", "footer menu") and print it where it belongs. The site owner builds the actual menu in the dashboard and assigns it to that location. Widget areas work the same way: you register a sidebar (any region that holds widgets), and the owner fills it.

This lesson covers register_nav_menus() and wp_nav_menu(), the classes WordPress adds to menu items, how to customize the HTML, how to register and print widget areas with register_sidebar() and dynamic_sidebar(), and how classic widgets differ from block widgets. The runnable example turns a nested menu array into HTML, using plain PHP, because WordPress cannot run on this site. All WordPress code in code blocks is read-only.

You can read this after Your First Classic Theme and Template Parts and Template Tags.

Registering menu locations

A menu location is a named slot in your theme. Register locations on the after_setup_theme hook:

PHP
function mytheme_setup(): void {
    register_nav_menus( [
        'primary' => __( 'Primary menu', 'mytheme' ),
        'footer'  => __( 'Footer menu', 'mytheme' ),
    ] );
}
add_action( 'after_setup_theme', 'mytheme_setup' );

The array keys (primary, footer) are the identifiers your templates use. The values are labels shown in the dashboard. After this code runs, the site owner can open Appearance > Menus, build a menu and tick the location checkbox. The owner can leave a location empty on purpose, so your theme must cope with that.

Printing a menu with wp_nav_menu

Call wp_nav_menu() in the template where the menu should appear, usually header.php:

PHP
wp_nav_menu( [
    'theme_location' => 'primary',
    'container'      => 'nav',
    'container_class'=> 'site-nav',
    'menu_class'     => 'menu',
    'depth'          => 2,
    'fallback_cb'    => false,
] );

The arguments you will use most:

Argument What it controls
theme_location Which registered location to print
container The wrapper element (div by default, nav is better; false removes it)
menu_class CSS class on the <ul>
menu_id The id of the <ul>
depth How many levels to print (0 means all)
fallback_cb What to do when no menu is assigned (false prints nothing)
items_wrap The <ul> wrapper pattern, using %1$s, %2$s and %3$s
walker An object that generates the HTML for each item

By default, when a location has no menu, wp_nav_menu() falls back to a list of pages. Setting fallback_cb to false avoids that surprise. Use has_nav_menu( 'primary' ) to check whether a menu is assigned, for example to show a different layout.

WordPress also adds helpful classes to each <li>, so you can style the menu with CSS alone:

  • menu-item on every item
  • menu-item-has-children on items with a submenu
  • current-menu-item on the page you are viewing
  • current-menu-ancestor and current-menu-parent on the parents of that item
  • sub-menu on nested <ul> elements
flowchart LR
    A["Theme registers location<br/>'primary'"] --> B["Owner builds a menu<br/>in the dashboard"]
    B --> C["Owner assigns menu<br/>to the location"]
    C --> D["Template calls<br/>wp_nav_menu('primary')"]
    D --> E["HTML nav printed<br/>with classes"]

The theme defines where menus can appear. The owner decides what goes in them.

Customizing menu markup

Most of the time you do not need a custom walker. You can change a lot with arguments and filters:

PHP
// Add a class to every link.
add_filter( 'nav_menu_link_attributes', function ( array $atts ): array {
    $atts['class'] = trim( ( $atts['class'] ?? '' ) . ' nav-link' );
    return $atts;
} );

// Remove noisy default classes from <li>.
add_filter( 'nav_menu_css_class', function ( array $classes ): array {
    return array_filter( $classes, fn ( $c ) => ! str_starts_with( $c, 'menu-item-' ) || $c === 'menu-item-has-children' );
} );

When the structure itself must change (a mega menu, custom icons), extend the Walker_Nav_Menu class. A walker implements four methods: start_lvl() opens a submenu, end_lvl() closes it, start_el() prints the opening part of an item, and end_el() closes the item. Walkers are powerful but fragile, so prefer filters first. You pass your walker with 'walker' => new Mytheme_Walker().

Accessibility matters here too. A <nav> container gets a landmark role automatically, and with several navigation areas you should add an aria-label through items_wrap or a container attribute so screen-reader users can tell them apart.

A nested menu, rendered

A menu is stored as a flat list of items, each with a parent ID. wp_nav_menu() turns that flat list into nested HTML. The stand-in below does the same with an array, showing the tree building, the current-item classes and the depth argument.

PHP Render a nested menu array to HTML (stand-in)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

Notice three things in the output. The nested ul.sub-menu lists appear only while the level is within depth. The ancestors of the current page get an ancestor class. The title Contact <us> is escaped, because menu labels come from the database and should always be escaped on output.

Widget areas: register_sidebar and dynamic_sidebar

A sidebar in WordPress terms is any widget area, not necessarily a column on the left or right. It can be a footer column, a banner strip or a header slot. Register areas on the widgets_init hook:

PHP
function mytheme_widgets_init(): void {
    register_sidebar( [
        'name'          => __( 'Blog sidebar', 'mytheme' ),
        'id'            => 'sidebar-blog',
        'description'   => __( 'Shown beside posts.', 'mytheme' ),
        'before_widget' => '<section id="%1$s" class="widget %2$s">',
        'after_widget'  => '</section>',
        'before_title'  => '<h2 class="widget-title">',
        'after_title'   => '</h2>',
    ] );
}
add_action( 'widgets_init', 'mytheme_widgets_init' );

The id is what you print later and must be unique. %1$s and %2$s in before_widget are replaced with the widget's unique HTML id and its CSS class, so you can style each widget type. To print the area, call dynamic_sidebar() in a template, guarded by is_active_sidebar() so an empty area does not leave an empty wrapper:

PHP
<?php if ( is_active_sidebar( 'sidebar-blog' ) ) : ?>
    <aside class="sidebar" aria-label="<?php esc_attr_e( 'Sidebar', 'mytheme' ); ?>">
        <?php dynamic_sidebar( 'sidebar-blog' ); ?>
    </aside>
<?php endif; ?>

dynamic_sidebar() prints every widget the owner placed in that area, each wrapped in your before_widget and after_widget markup. The same function name appears in older code with a numeric argument; always use the string ID.

Classic widgets and block widgets

Classic widgets are PHP classes that extend WP_Widget. Plugins and themes can provide their own, and the owner configures them in Appearance > Widgets.

Since WordPress 5.8, that screen uses the block editor by default. Instead of a fixed list of widget types, the owner drops regular blocks (Paragraph, Image, Latest Posts and so on) into the area, and old widgets still work through a "Legacy Widget" block. Your registration code does not change, and dynamic_sidebar() still prints everything. If you need the old interface, the use_widgets_block_editor filter can return false.

For block themes, the concept shifts again. There is no functions.php-registered sidebar. Instead, a navigation is a Navigation block whose menu is stored as a post, and "sidebars" are template parts built in the Site Editor, as you will see in Block Themes: The Big Picture. Classic themes remain widely used, and everything in this lesson still applies to them.

Common mistakes

  • Calling register_nav_menus() too early. Use after_setup_theme, not the top of functions.php outside a hook.
  • Assuming a menu always exists. Check has_nav_menu() or set fallback_cb to false.
  • Using id values that clash. Two sidebars with the same id overwrite each other.
  • Printing empty wrappers. Wrap dynamic_sidebar() in is_active_sidebar().
  • Skipping escaping in custom walkers. Titles and URLs from the database must be escaped with esc_html() and esc_url().

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Which hook is the right place to call register_nav_menus()?

    Menu locations are theme setup, so after_setup_theme is the standard hook. widgets_init is for register_sidebar().
  2. 2. What does 'fallback_cb' => false do in wp_nav_menu()?

    The default fallback prints a page list. Passing false turns that off so an unassigned location produces no output.
  3. 3. Which class does WordPress add to the <li> of the page being viewed?

    current-menu-item marks the current page, and current-menu-ancestor and current-menu-parent mark its parents.
  4. 4. How do you avoid printing an empty wrapper around a widget area?

    is_active_sidebar() returns true only when the area contains at least one widget.
  5. 5. What changed for widget areas in WordPress 5.8?

    Registration and dynamic_sidebar() are unchanged. Owners now use blocks in widget areas, and classic widgets still work.

Summary

  • Register menu locations with register_nav_menus() on after_setup_theme, and print them with wp_nav_menu(); the owner chooses the menu content.
  • Use container, menu_class, depth and fallback_cb first, then filters, and write a walker only when the structure itself must change.
  • WordPress adds classes such as menu-item-has-children and current-menu-item so CSS can do the styling.
  • Register widget areas with register_sidebar() on widgets_init and print them with dynamic_sidebar() inside an is_active_sidebar() check.
  • Widget areas use the block editor by default; block themes use the Navigation block and template parts instead.
  • Always escape titles and URLs from menus and widgets.

Next, learn how WordPress handles pictures in Images, Thumbnails and Media.