phpwordpressheadernavwp-nav-menu-item

wp_nav_menu_items - First position in the nav menu


I am using the following code to add a search box into the navigation menu:

add_filter( 'wp_nav_menu_items','add_search_box', 10, 2 );
function add_search_box( $items, $args ) {
   $items .= '<li class="menu-searchbox">' . get_search_form( false ) . '</li>';
   return $items;
}

It works great, but it adds the search box at the end of the menu as the last <li> item

Is there any way the search box could be added as the first item on the menu?


Solution

  • Try this code

    add_filter( 'wp_nav_menu_items','add_search_box', 10, 2 );
    function add_search_box( $items, $args ) {
        $searchbox = '<li class="menu-searchbox">' . get_search_form( false ) . '</li>';
    
        return $searchbox.$items;
    }