Get children from navigation in WP3+

Even though I love WordPress’s new menu management system (WP3+), there are times it would be nice for it to pull all the children of a particular menu item into the menu automagically..

/**    Retrieve any posts that are assigned to a post as children through the nav menu
 *    system in WordPress 3.0+
 *
 *    @param    integer    The ID of the parent post
 *    @return    array    Any menu items that are children of the menu item for this post
 */
function get_menu_children( $parent ) {

    global $wpdb;

    // menu items are stored as a custom post type in the wp_posts table. Each one
    // points to an "actual" post that we'll need to retrieve.

    $result = $wpdb->get_results( "select * from $wpdb->posts where post_type='nav_menu_item' AND post_parent='$parent'" );

    if( !count( $result ) ) {

        // no children found -- let's get out of here!
        return false;
    }

    // use the menu items we've retrieved to populate an array with the "actual" posts

    $posts = array();

    foreach( $result as $menu_item ) {

        // find the post and push it onto our list

        $post_id = get_post_meta( $menu_item->ID, '_menu_item_object_id', true );
        $posts[] = get_post( $post_id );
    }

    return $posts;
}

Let’s keep in touch

Get noise-free updates on software, product, and process.

Hey, I'm RJ: digital entomologist and intermittent micropoet, writing from the beautiful Rose City.