In this article, I will show you how you can customize and show discount percentage on the product pricing like the other eCommerce sites like Amazon, Flipkart, Shopify etc. Woocommerce is extremely friendly for developers because it has a ton of actions and filters.
WooCommerce pricing display is an important area of the product page. Where customers check out the prices and carry out the price and compare them to sites. By default Woocommerce showing only product price, sale price without showing discounted price/ percentage price.
For doing that, we need a Woocommerce filter that converts the default price to a discounted price with a percentage. The customer can easily know what percentage of discount they get. So you just need to copy the below function and paste it into the themes functions.php
add_filter( 'woocommerce_get_price_html', 'qlc_price_calculation', 100, 2 );
function qlc_price_calculation( $price, $product ) {
$return_string = '<span style="color: #555;">M.R.P:</span> ' . $price;
return $return_string;
}
The above function gets the MRP Price that shows first after that we need to get the sale price. And then need to calculate the actual percentage of the discounted amount. The below function perform that calculation and show discount percentage to a page or other locations where the price displays.
add_filter( 'woocommerce_get_price_html', 'qlc_sale_price_html', 100, 2 );
function qlc_sale_price_html( $price, $product ) {
if ( $product->is_on_sale() ) :
$return_string = str_replace( '<ins>', '<ins><br><span style="color: #555;">Sale:</span> ', $price);
return $return_string;
else :
return $price;
endif;
}
// Add save percent next to sale item prices.
add_filter( 'woocommerce_get_price_html', 'woocommerce_customsave_sales_price', 10, 2 );
function woocommerce_customsave_sales_price( $price, $product ) {
if ( $product->is_on_sale() && $product->is_type( 'simple' ) ) :
$saveprice = ( $product->regular_price - $product->sale_price );
return $price . sprintf( __(' <br><span style="color: #555;">You Save</span> ₹%s', 'woocommerce' ), $saveprice );
else :
return $price;
endif;
}
// Add save percent next to sale item prices.
add_filter( 'woocommerce_get_price_html', 'woocommerce_custom_sales_price', 10, 2 );
function woocommerce_custom_sales_price( $price, $product ) {
if ( $product->is_on_sale() && $product->is_type( 'simple' ) ) :
$percentage = round( ( ( $product->regular_price - $product->sale_price ) / $product->regular_price ) * 100 );
return $price . sprintf( __(' (%s', 'woocommerce' ), $percentage . '%) <br><span style="color: #111;">Inclusive of all taxes</span>' );
else :
return $price;
endif;
}
You may also refer woocommerce documentation https://docs.woocommerce.com/document/introduction-to-hooks-actions-and-filters/ & also like https://quicklearncode.com/display-product-variations-in-shop-catalogue-page/
If you like this article so please share and if you have any query so please comment below.