X

How to Use WP_nav_menu Separate Submenu Output

Snippets by IsItWP

Are you looking for a way to use wp_nav_menu separate submenu output? While there’s probably a plugin for this, we have created a quick code snippet that you can use to use wp_nav_menu separate submenu output in WordPress.

Instructions:

All you have to do is add this code to your theme’s functions.php file or in a site-specific plugin:


/**
 * 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 );
    else
        return implode('', $output );
 
}

Note: If this is your first time adding code snippets in WordPress, then please refer to our guide on how to properly add code snippets in WordPress, so you don’t accidentally break your site.

If you liked this code snippet, please consider checking out our other articles on the site like: 9 best WordPress ad management plugins to boost revenue and how to properly create a custom login page in WordPress.

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!