Check if page is in a certain menu

The question:

I have a client that wanted two “main menus” and we needed to programmatically display whichever menu contained the current page. How can I do that?

Ex: We’re on the “About” page. Figure out which of the two menus contains the “About” page and show that one.

The Solutions:

Below are the methods you can try. The first solution is probably the best. Try others if the first one doesn’t work. Senior developers aren’t just copying/pasting – they read the methods carefully & apply them wisely to each case.

Method 1

Here’s the function I wrote to figure this out. You give it a menu slug/name/ID and post/page ID and it returns TRUE if that post/page is in the specified menu and FALSE otherwise. Then it was just simply a matter of a quick if/else statement to check against the two menus and display the correct one.

/**
 * 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 cms_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 );

}

Example Usage:

if( cms_is_in_menu( 'main-menu' ) ) {
    // do something like wp_nav_menu( $args );
}


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Comment