In my own WooCommerce shop, for Black Friday, I wanted to send customers directly to the Shop page showcasing only items on sale. To my surprise, WooCommerce doesn’t provide a built-in way to sort products by “on sale” out of the box.
This led me to explore a solution that not only solved the problem but also added a new sorting option to the WooCommerce Shop page dropdown.
Now, with a simple code snippet, you can enable a “Sort by On Sale” feature, or even use the “orderby=on_sale” parameter with your Shop page URL to show sale items effortlessly!
PHP Snippet: Add “Sort by on sale” Option @ WooCommerce Shop Page
Here’s a PHP snippet to add a custom “Sort by on sale” sorting option to WooCommerce. This snippet ensures that only products on sale appear in the product catalog when this sorting option is selected. Also, you can use the orderby=on_sale URL parameter to send customers directly to the filtered view!
/**
* @snippet Show only on sale products @ WooCommerce Shop
* @how-to businessbloomer.com/woocommerce-customization
* @author Rodolfo Melogli, Business Bloomer
* @compatible WooCommerce 9
* @community https://businessbloomer.com/club/
*/
add_filter( 'woocommerce_get_catalog_ordering_args', 'bbloomer_sort_by_on_sale' );
function bbloomer_sort_by_on_sale( $args ) {
if ( isset( $_GET['orderby'] ) && 'on_sale' === $_GET['orderby'] ) {
$args['meta_key'] = '_sale_price';
$args['orderby'] = 'meta_value_num';
$args['order'] = 'ASC';
}
return $args;
}
add_filter( 'woocommerce_catalog_orderby', 'bbloomer_sort_by_on_sale_dropdown' );
function bbloomer_sort_by_on_sale_dropdown( $options ) {
$options['on_sale'] = __( 'Sort by on sale', 'bbloomer' );
return $options;
}
How it works
- Filtering Catalog Arguments: The
woocommerce_get_catalog_ordering_args
filter modifies the query to sort by_sale_price
when the “Sort by on sale” option is selected. - Adding a New Sorting Option: The
woocommerce_catalog_orderby
filters add a new sorting option labeled “Sort by on sale” to the WooCommerce Shop page sorting dropdown.
URL parameter
When the filter is active, you will see that WooCommerce redirects you to https://example.com/shop/?orderby=on_sale
Which means, you can use that URL with the parameter to send customers to the filtered “On sale” view without having to create a custom page!