wp_get_nav_menu_items current menu item

When I want to display a menu in WordPress I sometimes find it pleasant to use the wp_get_nav_menu_items() function. This function returns only the menu item objects of the corresponding menu. So it allows you to build your custom menu exactly the way you want, without dealing with WordPress predefined output. However, if you would use the function wp_nav_menu() you benefit from a built-in “current menu” functionality which lets you know which menu item is active through a css class added to the current menu list item.

When building your custom menu with wp_get_nav_menu_items() you can create this current menu item functionality by simply checking the queried object id of the current page and compare it to each menu item’s object id.

if ( $menu_items = wp_get_nav_menu_items( 'menu' ) ) {
   foreach ( $menu_items as $menu_item ) {
      $current = ( $menu_item->object_id == get_queried_object_id() ) ? 'current' : '';
      echo '<li class="' . $current . '"><a href="' . $menu_item->url . '">' . $menu_item->title . '</a></li>';
   }
}

Pssst..

I wrote a related post about how to get your navigation menu items by location instead of menu name. If you are interested you can read the post here:

Get nav menu items by location →