How to get content from WordPress submenu only

wp_nav_manu() displays a navigation menu. We can call different menu by assigning a different $menu. But the is no straightforward function to get only a submenu. For example, we may want to display a submenu on the sidebar for easier navigation.

The following code snippet can do just that. Simply add a submenu in arguments for the function wp_nav_menu(), and pass the first-level menu item name that has the submenu we need for display.

Add following code in function.php, or your own custom plugin.

add_filter( 'wp_nav_menu_objects', 'submenu_limit', 10, 2 );

function submenu_limit( $items, $args ) {

    if ( empty($args->submenu) ) {
        return $items;
    }

    $parent_id = array_pop( wp_filter_object_list( $items, array( 'title' => $args->submenu ), 'and', 'ID' ) );
    $children  = submenu_get_children_ids( $parent_id, $items );

    foreach ( $items as $key => $item ) {

        if ( ! in_array( $item->ID, $children ) ) {
            unset($items[$key]);
        }
    }

    return $items;
}

function submenu_get_children_ids( $id, $items ) {

    $ids = wp_filter_object_list( $items, array( 'menu_item_parent' => $id ), 'and', 'ID' );

    foreach ( $ids as $id ) {
        $ids = array_merge( $ids, submenu_get_children_ids( $id, $items ) );
    }

    return $ids;
}

 

For instance, I would like to display submenu content from “Dropbox”.

wordpress-menu-structure

Here is how to make the call:

$args = array(
    'menu'    => 'Main',
    'submenu' => 'Dropbox',
);

wp_nav_menu( $args );

 

 

Comments are closed.

Post Navigation