Debugging – trying to add search box to menus

wp_nav_menu_items aren’t mentioned in the codex, so there are no concrete description on how to use it.

wp_nav_menu_items can be found on line 347 in

wp-includes/nav-menu-template.php

$items = apply_filters( 'wp_nav_menu_items', $items, $args );

within wp_nav_menu.

In the codex, it states the following

Displays a navigation menu created in the Appearance → Menus panel.

So this means that wp_nav_menu_items is only fired when a navigation menu is present that was created in the “menus” panel, and not on the default navigation menu. It is a design flaw in my opinion. wp_nav_menu_items should actually be included in the default menu as well. This is also one aspect that is not mentioned in any of the tutorials I’ve tested.

There is another filter that I’ve tested, wp_list_pages, that seems to work as expected.

There is a problem with your code though as well. When I add it to the default nav bar, any searches I do sents me to my db. Actually again. I could not get proper examples to work. I eventually found this code in a plugin called search-box-on-navigation-menu.

<?php
add_filter('wp_nav_menu_items','add_search_box', 10, 2);
function add_search_box($items, $args) {

        ob_start();
        get_search_form();
        $searchform = ob_get_contents();
        ob_end_clean();

        $items .= '<li>' . $searchform . '</li>';

    return $items;
    }
?>

For this code to work on the default nav bar, just add the following line to the code add_filter('wp_list_pages','add_search_box', 10, 2);, so your end code will be

<?php
add_filter('wp_list_pages','add_search_box', 10, 2);
add_filter('wp_nav_menu_items','add_search_box', 10, 2);
function add_search_box($items, $args) {

        ob_start();
        get_search_form();
        $searchform = ob_get_contents();
        ob_end_clean();

        $items .= '<li>' . $searchform . '</li>';

    return $items;
}    
?> 

Hope this help