Create product category and keyword search form in woocommerce? [closed]

I just made it for a client, you’ll have to do it on the pre_get_posts action. That means you will add parameters to the WordPress query before it returns the posts.

Add this to functions.php:

// advanced search functionality
function advanced_search_query($query) {

    if($query->is_search()) {
        // category terms search.
        if (isset($_GET['category']) && !empty($_GET['category'])) {
            $query->set('tax_query', array(array(
                'taxonomy' => '***the_taxonomy_slug_of_your_category***',
                'field' => 'slug',
                'terms' => array($_GET['category']) )
            ));
        }    
    }
    return $query;
}
add_action('pre_get_posts', 'advanced_search_query', 1000);

The code above works assuming you passed a category variable. You can do it by creating a select tag with ‘category’ as name :

<select name="category">
    <option value="***cat_slug***">Cat. name</option>
    <option value="***cat_slug***">Cat. name</option>
    <option value="***cat_slug***">Cat. name</option>
</select>

The complete form:

<form role="search" method="get" action="<?php echo esc_url( home_url( "https://wordpress.stackexchange.com/" ) ); ?>">
    <!-- With this hidden input you can define a specific post type. -->
    <input type="hidden" name="post_type" value="your_post_type" />
    <input name="s" type="text" />
    <select name="category">
        <!-- Insert here all option tags you want, with category slug as value -->
    </select>
    <button type="submit">Submit</button>
</form>

Once submitted, $_GET[] will contain s, post_type and category. s and post_type are used by default WP search, and category will be using in pre_get_posts() to add parameters to WP query.

So finally WP query will consider:

  • s : your keywords.
  • post_type : avoids mixing results if several post types have a same taxonomy.
  • category : the taxonomy you’re searching on.

For WooCommerce

Replace the action attribute of your <form> tag by:

<?php echo get_permalink( wc_get_page_id( 'shop' ) ); ?>

You may also leave it empty if you’re sure your form is only on the shop page.

Set the value of the hidden field to product, the custom post type slug for WC products.

Leave a Comment