The nav_menu_item_id filter allows you to modify the ID attribute applied to a menu item’s <li> element in a WordPress navigation menu.
Usage
add_filter('nav_menu_item_id', 'your_custom_function', 10, 4);
function your_custom_function($menu_item_id, $menu_item, $args, $depth) {
// Your custom code here
return $menu_item_id;
}
Parameters
$menu_item_id (string)– The ID attribute applied to the menu item’s<li>element.$menu_item (WP_Post)– The current menu item.$args (stdClass)– An object ofwp_nav_menu()arguments.$depth (int)– Depth of menu item, used for padding.
Examples
Add a prefix to the menu item ID
add_filter('nav_menu_item_id', 'prefix_menu_item_id', 10, 4);
function prefix_menu_item_id($menu_item_id, $menu_item, $args, $depth) {
return 'my-prefix-' . $menu_item_id;
}
This code adds a prefix “my-prefix-” to the menu item ID.
Remove the ID attribute from menu items
add_filter('nav_menu_item_id', '__return_empty_string');
This code removes the ID attribute from all menu items.
Add a custom class to specific menu items based on their depth
add_filter('nav_menu_item_id', 'add_custom_class_to_menu_item', 10, 4);
function add_custom_class_to_menu_item($menu_item_id, $menu_item, $args, $depth) {
if ($depth === 1) {
return $menu_item_id . ' custom-class';
}
return $menu_item_id;
}
This code adds a custom class “custom-class” to menu items with a depth of 1.
Add the menu item’s slug to the ID attribute
add_filter('nav_menu_item_id', 'add_slug_to_menu_item_id', 10, 4);
function add_slug_to_menu_item_id($menu_item_id, $menu_item, $args, $depth) {
return $menu_item_id . '-' . $menu_item->post_name;
}
This code adds the menu item’s slug to the ID attribute.
Append a custom suffix to the menu item ID based on the menu location
add_filter('nav_menu_item_id', 'append_suffix_to_menu_item_id', 10, 4);
function append_suffix_to_menu_item_id($menu_item_id, $menu_item, $args, $depth) {
if ($args->theme_location == 'primary') {
return $menu_item_id . '-primary-menu';
}
return $menu_item_id;
}
This code appends a custom suffix “-primary-menu” to the menu item ID if the menu location is set to “primary”.