The customize_nav_menu_searched_items WordPress PHP filter allows you to modify the available menu items during a search request.
Usage
add_filter('customize_nav_menu_searched_items', 'your_custom_function', 10, 2); function your_custom_function($items, $args) { // your custom code here return $items; }
Parameters
$items
(array): The array of menu items.$args
(array): Includes ‘pagenum’ and ‘s’ (search) arguments.
More information
See WordPress Developer Resources: customize_nav_menu_searched_items
Examples
Exclude specific menu items from search results
This code excludes menu items with IDs 5 and 7 from search results.
add_filter('customize_nav_menu_searched_items', 'exclude_menu_items_from_search', 10, 2); function exclude_menu_items_from_search($items, $args) { $excluded_items = array(5, 7); foreach ($items as $key => $item) { if (in_array($item->ID, $excluded_items)) { unset($items[$key]); } } return $items; }
Limit search results to specific menu items
This code limits search results to menu items with IDs 10 and 12.
add_filter('customize_nav_menu_searched_items', 'limit_search_results_to_specific_items', 10, 2); function limit_search_results_to_specific_items($items, $args) { $allowed_items = array(10, 12); $new_items = array(); foreach ($items as $item) { if (in_array($item->ID, $allowed_items)) { $new_items[] = $item; } } return $new_items; }
Add a custom attribute to menu items in search results
This code adds a custom attribute ‘data-custom’ to menu items in search results.
add_filter('customize_nav_menu_searched_items', 'add_custom_attribute_to_search_results', 10, 2); function add_custom_attribute_to_search_results($items, $args) { foreach ($items as $item) { $item->attr_title = 'data-custom'; } return $items; }
Add a custom class to menu items in search results
This code adds a custom class ‘search-result-item’ to menu items in search results.
add_filter('customize_nav_menu_searched_items', 'add_custom_class_to_search_results', 10, 2); function add_custom_class_to_search_results($items, $args) { foreach ($items as $item) { $item->classes[] = 'search-result-item'; } return $items; }
Change menu item URL based on search query
This code changes the menu item URL to include the search query as a parameter.
add_filter('customize_nav_menu_searched_items', 'change_menu_item_url_based_on_search', 10, 2); function change_menu_item_url_based_on_search($items, $args) { $search_query = urlencode($args['s']); foreach ($items as $item) { $item->url = add_query_arg('search', $search_query, $item->url); } return $items; }