The wp_nav_menu_items WordPress PHP filter allows you to modify the HTML list content of navigation menus.
Usage
add_filter('wp_nav_menu_items', 'your_function_name', 10, 2); function your_function_name($items, $args) { // your custom code here return $items; }
Parameters
- $items (string) – The HTML list content for the menu items.
- $args (stdClass) – An object containing wp_nav_menu() arguments.
Returns
The filter returns the modified $items string with your custom code applied.
More information
See WordPress Developer Resources: wp_nav_menu_items
Examples
Add a “Home” link to the menu
To add a “Home” link at the beginning of the menu, use the following code:
add_filter('wp_nav_menu_items', 'add_home_link', 10, 2); function add_home_link($items, $args) { $home_link = '<li><a href="' . home_url('/') . '">Home</a></li>'; $items = $home_link . $items; return $items; }
Add a “Login” or “Logout” link to the menu
To add a “Login” or “Logout” link at the end of the menu depending on the user’s authentication status:
add_filter('wp_nav_menu_items', 'add_login_logout_link', 10, 2); function add_login_logout_link($items, $args) { if (is_user_logged_in()) { $items .= '<li><a href="' . wp_logout_url() . '">Logout</a></li>'; } else { $items .= '<li><a href="' . wp_login_url() . '">Login</a></li>'; } return $items; }
Remove specific menu item by ID
To remove a specific menu item by ID (replace 123
with the desired menu item ID):
add_filter('wp_nav_menu_items', 'remove_menu_item_by_id', 10, 2); function remove_menu_item_by_id($items, $args) { $menu_item_id = 123; $items = preg_replace('/<li id="menu-item-' . $menu_item_id . '.*?<\/li>/', '', $items); return $items; }
Add a CSS class to menu items
To add a custom CSS class to all menu items:
add_filter('nav_menu_css_class', 'add_custom_menu_class', 10, 2); function add_custom_menu_class($classes, $item) { $classes[] = 'custom-menu-item-class'; return $classes; }
Add a “Search” form to the menu
To add a search form at the end of the menu:
add_filter('wp_nav_menu_items', 'add_search_form', 10, 2); function add_search_form($items, $args) { $search_form = '<li class="menu-search">' . get_search_form(false) . '</li>'; $items .= $search_form; return $items; }