Created
December 27, 2024 11:58
-
-
Save SitesByYogi/d8fa960187be170a109330f76e4bdcee to your computer and use it in GitHub Desktop.
Display a product search bar on your WordPress
This file contains hidden or 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 | |
// Add this code to your theme's functions.php file or use the Code Snippets plugin. | |
/** | |
* WooCommerce Product Search Bar Shortcode | |
*/ | |
function custom_woocommerce_product_search_shortcode($atts) { | |
// Ensure WooCommerce is active | |
if (!class_exists('WooCommerce')) { | |
return '<p>WooCommerce plugin is not activated.</p>'; | |
} | |
// Extract attributes | |
$atts = shortcode_atts(array( | |
'placeholder' => 'Search for products...', // Default placeholder text | |
'button_text' => 'Search', // Default button text | |
), $atts, 'product_search'); | |
// Build the search form HTML | |
ob_start(); | |
?> | |
<form role="search" method="get" class="woocommerce-product-search" action="<?php echo esc_url(home_url('/')); ?>"> | |
<label class="screen-reader-text" for="woocommerce-product-search-field"><?php esc_html_e('Search for:', 'woocommerce'); ?></label> | |
<input | |
type="search" | |
id="woocommerce-product-search-field" | |
class="search-field" | |
placeholder="<?php echo esc_attr($atts['placeholder']); ?>" | |
value="<?php echo get_search_query(); ?>" | |
name="s" | |
/> | |
<button type="submit" class="search-submit"><?php echo esc_html($atts['button_text']); ?></button> | |
<input type="hidden" name="post_type" value="product" /> | |
</form> | |
<?php | |
return ob_get_clean(); | |
} | |
add_shortcode('product_search', 'custom_woocommerce_product_search_shortcode'); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment