The code snippet for appending a search box in Primary or Secondary Navigation menu currently uses output buffering to display the output of get_search_form() like this:
ob_start(); | |
get_search_form(); | |
$search = ob_get_clean(); | |
$menu .= '<li class="right search">' . $search . '</li>'; |
We can simply use the false parameter in get_search_form() to return the search form as a string instead of echoing thus avoiding storing it in buffer.
$menu .= '<li class="right search">' . get_search_form( false ) . '</li>'; |
Here’s the full code:
<?php | |
//* Do NOT include the opening php tag | |
add_filter( 'wp_nav_menu_items', 'theme_menu_extras', 10, 2 ); | |
/** | |
* Filter menu items, appending a search form. | |
* | |
* @param string $menu HTML string of list items. | |
* @param stdClass $args Menu arguments. | |
* | |
* @return string Amended HTML string of list items. | |
*/ | |
function theme_menu_extras( $menu, $args ) { | |
//* Change 'primary' to 'secondary' to add search form to the secondary navigation menu | |
if ( 'primary' !== $args->theme_location ) | |
return $menu; | |
$menu .= '<li class="right search">' . get_search_form( false ) . '</li>'; | |
return $menu; | |
} |
References:
http://codex.wordpress.org/Function_Reference/get_search_form