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:
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?
Assuming that you have custom Nav Menus implemented properly:
Registering nav menu Theme Locations:
Calling
wp_nav_menu()
correctly:…then you can use the
has_nav_menu()
conditional to determine if a Theme Location has a menu assigned to it:In your specific case, you could do something like so:
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.