函数文档

has_nav_menu()

💡 云策文档标注

概述

has_nav_menu() 函数用于检查已注册的导航菜单位置是否分配了菜单。它接受一个位置标识符参数,返回布尔值表示是否有菜单分配。

关键要点

  • 参数 $location 为必需的字符串,表示菜单位置标识符。
  • 返回布尔值,指示该位置是否有菜单分配。
  • 内部通过 get_registered_nav_menus() 和 get_nav_menu_locations() 函数验证位置和菜单分配状态。
  • 包含 apply_filters('has_nav_menu', $has_nav_menu, $location) Hook,允许过滤结果。

代码示例

if ( has_nav_menu( 'primary' ) ) {
    wp_nav_menu( array( 'theme_location' => 'primary' ) );
}

📄 原文内容

Determines whether a registered nav menu location has a menu assigned to it.

Parameters

$locationstringrequired
Menu location identifier.

Return

bool Whether location has a menu.

Source

function has_nav_menu( $location ) {
	$has_nav_menu = false;

	$registered_nav_menus = get_registered_nav_menus();
	if ( isset( $registered_nav_menus[ $location ] ) ) {
		$locations    = get_nav_menu_locations();
		$has_nav_menu = ! empty( $locations[ $location ] );
	}

	/**
	 * Filters whether a nav menu is assigned to the specified location.
	 *
	 * @since 4.3.0
	 *
	 * @param bool   $has_nav_menu Whether there is a menu assigned to a location.
	 * @param string $location     Menu location.
	 */
	return apply_filters( 'has_nav_menu', $has_nav_menu, $location );
}

Hooks

apply_filters( ‘has_nav_menu’, bool $has_nav_menu, string $location )

Filters whether a nav menu is assigned to the specified location.

Changelog

Version Description
3.0.0 Introduced.

User Contributed Notes