How to display discount in percentage on shop page & loop page in woocommerce
By digimonster blog
Default WooCommerce shows a “Sale” badge if the item is on sale – however what concerning showing the precise sale proportion as well?
We enforced this for one in every of our shoppers thus here you come with the easy-peasy solution!!
Add this code into functions.php.,
add_action( 'woocommerce_before_shop_loop_item_title', 'new_show_sale_percentage_loop', 25 ); function new_show_sale_percentage_loop() { global $product; if ( $product->is_on_sale() ) { if ( ! $product->is_type( 'variable' ) ) { $max_percentage = round( ( ( $product->regular_price - $product->sale_price ) / $product->regular_price ) * 100 ); } else { foreach ( $product->get_children() as $child_id ) : $variation = $product->get_child( $child_id ); $price = $variation->get_regular_price(); $sale = $variation->get_sale_price(); $percentage = $price != 0 && ! empty( $sale ) ? ( ( $price - $sale ) / $price * 100 ) : $max_percentage; if ( $percentage >= $highest_percentage ) : $max_percentage = $percentage; $regular_price = $product->get_variation_regular_price( 'min' ); $sale_price = $product->get_variation_sale_price( 'min' ); endif; endforeach; } echo "<div class='sale-perc'>-" . round($max_percentage) . "%</div>"; } }
and also add this code bottom of the style.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; }

