52
Hola amigos, today’s snippet actually comes from my own website. You might have noticed there is a little “magnifying glass” in the navigation menu which scrolls down to a search bar.
Mine, specifically, searches exclusively for blog posts (I excluded pages, products, etc.), but you can customize this and make it search for products only for example. Here’s how I did it – hopefully you can learn something new today!
PHP Snippet: Add a custom search bar to your WooCommerce header/footer
/**
* @snippet WooCommerce Custom Search Bar
* @how-to Get tutoraspire.com FREE
* @sourcecode https://tutoraspire.com/?p=21175
* @author Tutor Aspire
* @compatible WooCommerce 3.5.7
* @donate $9 https://tutoraspire.com
*/
// ----------------------------------
// 1. ADD SEARCH TO STOREFRONT FOOTER
add_action( 'storefront_footer', 'tutoraspire_add_search_to_footer' );
function tutoraspire_add_search_to_footer() {
get_search_form();
}
// ----------------------------------
// 2. LIMIT SEARCH TO POSTS OR PRODUCTS ONLY
function SearchFilter($query) {
if ( !is_admin() && $query->is_search ) {
$query->set('post_type', 'post'); // OR USE 'PRODUCT'
}
return $query;
}
add_filter( 'pre_get_posts', 'SearchFilter' );
// ----------------------------------
// 3. CHANGE PLACEHOLDER & BUTTON TEXT
function tutoraspire_storefront_search_form_modify( $html ) {
return str_replace( array('Search …','Search'), array('WooCommerce Hooks, Storefront Theme, Google AdWords...','Search Article'), $html );
}
add_filter( 'get_search_form', 'tutoraspire_storefront_search_form_modify' );
// ------------------------------
// 4. ADD SEARCH ICON TO NAVIGATION MENU
function tutoraspire_new_nav_menu_items($items) {
$searchicon = '
‘;
$items = $items . $searchicon;
return $items;
}
add_filter( ‘wp_nav_menu_additional-resources_items’, ‘tutoraspire_new_nav_menu_items’ );
That’s it 🙂 Now give my search box a go to see if it works!