Make WordPress Core

Opened 6 years ago

Last modified 5 years ago

#48015 new defect (bug)

Unexpected results from wp_nav_menu()

Reported by: chiefalchemist's profile ChiefAlchemist Owned by:
Milestone: Awaiting Review Priority: normal
Severity: major Version: 5.2.3
Component: Menus Keywords:
Focuses: Cc:

Description

I'm using wp_nav_menu() in a shortcode. That is, I'm creating / placing a menu within a page (or post) and using a shortcode to that (as opposed to hardcoding it into the theme in a specific place). Specifically, I'm placing that shortcode via the core Gutenberg block for such things, but I don't believe that matters.

  • If I pass in an empty array - wp_nav_menu([]) - it echos (?) a random menu, and return null.
  • If I start with the default args for the function and unset both 'theme_location' and 'menu' and then pass that array in - wp_nav_menu([$args]) - , a random menu (same as the one echo'ed) is returned. How can it return an menu when none were specified.
  • If I specify an invalid menu name / location (i.e., it's not registered), it returns a random array.
  • For the menu it is returning, Admin > Appearance > Menus, I've unchecked all the Display Locations. That is, the menu does exit, but it's not associated with any locations. Still, wp_nav_menu() returns this menu.

I've done some other variations on the above trying to get empty or null back and I get a menu.

Long to short, I'm getting results when - afaik - I shouldn't be getting anything at all.

I'm going to add a check against the global $_wp_registered_nav_menus before I do anything with wp_nav_menu(), perhaps wp_nav_menu() should do similar?

I assigned a Severity = major mainly because this is a common function that gets used A LOT. I would think / hope it should, at this point, work flawlessly.

Change History (3)

#1 @ChiefAlchemist
6 years ago

Opps. I said

If I specify an invalid menu name / location (i.e., it's not registered), it returns a random array.

but meant to say

If I specify an invalid menu name / location (i.e., it's not registered), it returns a random MENU.

#2 @ChiefAlchemist
6 years ago

Deleted

Last edited 6 years ago by ChiefAlchemist (previous) (diff)

#3 @anuj2
5 years ago

In the core file wp-includes/nav-menu-template.php

// get the first menu that has items if we still can't find a menu
	if ( ! $menu && ! $args->theme_location ) {
		$menus = wp_get_nav_menus();
		foreach ( $menus as $menu_maybe ) {
			if ( $menu_items = wp_get_nav_menu_items( $menu_maybe->term_id, array( 'update_post_term_cache' => false ) ) ) {
				$menu = $menu_maybe;
				break;
			}
		}
	}

It is stated that if the menu passed in the arguments in not found then get the first menu that has items.

Last edited 5 years ago by anuj2 (previous) (diff)
Note: See TracTickets for help on using tickets.