Home » WooCommerce: Display % Discount @ Shop Page

WooCommerce: Display % Discount @ Shop Page

by Tutor Aspire

Default WooCommerce shows a “Sale” badge if the item is on sale – but what about showing the exact sale percentage instead?

I implemented this for one of my freelance clients so here you go with the easy-peasy solution. Enjoy!

Show discount percentage instead of the default “SALE!” on the WooCommerce product loop

PHP Snippet: Display Discount Percentage @ WooCommerce Shop / Category / Product Archive Pages

/**
 * @snippet       Display Discount Percentage @ Loop Pages - WooCommerce
 * @how-to        Get tutoraspire.com FREE
 * @author        Tutor Aspire
 * @compatible    WooCommerce 6
 * @donate $9     https://www.tutoraspire.com
 */ 

add_action( 'woocommerce_before_shop_loop_item_title', 'tutoraspire_show_sale_percentage_loop', 25 );

function tutoraspire_show_sale_percentage_loop() {
global $product;
if ( ! $product->is_on_sale() ) return;
if ( $product->is_type( 'simple' ) ) {
$max_percentage = ( ( $product->get_regular_price() - $product->get_sale_price() ) / $product->get_regular_price() ) * 100;
} elseif ( $product->is_type( 'variable' ) ) {
$max_percentage = 0;
foreach ( $product->get_children() as $child_id ) {
$variation = wc_get_product( $child_id );
$price = $variation->get_regular_price();
$sale = $variation->get_sale_price();
if ( $price != 0 && ! empty( $sale ) ) $percentage = ( $price - $sale ) / $price * 100;
if ( $percentage > $max_percentage ) {
$max_percentage = $percentage;
}
}
}
if ( $max_percentage > 0 ) echo "
-" . round( $max_percentage ) . "%
"; } [/php]

And a bit of CSS:

.sale-perc {
   background-color: #D9534F;
   display: inline;
   padding: .2em .6em .3em;
   font-size: 75%;
   font-weight: bold;
   color: #fff;
   text-align: center;
   border-radius: .25em;
}

“I don’t code – is there a reliable plugin for that?”

As many readers would love to code but don’t feel 100% confident with it, I decided to look for a reliable plugin that achieves the same (or even better) result.

In this case, I recommend the YITH WooCommerce Badge Management plugin. On top of displaying custom text badges (free version), you can also create CSS, image and advanced badges, assign product badges to specific products and/or categories, pick the badge position and much more.

But in case you wish to code, keep reading 🙂

You may also like