How to get IDs for objects in menu branch?

I am lazy to write supporting logic from scratch so I am reusing functions from linked answer on branches:

/**
 * Retrieve IDs of posts in branch of menu.
 *
 * @param mixed  $menu
 * @param string $branch_title
 *
 * @link http://wordpress.stackexchange.com/questions/2802/display-a-portion-branch-of-the-menu-tree-using-wp-nav-menu
 *
 * @return array
 */
function get_post_ids_from_menu_branch( $menu, $branch_title ) {

    $menu_object = wp_get_nav_menu_object( $menu );
    $menu_items  = wp_get_nav_menu_items( $menu_object->term_id );
    $items       = submenu_limit( $menu_items, (object) array( 'submenu' => $branch_title ) );
    $items       = wp_list_filter( $items, array( 'object' => 'post' ) );
    $ids         = wp_list_pluck( $items, 'object_id' );

    return $ids;
}

// example
var_dump( get_post_ids_from_menu_branch( 'Test menu', 'Level 1' ) );

Leave a Comment