Search Form in PHP templates
↑ Back to topUse the woocommerce_product_search()
function to render the search facility in PHP templates.
This function accepts an array of options as described for the shortcode. See the page Shortcodes for details on the parameters that can be passed to this function.
Example code:
<?php if ( function_exists( 'woocommerce_product_search' ) ) { echo woocommerce_product_search( array( 'limit' => 20 ) ); } ?>
This code can be used in any template file, for example, you could add it to your theme’s single-product.php
template.
Replacing the default Search Form
↑ Back to topYou need to edit your theme’s searchform.php file, preferably using a child theme to preserve customizations against upgrades. More here: How to set up and use a child theme
From your parent theme’s searchform.php template file, copy it from the parent theme directory to your child theme directory and edit to conditionally output the WooCommerce Product Search (if it exists). The following snippet demonstrates one way that this might be accomplished, in this case placing it at the beginning of the searchform.php
file*.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
if ( function_exists( 'woocommerce_product_search' ) ) { | |
echo woocommerce_product_search(); | |
} else { | |
//the original contents of search.php should follow | |
//make sure to close the php tag as appropriate |
*This does not apply to Storefront and child themes based on it. For these, please refer to the section below.
Replacing the search form in Storefront themes
↑ Back to topIf using Storefront or one of the Storefront child themes, there isn’t a searchform.php file and you can use this code instead in your theme’s functions.php
– please remember to create a child theme for that, don’t put this in Storefront’s functions.php
as it will be overwritten next time you update the theme.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
function storefront_product_search() { | |
if ( function_exists('storefront_is_woocommerce_activated' ) ) { | |
if ( storefront_is_woocommerce_activated() ) { ?> | |
<div class="site-search"> | |
<?php | |
if ( function_exists( 'woocommerce_product_search' ) ) { | |
echo woocommerce_product_search(); | |
} else { | |
the_widget( 'WC_Widget_Product_Search', 'title=' ); | |
} | |
?> | |
</div> | |
<?php | |
} | |
} | |
} |