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
Hello Sridhar,
I can see that your code is simpler than the regular way of adding Nav Extras. But what advantage would not storing this in the output buffer give? Less memory used?
Thank you,
Richard
I am not certain whether it will improve the performance by using less memory.
Code wise, it certainly is cleaner.
One day when I buy a PHP book and read it all, I’ll come here and add an update.
Can I borrow that PHP book when you’ve finished with it? 😉
Sure.
I have had http://www.phptherightway.com/ open in a tab for 3 days now. But have so much to do and share..
Nice! Although doesn’t work in the mobile/collapsed menu?
I just tested this in the current latest version of Genesis Sample and do see the search box in the mobile menu.
(Just needs styling)
OK, yup I see it fine with Sample. I was trying with Agency Pro. Maybe I need to make some other adjustments to get it to work on all themes.
Just delete or comment out
from the 1023px media query.
[…] poner la caja de búsqueda en el menú podemos utilizar este código de Sridhar Katakam que deberéis colocar en el archivo functions.php de vuestra […]