获取与特定对象关联的菜单项。

原型

wp_get_associated_nav_menu_items( int $object_id, string $object_type = 'post_type', string $taxonomy = '' )

参数

$object_id (int) (Required) 原始对象的ID。

$object_type (string) (Optional) 对象的类型,例如“taxonomy”或“post_type”。

$taxonomy (string) (Optional) 如果$ object_type是“taxonomy”,$ taxonomy是$ object_id所属的税的名称

返回值

(array)  菜单项ID数组;空数组,如果没有;

源文件

路径:wp-includes/nav-menu.php

<?php
...
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 );
}
...
?>

其他

英文文档:https://developer.wordpress.org/reference/functions/wp_get_associated_nav_menu_items/