Dynamically Add a Sub-menu Item to wp_nav_menu

This function will add a sub-menu item to an existing menu item in wp_nav_menu, only if a user is logged in.

Replace ‘main-menu’ on line 8 with the Theme Location of the menu that you want to modify. Use the slug of the location name. Find the Theme Location name in “Appearance -> Menus -> Manage Locations.”

Replace ‘99999’ on line 9 with the ID number of the existing menu item which you want to modify. To find this, go to “Appearance –> Menus.” Under “Menu Structure,” find your desired menu item. Hover over its drop-down arrow and its ID number will appear in your status bar at the bottom of your browser window.

Replace ‘99254’ on line 10 with any unique ID number which is not currently being used by another menu item on your WordPress site. A random 4 or 5 digit number should work.

Replace ‘Log out’ on line 11 with your desired text for the new sub-menu item.

On line 12, set $url to the URL which the new menu item will link to. This example uses the WP log-out link which simply logs the user out.

Optionally, you can pass a custom CSS class to the menu item on line 28.

/**
* Dynamically add a sub-menu item to an existing menu item in wp_nav_menu
* only if a user is logged in.
*/
 
 function isa_dynamic_submenu_logout_link( $items, $args ) {
 
    $theme_location = 'main-menu';// Theme Location slug
    $existing_menu_item_db_id = 99999;
    $new_menu_item_db_id = 99254; // unique id number
    $label = 'Log out';
    $url = wp_logout_url(get_permalink());
    
    if ( $theme_location !== $args->theme_location ) {
        return $items;
    }
    
 
    if ( is_user_logged_in() ) {
         
        // only if user is logged-in, do sub-menu link
        $item = array(
            'title'            => $label,
            'menu_item_parent' => $existing_menu_item_db_id,
            'ID'               => 'log-out',
            'db_id'            => $new_menu_item_db_id,
            'url'              => $url,
           // 'classes'          => array( 'custom-menu-item' )// optionally add custom CSS class
        );
 
	$items[] = (object) $item;
     }
 
    return $items;
}
add_filter( 'wp_nav_menu_objects', 'isa_dynamic_submenu_logout_link', 10, 2 );

See more:

We've 5 Responses

  1. February 16th, 2016 at 8:09 am

    Thank you so much! Your example is just what I was looking for.

    I have a project that requires adding items created using a custom taxonomy to a submenu without the user having to manually modify the existing menu whenever a new item is created on the fly. I can modify your sample script to populate the submenu in this manner.

    dyl604

Questions and Comments are Welcome

Your email address will not be published. All comments will be moderated.

Please wrap code in "code" bracket tags like this:

[code]

YOUR CODE HERE 

[/code]