Here is the real picture I want to produce.

            <li> </li>
            <li> </li>
           ###NOT HERE ###
    ###I want to add some html here ###

I am trying as follows:

public function end_lvl( &$output, $depth = 0, $args = array() ) {
    if ( isset( $args->item_spacing ) && 'discard' === $args->item_spacing ) {
        $t = '';
        $n = '';
    } else {
        $t = "\t";
        $n = "\n";
    $indent = str_repeat( $t, $depth );
    $output .= "$indent".get_search_form(false)."</ul>{$n}";

But it appended the search box at the end of every sub menu(###NOT HERE ### section). How can I achieve the desired output. Any idea?

2 Answers 2


You should check the $depth argument to make sure the search form only appears at a certain depth/level, e.g. if( 0 === $depth ) { ... }

I personally would place the search form outside the <ul> though as I don't think it's valid HTML. It would hurt your site's accessibility. Alternatively, wrap it in a <li></li> so it's a proper list item.


I apply this trick to filter the menu:

add_filter('wp_nav_menu_items','add_search_box_to_menu', 10, 2);
    function add_search_box_to_menu( $items, $args ) {
        if( $args->theme_location == 'primary' )
            return $items."<li class='menu-header-search'><form action='http://example.com/' id='searchform' method='get'><input type='text' name='s' id='s' placeholder='Search'></form></li>";

        return $items;

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.