madseason
1/15/2020 - 6:15 PM

wp_get_nav_menu_items() current menu item

When displaying a menu in WordPress I sometimes find it pleasant to use the wp_get_nav_menu_items() function. This function returns only an array of 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” conditional logic which lets you know which menu item is active through a CSS class added to the current menu list item. When using wp_get_nav_menu_items you have to create this logic yourself.

Solution 1: Queried object id 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.

// Check if menu exists if ( $menu_items = wp_get_nav_menu_items( 'menu' ) ) {

// Loop over menu items foreach ( $menu_items as $menu_item ) {

  // Compare menu object with current page menu object
  $current = ( $menu_item->object_id == get_queried_object_id() ) ? 'current' : '';
  
  // Print menu item
  echo '<li class="' . $current . '"><a href="' . $menu_item->url . '">' . $menu_item->title . '</a></li>';

} } Solution 2: Request URI path There is only one problem when you use the queried object id to check if the menu item is the current page, namely; when you add link menu items to, for example, a post type archive. These pages have no object id. In that case, it is a better option to compare the path of the request URI with the URL of the menu item. You can do this as follows:

// Check if menu exists if ( $menu_items = wp_get_nav_menu_items( 'menu' ) ) {

// Loop over menu items foreach ( $menu_items as $menu_item ) {

  // Compare menu item url with server request uri path
  $current = ( $_SERVER['REQUEST_URI'] == parse_url( $menu_item['url'], PHP_URL_PATH ) ) ? 'current' : '';

  // Print menu item
  echo '<li class="' . $current . '"><a href="' . $menu_item->url . '">' . $menu_item->title . '</a></li>';

} }

// Check if menu exists
if ( $menu_items = wp_get_nav_menu_items( 'menu' ) ) {
   
   // Loop over menu items
   foreach ( $menu_items as $menu_item ) {

      // Compare menu item url with server request uri path
      $current = ( $_SERVER['REQUEST_URI'] == parse_url( $menu_item['url'], PHP_URL_PATH ) ) ? 'current' : '';

      // Print menu item
      echo '<li class="' . $current . '"><a href="' . $menu_item->url . '">' . $menu_item->title . '</a></li>';
   }
}