2

I am using wp_nav_menu() and I want to add the search box as a part of the menu.

I am having trouble figuring it out and was hoping for some assistance:

My code:

        <?php 
        $args = array('theme_location' => 'primary', 'container' => false);
        wp_nav_menu( $args ); 
        ?>

Now I want to add an additional <li> element to the end or the menu <ul> and all I want in the <li> is the output of:

        <?php get_search_form();?>

Can this be done?

functions.php:

add_action('init', 'register_top_menu');

function register_top_menu() {
    register_nav_menu('primary', __('Top Menu', 'leeaenergy'));
}


add_filter('wp_nav_menu_items','add_search', 10, 2);

function add_search($items, $args) {

    if( $args->theme_location == 'primary' )
    return $items . '<li>'.get_search_form().'</li>';
}

1 Answer 1

3

Yes you need to use a filter. Add the following code to your functions.php file. Change the theme_location to whatever is set up for your current theme:

add_filter( 'wp_nav_menu_items', 'add_search', 10, 2 );

function add_search( $items, $args ) {
    if ( $args->theme_location == 'primary' ) {
        return $items . '<li>' . get_search_form() . '</li>';
    }
}
Sign up to request clarification or add additional context in comments.

5 Comments

tried that but nothing has changed what else do I need to have in place?
That's all you need. Try removing the if statement and see if it adds it to all menus
the problem is with the menu not registering... I think it was just displaying all pages - I finally "sort of" have the menu regsitered and I found another way to do it but that is presenting issues as well... F*ing painful!!! Anyway, I'll keep battling... thanks
BTW I can't test this until I figure out this menu stuff so I can't confirm or deny that it works.
You have to use get_search_form( false ) to prevent it echoing.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.