Check if page is in menu

With the following function you can check if a page is in a certain menu.

/**
* Check if post is in a menu
*
* @param $menu menu name, id, or slug
* @param $object_id int post object id of page
* @return bool true if object is in menu
*/
function is_in_menu( $menu = null, $object_id = null ) {
   // Get menu object
   $menu_object = wp_get_nav_menu_items( esc_attr( $menu ) );
 
   // Stop if there isn't a menu
   if ( ! $menu_object )
   return false;
 
   // Get the object_id field out of the menu object
   $menu_items = wp_list_pluck( $menu_object, 'object_id' );
 
   // Use the current post if object_id is not specified
   if ( ! $object_id ) {
      global $post;
      $object_id = get_queried_object_id();
   }
 
   // Test if the specified page is in the menu or not. return true or false.
   return in_array( (int) $object_id, $menu_items );
}

Leave a Reply

Your email address will not be published. Required fields are marked *

Robbert Vermeulen

Need help from a WordPress expert?

I would love to hear about your project and how I can help you achieve your goals