Introduction
This article describes two scenarios to modify the navigation menu items using the ‘wp_nav_menu_items‘ filter .
1. Append a new menu item to the menu
This example is to add a menu item labelled ‘Book An Appointment’ which calls a Calendly popup. Add the below code to functions.php (or plugin).
// ^^^Add 'Appointment' menu item to Menu
function add_appointment_item($items, $args) {
if( $args->theme_location == 'primary' ){
$items .= '<li class="menu-item menu-item-type-post_type menu-item-object-page">'
. '<a href="" onclick="Calendly.initPopupWidget({url: \'https://calendly.com/roger-gordon73?hide_landing_page_details=1\'});return false;">Book An Appointment</a>'
.'</li>';
}
return $items;
}
add_filter('wp_nav_menu_items', 'add_appointment_item', 10, 2);
2. Modify a menu item label by shortcode
This example is to modify a menu item label to display the log-in username. First, go to the menu and in the label field enter [ivr_show_username ]. Then add the below code to functions.php (or plugin).
//^^^ Change the menu item label using shortcode
function show_username() {
$current_user = wp_get_current_user();
return esc_html($current_user->user_login);
}
add_shortcode('ivr_show_username', 'show_username');
add_filter('wp_nav_menu_items', 'do_shortcode');
