0
0
Wordpressframework~5 mins

Navigation walker classes in Wordpress

Choose your learning style9 modes available
Introduction

Navigation walker classes help you control how WordPress menus look and behave. They let you change the menu HTML easily.

You want to add custom CSS classes to menu items.
You need to change the HTML structure of your menu.
You want to add icons or extra elements inside menu links.
You want to support dropdown menus with special markup.
You want to customize menu output without editing core files.
Syntax
Wordpress
class My_Custom_Walker extends Walker_Nav_Menu {
    // Override methods like start_el() or start_lvl() here
    public function start_el(&$output, $item, $depth = 0, $args = null, $id = 0) {
        // Custom code to change menu item output
    }
}

You create a new class that extends Walker_Nav_Menu.

Override methods like start_el() to change menu item HTML.

Examples
This example makes a simple list item with the menu title only.
Wordpress
class Simple_Walker extends Walker_Nav_Menu {
    public function start_el(&$output, $item, $depth = 0, $args = null, $id = 0) {
        $output .= '<li>' . esc_html($item->title) . '</li>';
    }
}
This adds a star icon before each menu item.
Wordpress
class Icon_Walker extends Walker_Nav_Menu {
    public function start_el(&$output, $item, $depth = 0, $args = null, $id = 0) {
        $icon = '<span class="icon">ā˜…</span>';
        $output .= '<li>' . $icon . ' ' . esc_html($item->title) . '</li>';
    }
}
Sample Program

This custom walker adds the original menu item classes to each <li> and outputs a normal link inside it. It is used by passing an instance of the walker to wp_nav_menu.

Wordpress
<?php
class Custom_Walker extends Walker_Nav_Menu {
    public function start_el(&$output, $item, $depth = 0, $args = null, $id = 0) {
        $classes = implode(' ', $item->classes);
        $output .= '<li class="' . esc_attr($classes) . '">';
        $output .= '<a href="' . esc_url($item->url) . '">' . esc_html($item->title) . '</a>';
    }
    public function end_el(&$output, $item, $depth = 0, $args = null) {
        $output .= '</li>';
    }
}

// Usage in wp_nav_menu
wp_nav_menu(array(
    'theme_location' => 'primary',
    'walker' => new Custom_Walker()
));
?>
OutputSuccess
Important Notes

Always sanitize output with functions like esc_html() and esc_url() for security.

Use start_el() to customize each menu item and start_lvl() to customize submenu wrappers.

Test your walker with different menu setups to avoid breaking navigation.

Summary

Navigation walker classes let you change how WordPress menus are built.

Create a class extending Walker_Nav_Menu and override methods.

Pass your custom walker to wp_nav_menu to use it.