wp_get_nav_menu_name()WP 4.9.0

Gets the menu name for the specified location in the admin.

The function retrieves an array of registered menu locations, checks for the required one, gets the menu object via wp_get_nav_menu_object(), and then returns its property name, or an empty string if no menu is assigned to the location.

If the location is not assigned to a menu or the menu has no name, an empty string is returned.

Used in themes to output dynamic menu titles, for example above <ul> before wp_nav_menu().

The obtained name can be filtered through wp_get_nav_menu_name, for example for translation or adding a prefix.

You can register a location for the menu using the function register_nav_menu().

Hooks from the function

Returns

String. The name of the menu or an empty string if there is no menu.

Usage

wp_get_nav_menu_name( $location );
$location(string) (required)
Identifier of the menu location specified in the register_nav_menu() function during registration, for example primary, footer.

Examples

0

#1 Register menu area and display the menu name

  • Register a menu area with the identifier primary and the name Main Menu.
  • In the admin panel, create a menu called "Header Menu" and give it a menu area of Main Menu.
  • Display the menu name assigned to the menu area with the identifier primary.

// Register the "Main menu" menu area with the identifier "primary"
add_action( 'after_setup_theme', 'theme_register_nav_menu' );

function theme_register_nav_menu() {
	register_nav_menu('primary', 'Main menu' );
}

// Get the name of the menu assigned to the "primary" area
$name_menu = wp_get_nav_menu_name( $location );

// Menu name output
echo $name_menu; //> Header menu
0

#2 Output the name of the menu before displaying the menus items to the user

$locations = get_nav_menu_locations();
$menu = wp_get_nav_menu_object( $locations['registered-menu-location-slug'] );

echo '<div class="footer-menu__title">' . esc_html( $menu->name ) . '</div>';

Changelog

Since 4.9.0 Introduced.

wp_get_nav_menu_name() code WP 6.8.1

function wp_get_nav_menu_name( $location ) {
	$menu_name = '';

	$locations = get_nav_menu_locations();

	if ( isset( $locations[ $location ] ) ) {
		$menu = wp_get_nav_menu_object( $locations[ $location ] );

		if ( $menu && $menu->name ) {
			$menu_name = $menu->name;
		}
	}

	/**
	 * Filters the navigation menu name being returned.
	 *
	 * @since 4.9.0
	 *
	 * @param string $menu_name Menu name.
	 * @param string $location  Menu location identifier.
	 */
	return apply_filters( 'wp_get_nav_menu_name', $menu_name, $location );
}