When managing a WooCommerce store, your sales strategy can be a powerful way to engage customers and drive urgency.
One cool trick is featuring products with sale prices about to expire (“sale price end date“) in a custom product category. We’ve already seen how to populate a “Sale” category, but this time I’d like to get only the sale products with a sale end date!
Highlighting expiring sale items allows store owners to showcase time-sensitive deals, enticing shoppers to act fast before discounts disappear. This approach not only enhances the shopping experience but can also boost conversions during critical sales periods.
In this tutorial, we’ll explore how to dynamically populate a custom WooCommerce category with products whose sale end dates are approaching. Using a PHP code snippet, you’ll learn how to identify expiring sale items and assign them to a dedicated category automatically.
Whether you’re a store owner looking to create a “Last Chance” section or a developer helping clients achieve similar functionality, this guide will walk you through the steps. Let’s dive in!
PHP Snippet: Populate Custom WooCommerce Product Category With Sale End Date Products
Note: for this snippet to work, you must first create a product category with slug “last-chance” (or edit the snippet accordingly by entering the correct slug there).
/**
* @snippet WooCommerce Category With Sale End Date Products
* @how-to businessbloomer.com/woocommerce-customization
* @author Rodolfo Melogli, Business Bloomer
* @testedwith WooCommerce 9
* @community https://businessbloomer.com/club/
*/
add_action( 'woocommerce_product_query', 'bbloomer_populate_last_chance_category' );
function bbloomer_populate_last_chance_category( $q ) {
if ( "last-chance" !== $q->get( 'product_cat' ) ) return;
$q->set( 'post_type', 'product' );
$q->set( 'product_cat', null );
$product_ids_on_sale = bbloomer_get_on_sale_end_products() ? bbloomer_get_on_sale_end_products() : array( -1 );
$q->set( 'post__in', $product_ids_on_sale );
});
function bbloomer_get_on_sale_end_products() {
$product_ids_on_sale = wc_get_products( array(
'limit' => -1,
'date_on_sale_to' => '>' . time(),
'return' => 'ids',
'status' => 'publish',
));
return $product_ids_on_sale;
}