7

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.

  • can I ask why they wanted two main menus? Sounds odd, or like they didn't want this, this is just their idea on how to implement what they actually want – Tom J Nowell Dec 10 '12 at 18:23
  • I'm not thrilled with needing to do this, but what they asked for both in site structure and design required two menus for two mostly independent sections of the site. I'm guessing that this function could be used for some other stuff too, and I was surprised that I didn't find anything like it when I first looked. – mrwweb Dec 10 '12 at 22:21
17

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 );
}
  • Nice snippet. I needed to use it to serve up a different header image depending on the menu the page was assigned to. Thanks! – Stephen S. May 5 '14 at 18:31
  • Why is $menu passed through esc_attr in the first line? – Luke A. Leber Dec 18 '18 at 15:20
  • @LukeA.Leber It's been a long time since I wrote this. I believe I was using it in a context where site editors could set values used in this function. – mrwweb Dec 20 '18 at 19:45
  • This apparently works only with 1-level menus. – certainlyakey Oct 21 at 15:29

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.