We learned how to use add_filter to hook a function or a method to a specific filter action.
We also learned to use applt_filters to call the functions that have been added to the filter hook.
We are going to use the same applt_filters function to modify the menu in WordPress.
Side note: WordPress has another function wp_nav_menu to display the menu.
Syntax
apply_filters( 'wp_nav_menu_items', $items, $args )
Where $items is the HTML list content for the menu items. It must be a string. $args is an object containing wp_nav_menu() arguments.
Example 1: This is how we can modify the menu.
function add_search_form($items, $args) {
if( $args->theme_location == 'main-menu' ){
$items .= ' '
. ''
. ' ';
}
return $items;
}
add_filter('wp_nav_menu_items', 'add_search_form', 10, 2);
Replace “main-menu” with your menu id in the code above. Adjust any other style if you want.
Example 2
add_filter( 'wp_nav_menu_items', 'add_extra_item_to_nav_menu', 10, 2 );
function add_extra_item_to_nav_menu( $items, $args ) {
if (is_user_logged_in() && $args->menu == 303) {
$items .= ' My Account ';
}
elseif (!is_user_logged_in() && $args->menu == 303) {
$items .= 'Sign in / Register ';
}
return $items;
}
Same like the example before, replace “303” with your menu id in the code above. Adjust any other style if you want.
Adding the code 303 will replace it with whatever your menu id is.
Example 3: the simplest solution
add_filter('wp_nav_menu_items', 'add_search_in_menu', 10, 2);
function add_search_in_menu($items, $args) {
if( $args->theme_location == 'primary' )
$items .= ' ';
return $items;
}
You can attach the search form as well into the hook above. Then display it using JavaScript.
Credit goes to this page: WordPress wp_nav_menu_items hook
add_filter apply_filters functions link menu