WooCommerce Search Filter Setup
November 29, 2024 · AI Conversations
—
### **1. Add Categories Dropdown Before the Search Input**
You need to use a WordPress hook to modify the WooCommerce search form. Add this code to your theme’s `functions.php` file or a custom plugin:
add_filter('get_product_search_form', 'custom_woocommerce_search_form');
function custom_woocommerce_search_form($form) {
// Get product categories
$categories = get_terms([
'taxonomy' => 'product_cat',
'hide_empty' => true,
]);
// Build categories dropdown
$dropdown = '<select name="product_cat" id="product_cat">';
$dropdown .= '<option value="">' . __('All Categories', 'woocommerce') . '</option>';
foreach ($categories as $category) {
$dropdown .= sprintf(
'<option value="%s">%s</option>',
esc_attr($category->slug),
esc_html($category->name)
);
}
$dropdown .= '</select>';
// Original WooCommerce search form with dropdown added
$form = '<form role="search" method="get" class="woocommerce-product-search" action="' . esc_url(home_url('/')) . '">';
$form .= $dropdown;
$form .= '<input type="search" class="search-field" placeholder="' . esc_attr__('Search products…', 'woocommerce') . '" value="' . get_search_query() . '" name="s" />';
$form .= '<button type="submit" value="' . esc_attr__('Search', 'woocommerce') . '">' . esc_html__('Search', 'woocommerce') . '</button>';
$form .= '<input type="hidden" name="post_type" value="product" />';
$form .= '</form>';
return $form;
}
This will add a dropdown of product categories to the WooCommerce search form.
—
### **2. Modify the Search Query to Filter by Category**
Use the `pre_get_posts` hook to adjust the query based on the selected category:
add_action('pre_get_posts', 'custom_search_filter_by_category');
function custom_search_filter_by_category($query) {
// Check if it's the main search query and a product search
if (!is_admin() && $query->is_main_query() && $query->is_search() && isset($_GET['post_type']) && $_GET['post_type'] === 'product') {
if (!empty($_GET['product_cat'])) {
// Add taxonomy query for the selected category
$query->set('tax_query', [
[
'taxonomy' => 'product_cat',
'field' => 'slug',
'terms' => sanitize_text_field($_GET['product_cat']),
],
]);
}
}
}
This code ensures the search query filters products based on the selected category from the dropdown.
—
### **3. Style the Dropdown (Optional)**
Add custom CSS to style the dropdown and integrate it well with your theme:
.woocommerce-product-search select#product_cat {
margin-right: 10px;
padding: 5px;
font-size: 14px;
}
Place this CSS in your theme’s stylesheet or a custom CSS section.
—
### **4. Test the Functionality**
– Visit your site and look at the search bar.
– Select a category from the dropdown and enter a keyword to verify that the results are filtered accordingly.
This implementation customizes the WooCommerce search functionality to include a category filter, improving user experience and relevance of results.