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?
2 Answers
Assuming that you have custom Nav Menus implemented properly:
-
Registering nav menu Theme Locations:
register_nav_menus( array( 'parent_page' => "Parent Page", 'page_a' => "Page A", 'page_b' => "Page B", //etc ) );
-
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' ) );
}