wp_get_nav_menu_object()WP 3.0.0

Returns a navigation menu object.

1 time — 0.000026 sec (very fast) | 50000 times — 0.24 sec (very fast)
Hooks from the function

Return

WP_Term|false. Menu object on success, false if $menu param isn't supplied or term does not exist.

Usage

wp_get_nav_menu_object( $menu );
$menu(int|string|WP_Term) (required)
Menu ID, slug, name, or object.

Examples

1

#1 Demo

// By name.
$menu = wp_get_nav_menu_object( 'wpdocs mainmenu' );

// By slug.
$menu = wp_get_nav_menu_object( 'wpdocs-mainmenu' );

// By ID.
$menu_name = 'wpdocs mainmenu';
$menu_obj  = get_term_by( 'name', $menu_name, 'nav_menu' );
$menu_id   = $menu_obj->term_id;
$menu = wp_get_nav_menu_object( $menu_id );

// By location.
$menu_name = 'primary';
$locations = get_nav_menu_locations();
$menu_id   = $locations[ $menu_name ] ;
wp_get_nav_menu_object( $menu_id );
0

#2 Get the menu object

Suppose we have a menu location name: my_menu_location registered with register_nav_menu(). And we created a menu in the admin and attached it to that location. Then:

$locations = get_nav_menu_locations();

if( isset( $locations['my_menu_location'] ) ){

	$items = wp_get_nav_menu_object( $locations['my_menu_location'] );
	print_r( $items );

	/* will output
	stdClass Object
	(
		[term_id] => 693
		[name] => Panel
		[slug] => panel
		[term_group] => 0
		[term_taxonomy_id] => 701
		[taxonomy] => nav_menu
		[description] => 
		[parent] => 0
		[count] => 1
		[filter] => raw
	)
	*/  
}

Changelog

Since 3.0.0 Introduced.

Code of wp_get_nav_menu_object() WP 6.0.1

function wp_get_nav_menu_object( $menu ) {
	$menu_obj = false;

	if ( is_object( $menu ) ) {
		$menu_obj = $menu;
	}

	if ( $menu && ! $menu_obj ) {
		$menu_obj = get_term( $menu, 'nav_menu' );

		if ( ! $menu_obj ) {
			$menu_obj = get_term_by( 'slug', $menu, 'nav_menu' );
		}

		if ( ! $menu_obj ) {
			$menu_obj = get_term_by( 'name', $menu, 'nav_menu' );
		}
	}

	if ( ! $menu_obj || is_wp_error( $menu_obj ) ) {
		$menu_obj = false;
	}

	/**
	 * Filters the nav_menu term retrieved for wp_get_nav_menu_object().
	 *
	 * @since 4.3.0
	 *
	 * @param WP_Term|false      $menu_obj Term from nav_menu taxonomy, or false if nothing had been found.
	 * @param int|string|WP_Term $menu     The menu ID, slug, name, or object passed to wp_get_nav_menu_object().
	 */
	return apply_filters( 'wp_get_nav_menu_object', $menu_obj, $menu );
}