不确定这是否足够健壮,但它显示了通过菜单的基本遍历,首先查找当前帖子,然后再查找其菜单父项:
/**
* @param mixed $menu
* @param int $post_id
*
* @return WP_Post|bool
*/
function get_menu_parent( $menu, $post_id = null ) {
$post_id = $post_id ? : get_the_ID();
$menu_items = wp_get_nav_menu_items( $menu );
$parent_item_id = wp_filter_object_list( $menu_items, array( \'object_id\' => $post_id ), \'and\', \'menu_item_parent\' );
if ( ! empty( $parent_item_id ) ) {
$parent_item_id = array_shift( $parent_item_id );
$parent_post_id = wp_filter_object_list( $menu_items, array( \'ID\' => $parent_item_id ), \'and\', \'object_id\' );
if ( ! empty( $parent_post_id ) ) {
$parent_post_id = array_shift( $parent_post_id );
return get_post( $parent_post_id );
}
}
return false;
}