wp_nav_menu_objects
Allows you to modify the sorted list of menu item objects before the menu HTML is generated from them.
Usage
add_filter( 'wp_nav_menu_objects', 'wp_kama_nav_menu_objects_filter', 10, 2 );
/**
* Function for `wp_nav_menu_objects` filter-hook.
*
* @param array $sorted_menu_items The menu items, sorted by each menu item's menu order.
* @param stdClass $args An object containing wp_nav_menu() arguments.
*
* @return array
*/
function wp_kama_nav_menu_objects_filter( $sorted_menu_items, $args ){
// filter...
return $sorted_menu_items;
}
- $sorted_menu_items(array)
- Array of menu item objects sorted by the
menu_orderkey. Their order therefore matches the menu item order configured in the admin area when the menu was created. - $args(stdClass)
- Object containing the arguments passed to wp_nav_menu().
Examples
#1 Remove a menu item
Task: remove items linking to the login page from every menu for logged-in users. If the page ID is known, this can be done as follows:
## Remove one of the menu items.
add_filter( 'wp_nav_menu_objects', 'change_nav_menu_objects', 10, 2 );
function change_nav_menu_objects( $sorted_menu_items, $args ) {
foreach ( $sorted_menu_items as $index => $item ) {
if ( is_user_logged_in() && 'page' == $item->object && 214 == $item->object_id ) {
unset( $sorted_menu_items[ $index ] );
}
}
return $sorted_menu_items;
}
#2 Add a custom CSS class to parent menu items
add_filter( 'wp_nav_menu_objects', 'add_css_class_for_menu_item_has_child_elements' );
function add_css_class_for_menu_item_has_child_elements( $items ) {
// Collect the IDs of menu items that have children.
$parents = wp_list_pluck( $items, 'menu_item_parent' );
foreach ( $items as $item ) {
// Check whether the current menu item is among them, and add a CSS class.
if ( in_array( $item->ID, $parents ) ) {
$item->classes[] = 'has-child-elements';
}
}
return $items;
}
#3 Add a custom CSS class to the current menu item
The current menu item is the item whose page the user is viewing.
add_filter( 'wp_nav_menu_objects', 'add_css_class_for_current_menu_item' );
function add_css_class_for_current_menu_item( $items ) {
foreach ( $items as $item ) {
if ( $item->current ) {
$item->classes[] = 'current-element';
}
}
return $items;
}Changelog
| Since 3.1.0 | Introduced. |
Where the hook is called
wp_nav_menu_objects
wp-includes/nav-menu-template.php 239
$sorted_menu_items = apply_filters( 'wp_nav_menu_objects', $sorted_menu_items, $args );