函数文档

wp_get_associated_nav_menu_items()

💡 云策文档标注

概述

wp_get_associated_nav_menu_items() 函数用于检索与特定对象关联的导航菜单项 ID 数组。它通过查询 nav_menu_item 帖子类型,并基于对象 ID 和类型进行筛选,适用于 WordPress 开发者处理菜单项关联逻辑。

关键要点

  • 函数返回与指定对象关联的菜单项 ID 数组,若无关联则返回空数组。
  • 参数包括 $object_id(对象 ID,默认 0)、$object_type(对象类型,如 'post_type' 或 'taxonomy',默认 'post_type')和 $taxonomy(当 $object_type 为 'taxonomy' 时指定分类法名称,默认空)。
  • 内部使用 WP_Query 查询 nav_menu_item 帖子类型,并通过元数据 _menu_item_object_id 和 _menu_item_type 进行匹配。
  • 支持 post_type 和 taxonomy 两种对象类型,确保菜单项类型与对象类型一致,对于 taxonomy 还需检查 _menu_item_object 元数据。

代码示例

// 示例:获取与文章 ID 为 123 关联的菜单项 ID
$menu_item_ids = wp_get_associated_nav_menu_items( 123, 'post_type' );
// 返回数组,如 [45, 67],表示菜单项 ID 列表

注意事项

  • 函数在 WordPress 3.0.0 版本引入,使用时需确保版本兼容性。
  • 返回的 ID 数组经过 array_unique 处理,避免重复项。
  • 对于 taxonomy 类型,必须提供正确的 $taxonomy 参数以确保准确匹配。

📄 原文内容

Returns the menu items associated with a particular object.

Parameters

$object_idintoptional
The ID of the original object. Default 0.
$object_typestringoptional
The type of object, such as 'post_type' or 'taxonomy'.
Default 'post_type'.
$taxonomystringoptional
If $object_type is 'taxonomy', $taxonomy is the name of the tax that $object_id belongs to. Default empty.

Return

int[] The array of menu item IDs; empty array if none.

Source

function wp_get_associated_nav_menu_items( $object_id = 0, $object_type = 'post_type', $taxonomy = '' ) {
	$object_id     = (int) $object_id;
	$menu_item_ids = array();

	$query      = new WP_Query();
	$menu_items = $query->query(
		array(
			'meta_key'       => '_menu_item_object_id',
			'meta_value'     => $object_id,
			'post_status'    => 'any',
			'post_type'      => 'nav_menu_item',
			'posts_per_page' => -1,
		)
	);
	foreach ( (array) $menu_items as $menu_item ) {
		if ( isset( $menu_item->ID ) && is_nav_menu_item( $menu_item->ID ) ) {
			$menu_item_type = get_post_meta( $menu_item->ID, '_menu_item_type', true );
			if (
				'post_type' === $object_type &&
				'post_type' === $menu_item_type
			) {
				$menu_item_ids[] = (int) $menu_item->ID;
			} elseif (
				'taxonomy' === $object_type &&
				'taxonomy' === $menu_item_type &&
				get_post_meta( $menu_item->ID, '_menu_item_object', true ) === $taxonomy
			) {
				$menu_item_ids[] = (int) $menu_item->ID;
			}
		}
	}

	return array_unique( $menu_item_ids );
}

Changelog

Version Description
3.0.0 Introduced.