Using WordPress ‘nav_menu_item_title’ PHP filter

The nav_menu_item_title filter allows you to modify a WordPress menu item’s title.

Usage

add_filter('nav_menu_item_title', 'your_custom_function', 10, 4);
function your_custom_function($title, $menu_item, $args, $depth) {
    // your custom code here
    return $title;
}

Parameters

  • $title (string) – The menu item’s title.
  • $menu_item (WP_Post) – The current menu item object.
  • $args (stdClass) – An object of wp_nav_menu() arguments.
  • $depth (int) – Depth of menu item, used for padding.

Examples

Add an icon to a menu item

add_filter('nav_menu_item_title', 'add_icon_to_menu_item', 10, 4);

function add_icon_to_menu_item($title, $menu_item, $args, $depth) {
    if ($menu_item->title == 'Home') {
        $title = '<i class="fas fa-home"></i> ' . $title;
    }

    return $title;
}

This code adds a home icon to the menu item with the title ‘Home’.

Wrap menu item title in custom HTML

add_filter('nav_menu_item_title', 'wrap_menu_item_title', 10, 4);

function wrap_menu_item_title($title, $menu_item, $args, $depth) {
    $title = "<span class='custom-menu-title'>{$title}</span>";

    return $title;
}

This code wraps each menu item title in a custom HTML <span> element with the class custom-menu-title.

Make menu item title uppercase

add_filter('nav_menu_item_title', 'uppercase_menu_item_title', 10, 4);

function uppercase_menu_item_title($title, $menu_item, $args, $depth) {
    $title = strtoupper($title);

    return $title;
}

This code changes the menu item title to uppercase.

Add a custom attribute to menu item title

add_filter('nav_menu_item_title', 'add_custom_attribute_to_menu_item', 10, 4);

function add_custom_attribute_to_menu_item($title, $menu_item, $args, $depth) {
    $title = "<span data-custom-attr='example'>{$title}</span>";

    return $title;
}

This code adds a custom attribute data-custom-attr with the value ‘example’ to each menu item title.

Append item depth to menu item title

add_filter('nav_menu_item_title', 'append_item_depth_to_menu_item', 10, 4);

function append_item_depth_to_menu_item($title, $menu_item, $args, $depth) {
    $title .= " (Depth: {$depth})";

    return $title;
}

This code appends the menu item’s depth to the title, for example “Home (Depth: 0)”.