This is a follow up question to a few related threads. How can you display a wp_nav_menu
in WordPress only if it has menu items already assigned? Because has_nav_menu
does not seem to be enough here, since it will return true even if there are not any menu items yet but the queried menu location exists or is registered...
-
Related: wordpress.stackexchange.com/questions/117146/…– Jesse NicklesCommented Jun 19 at 11:21
3 Answers
This solution was shared by @TheDeadMedic over here...
$menu_exists_and_has_items = wp_nav_menu(
array(
'theme_location' => 'example-menu-location',
'container_class' => 'example-menu-container',
'menu_class' => 'example-menu-class',
'fallback_cb' => false,
'echo' => false
)
);
if ( $menu_exists_and_has_items ) {
...
Importantly, note that the menu is not echoed in the initial array saved to PHP variable...
To ensure that a navigation menu in WordPress is displayed only if it is populated with menu items, you can use a combination of has_nav_menu()
to check if a menu is assigned to a location, and wp_get_nav_menu_items()
to verify that the menu has items. Here’s how you can implement this in your theme’s code:
Check if a menu location has a menu assigned and has items: You will first need to determine the menu assigned to a specific location and then check if this menu has any items.
Display the menu if conditions are met: If both conditions are satisfied (menu is assigned and has items), then you render the menu.
Here is an example code snippet that accomplishes this:
// Specify the menu location you want to check
$menu_location = 'primary'; // change 'primary' to your actual menu location id
// Check if a menu is assigned to this location
if ( has_nav_menu( $menu_location ) ) {
// Get the menu object assigned to the specified location
$locations = get_nav_menu_locations();
$menu = wp_get_nav_menu_object( $locations[ $menu_location ] );
if ( $menu && ! is_wp_error( $menu ) ) {
// Get the menu items for this menu
$menu_items = wp_get_nav_menu_items( $menu->term_id );
if ( $menu_items && count( $menu_items ) > 0 ) {
// Menu has items, display the menu
wp_nav_menu( array( 'theme_location' => $menu_location ) );
}
}
}
-
Really nice and clean solution! And more specific/valid than mine. Commented Jun 19 at 13:28
To display a wp_nav_menu
in WordPress only if it has menu items assigned, you can use wp_get_nav_menu_items
to check if the menu has items. Here’s a code example:
$menu_name = 'primary'; // Replace with your menu location
$locations = get_nav_menu_locations();
if (isset($locations[$menu_name])) {
$menu = wp_get_nav_menu_object($locations[$menu_name]);
$menu_items = wp_get_nav_menu_items($menu->term_id);
if ($menu_items) {
wp_nav_menu(array('theme_location' => $menu_name));
}
}
Note: This code is not tested.