How to add WooCommerce product filter by category beside Shop default sorting

To add a WooCommerce product filter by category beside the shop default sorting, you can use a combination of hooks and filters in WordPress. Here’s a step-by-step guide to help you achieve this:

Step 1: Add the below code into your theme function.php file

Add the following code to register a custom filter dropdown in your shop:

function custom_product_filter() {
    // Get all product categories
    $categories = get_terms('product_cat');


    // Output the filter HTML
    if (!empty($categories)) {
        echo '<form method="get" action="' . esc_url(home_url('/')) . '">';
        echo '<select name="product_cat" id="product_cat_filter">';
        echo '<option value="">All Categories</option>';


        foreach ($categories as $category) {
            echo '<option value="' . $category->slug . '">' . $category->name . '</option>';
        }


        echo '</select>';
        echo '<input type="hidden" name="post_type" value="product" />';
        echo '<input type="hidden" name="paged" value="1" />';
        echo '<input type="submit" value="Filter" />';
        echo '</form>';
    }
}
add_action('woocommerce_before_shop_loop', 'custom_product_filter', 20);

This code adds a select dropdown with all the product categories and a “Filter” button.

Step 2: Add the following code in function.php file to filter the products based on the selected category:

function custom_product_category_filter($query) {
    $product_cat = isset($_GET['product_cat']) ? sanitize_text_field($_GET['product_cat']) : '';

    if ($product_cat && is_shop()) {
        $tax_query = array(
            array(
                'taxonomy' => 'product_cat',
                'field' => 'slug',
                'terms' => $product_cat,
            ),
        );
        $query->set('tax_query', $tax_query);
    }
}
add_action('woocommerce_product_query', 'custom_product_category_filter');

This code modifies the WooCommerce product query to include the selected product category when the filter is applied.

After implementing these changes, you should see a product category dropdown and a “Filter” button on your WooCommerce shop page. Selecting a category and clicking the “Filter” button will filter the products accordingly.

That’s it! Thank you


Posted

in

,

by

Tags:

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *