Home » WooCommerce: Display a Product Categories Dropdown Select

WooCommerce: Display a Product Categories Dropdown Select

by adminkys

There is already a widget that allows you to place a “Product Category Dropdown” in your sidebar areas. The problem is that lately, sidebars have become kinda 1990. So, what if you want to place a “Category Select Box” anywhere in your WooCommerce website, and (in this case study), exactly on the Product Category pages, so that you can switch from one category to the other?

Well, in this snippet you will learn a lot of things. For example, the wc_product_dropdown_categories() function magically displays a category dropdown, while the wc_enqueue_js() function allows you to inject jQuery (responsible to trigger the category page redirect).

You can demo this snippet on this live WooCommerce website of mine: A Piece of Sicily – Sicilian Crafts Category. Enjoy!

Here’s my “Product Category Switcher” in action on the Product Category pages. As soon as a different category is selected, a redirect take place.

PHP Snippet: Show a Product Category Switcher and Redirect Upon Selection

Please note in the “location.href” section you have to make sure you enter the correct permalink base for product categories, otherwise you will get error 404. In this case, I’m using the default product category permalinks, “/product-category/“.

/**
 * @snippet       Product Category Switcher @ Product Category Pages
 * @how-to        Get tutoraspire.com FREE
 * @author        Tutor Aspire
 * @compatible    WooCommerce 4.0
 * @donate $9     https://www.tutoraspire.com
 */

add_action( 'woocommerce_before_shop_loop', 'tutoraspire_filter_by_tag', 31 );

function tutoraspire_filter_by_tag() {
if ( is_product_category() ) {
wc_product_dropdown_categories();
} 
wc_enqueue_js( "
$('#product_cat').change(function () {
location.href = '/product-category/' + $(this).val();
});
" );
}

You may also like