Here’s how to show a “you save X% in” in the WooCommerce shop loop when using Bricks Builder.
VIDEO: The Video Tutorial
Here is my YouTube video that shows you how to set this up.
The PHP code
And here is the code that we go through in the video.
<?php
// adapted from the original source found at this url
// https://www.businessbloomer.com/woocommerce-display-discount-shop-loop-pages/
add_shortcode( 'product_savings_percent', 'wpirate_show_sale_percentage_loop' );
function wpirate_show_sale_percentage_loop() {
if( !bricks_is_builder() ){
global $product;
if ( ! $product->is_on_sale() ) return;
if ( $product->is_type( 'simple' ) ) {
$savings_text = 'You Save: ';
$max_percentage = ( ( $product->get_regular_price() - $product->get_sale_price() ) / $product->get_regular_price() ) * 100;
} elseif ( $product->is_type( 'variable' ) ) {
$savings_text = 'Save up to: ';
$prices = $product->get_variation_prices( true ); // this is the fastest way to get the prices for all variants - returns multidimensional array from object cache
foreach($prices['regular_price'] as $pid => $regular_price) {
if ($regular_price == 0) continue; // if regular price is 0, skip this product
if ($regular_price == $prices['sale_price'][$pid]) continue; // if sale price = regular price, skip this product
$percentage = ( $regular_price - $prices['sale_price'][$pid] ) / $regular_price * 100;
if ( $percentage > $max_percentage ) {
$max_percentage = $percentage;
}
}
}
else{
return 'On Sale!';
}
if ( $max_percentage > 0 ) {
return $savings_text . round( $max_percentage ) . '%';
}
}
}
Code language: PHP (php)
Leave a Reply