WP_nav_menu separate submenu output

Use xPath to define which part of the menu do you want to output. By default it outputs menu starting at 2nd level.

Code Snippet:


 * WP_nav_menu separate submenu output.
 * Optional $args contents:
 * string theme_location - The menu that is desired.  Accepts (matching in order) id, slug, name. Defaults to blank.
 * string xpath - Optional. xPath syntax.
 * string before - Optional. Text before the menu tree.
 * string after - Optional. Text after the menu tree.
 * bool echo - Optional, default is TRUE. Whether to echo the menu or return it.
 * @param array $args Arguments
 * @return String If $echo value is set to FALSE.
function px_the_submenu( $args = array() )
    $defaults = array(
        'theme_location' => '',
        'xpath' => "./li[contains(@class,'current-menu-item') or contains(@class,'current-menu-ancestor')]/ul",
        'before' => '',
        'after' => '',
        'echo' => true
    $args = wp_parse_args( $args, $defaults );
    $args = (object) $args;
    $output = array();
    $menu_tree = wp_nav_menu( array( 'theme_location' => $args->theme_location, 'container' => '', 'echo' => false ) );
    $menu_tree_XML = new SimpleXMLElement( $menu_tree );
    $path = $menu_tree_XML->xpath( $args->xpath );
    $output[] = $args->before;
    if( ! empty( $path ) )
        $output[] = $path[0]->asXML();
    $output[] = $args->after;
    if( $args->echo )
        echo implode('', $output );
        return implode('', $output );


Comments  Leave a Reply

Add a Comment

We're glad you have chosen to leave a comment. Please keep in mind that all comments are moderated according to our privacy policy, and all links are nofollow. Do NOT use keywords in the name field. Let's have a personal and meaningful conversation.

WordPress Launch Checklist

The Ultimate WordPress Launch Checklist

We've compiled all the essential checklist items for your next WordPress website launch into one handy ebook.
Yes, Send Me the Free eBook!