nav_menu_item_id
Allows you to change the ID attribute of a menu item's <li> element.
Use nav_menu_css_class to remove or change a menu item's class attribute.
WordPress core generates the <li> element's ID attribute as follows:
$id = apply_filters( 'nav_menu_item_id', 'menu-item-'. $item->ID, $item, $args, $depth ); $id = $id ? ' id="' . esc_attr( $id ) . '"' : '';
By default, the ID attribute is menu-item-{menu item ID}. The filter can completely change it. If the filter returns nothing, no ID attribute is added to the <li> element.
Remember that an element's ID attribute must be unique on the page.
Usage
add_filter( 'nav_menu_item_id', 'wp_kama_nav_menu_item_id_filter', 10, 4 );
/**
* Function for `nav_menu_item_id` filter-hook.
*
* @param string $menu_item_id The ID attribute applied to the menu item's `<li>` element.
* @param WP_Post $menu_item The current menu item.
* @param stdClass $args An object of wp_nav_menu() arguments.
* @param int $depth Depth of menu item. Used for padding.
*
* @return string
*/
function wp_kama_nav_menu_item_id_filter( $menu_item_id, $menu_item, $args, $depth ){
// filter...
return $menu_item_id;
}
- $menu_id(string)
- ID of the menu item's
<li>element. - $item(WP_Post)
Current menu item object. Example:
- $args(stdClass)
Object containing parameters from wp_nav_menu(). Example:
- $depth(int)
Menu item level used for indentation. Top-level items have
$depth = 0, nested items have$depth = 1, and so on.Added in version 4.1.0.
Examples
#1 Remove the ID attribute from menu items
Remove IDs from every menu item on the site:
add_filter( 'nav_menu_item_id', '__return_empty_string' );
Remove the ID attribute from every menu item output in the primary menu location:
add_filter( 'nav_menu_item_id', 'change_menu_item_css_id', 10, 4 );
function change_menu_item_css_id( $menu_id, $item, $args, $depth ) {
return $args->theme_location === 'primary' ? '' : $menu_id;
}
Notes
- The
$depthparameter was added in version 4.1.0.
Changelog
| Since 3.0.1 | Introduced. |
| Since 4.1.0 | The $depth parameter was added. |
Where the hook is called
$id = apply_filters( 'nav_menu_item_id', 'menu-item-' . $menu_item->ID, $menu_item, $args, $depth );
Where the hook is used in WordPress
add_filter( 'nav_menu_item_id', '_nav_menu_item_id_use_once', 10, 2 );