Home » WooCommerce: “Sale” Category (Automatic)

WooCommerce: “Sale” Category (Automatic)

by Tutor Aspire

You can use a shortcode or block in order to display the WooCommerce products on sale. However, what if you wanted a proper “product category” called “Sale” – and where you didn’t need to manually assign this category to each product?

Basically, how do we display all the discounted products in a custom category called “Sale”, without doing any manual work?

Here’s a super quick tutorial. Enjoy!

My “Sale” product category contains 16 products. With the snippet below I didn’t have to go into each product and tick this category by hand… it’s just all automatic!

Step 1: Add New Product Category

A one-off manual step is required, actually.

Simply go to WP Dashboard > Products > Categories > Add new category and enter the category name e.g. “Sale” and its slug e.g. “sale”.

The slug is very important as it’s used in the snippet below, so if you decide to rename it, you must change the PHP accordingly.

Step 2: PHP Snippet To Programmatically Populate the “Sale” Product Category With Products On Sale

/**
 * @snippet       Automatically Populate Sale Product Cat
 * @how-to        Get tutoraspire.com FREE
 * @author        Tutor Aspire
 * @compatible    WooCommerce 6
 * @donate $9     https://tutoraspire.com
 */

add_action( 'woocommerce_product_query', 'tutoraspire_sale_category' );

function tutoraspire_sale_category( $q ) {
   if ( "sale" !== $q->get( 'product_cat' ) ) return; // "sale" = slug
$q->set( 'post_type', 'product' );
$q->set( 'product_cat', null );
$product_ids_on_sale = wc_get_product_ids_on_sale() ? wc_get_product_ids_on_sale() : array();
$q->set( 'post__in', $product_ids_on_sale );
}

You may also like