How do I check if a menu exists?

I’m currently retrieving a nav menu based on the parent page’s title, and if the page doesn’t have a parent then it’s own title.

global $post;
$page_title;

if ($post->post_parent) {
    $page_title = get_the_title($post->post_parent);
}  else {
    $page_title = get_the_title($post);
}

$sidebar_title = 'Sidebar - '.$page_title;
wp_nav_menu(array( 'menu' => $sidebar_title));

Instead of first checking for a parent, I’d like to first check if a page has it’s own unique menu. This is what I wrote but it doesn’t work:

Read More
global $post;
$page_title = get_the_title($post);
$sidebar_title = 'Sidebar - '.$page_title;

if ( !wp_nav_menu(array( 'menu' => $sidebar_title, 'echo' => false )) ) {

    $page_title = get_the_title($post->post_parent);
    $sidebar_title = 'Sidebar - '.$page_title;
}

wp_nav_menu(array( 'menu' => $sidebar_title ));

TLDR: How do I check if a menu exists?

Related posts

2 comments

  1. Assuming that you have custom Nav Menus implemented properly:

    1. Registering nav menu Theme Locations:

      register_nav_menus( array(
          'parent_page' => "Parent Page",
          'page_a' => "Page A",
          'page_b' => "Page B", //etc
      ) );
      
    2. Calling wp_nav_menu() correctly:

      wp_nav_menu( array(
          'theme_location' => 'page_a'
      );
      

    …then you can use the has_nav_menu() conditional to determine if a Theme Location has a menu assigned to it:

    if ( has_nav_menu( 'page_a' ) ) {
        // do something
    }
    

    In your specific case, you could do something like so:

    if ( has_nav_menu( 'page_a' ) ) {
        wp_nav_menu( array( 'theme_location' => 'page_a' ) );
    } else {
        wp_nav_menu( array( 'theme_location' => 'parent_page' ) );
    }
    
  2. I think I’m doing a similar thing to the OP: letting my client (wp admin user) create Menus (in WP-Admin > Appearance > Menus), which are NOT assigned to a specific theme location, because that requires a static / one-to-one relationship.

    Instead, these Menus are displayed dynamically (by a custom widget), based on the name of the current-page’s top-ancestor. If that name matches an existing Menu’s name, show the Menu (wrapped by standard widget before/after html). But, if there’s NO match, output nothing.

    So I needed to check if the Menu exists, before starting widget output.

    $args = array(
        'menu' => $menu_name, // from top-ancestor of current page
        'echo' => 0,  // true or 0
        'theme_location' => '__fake', // fake value, to prevent display of 1st real menu
        'fallback_cb' => false  // prevent display of 1st real menu
    );
    $menu = wp_nav_menu( $args );
    if ($menu){ 
        # output
        echo $before_widget; // Before
        echo $before_title . $title . $after_title; // Title
        echo $menu;  
        echo $after_widget; // After
    }
    

Comments are closed.