wp_nav_menu_items

Home » Hooks » wp_nav_menu_items

The wp_nav_menu_items hook is a filter that allows developers to customize the navigation menu items in WordPress. This hook is used to add or remove items from the navigation menu, or to modify the attributes of existing items.

When WordPress generates a navigation menu, it first generates a list of menu items. These items are then passed through the wp_nav_menu_items filter, which allows developers to modify the list as needed. The filter receives two arguments: the list of menu items, and the arguments passed to the wp_nav_menu function.

Developers can use this hook to add custom menu items to the navigation menu, such as links to custom post types or custom pages. They can also use it to remove or modify existing menu items, such as changing the link URL or adding a CSS class.

Here’s an example usage code for this hook:

function my_nav_menu_items($items, $args) {
    // add a custom menu item to the end of the menu
    $items .= '<li><a href="#">Custom Link</a></li>';
    return $items;
}
add_filter('wp_nav_menu_items', 'my_nav_menu_items', 10, 2);

In this example, we’re using the wp_nav_menu_items filter to add a custom menu item to the end of the navigation menu. The function my_nav_menu_items is hooked into the filter using the add_filter function, and it receives two arguments: the list of menu items and the arguments passed to the wp_nav_menu function. The function adds a new menu item to the end of the list and returns the modified list.

Overall, the wp_nav_menu_items hook is a powerful tool for customizing the navigation menu in WordPress, allowing developers to create custom menus that fit their site’s unique needs.

Learn More on WordPress.org

Register an account to save your snippets or go Pro to get more features.