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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 | /** * 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 ); |
Leonie
April 8th, 2015 at 3:39 pm
Thank you so much for sharing this, it works like a charm đ
Aurovrata
October 1st, 2015 at 3:31 am
you should check out the plugin Shortcodes in Menu, its a neat way to do this with the power of shortcodes.
Isabel
October 2nd, 2015 at 10:48 am
Sounds good, thanks.
dyl604
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.
Hugh
September 1st, 2018 at 12:12 pm
The following no longer works:
$theme_location = 'main-menu';// Theme Location slug
'main-menu'
needs changing to:
'main_menu'
Great script thanks!