Reputation: 333
I'd like to display the percentage variable products are discounted in the archive pages. With the code below, I was able to get both the discounts % on variable products but also for simple products. Can I do this ONLY for variable products and not simple products? I realize it's probably a simple adjustment in the code but I can't figure it out because I'm an idiot when it comes to PHP.
add_action( 'woocommerce_after_shop_loop_item', 'show_sale_percentage', 25 );
function show_sale_percentage() {
global $product;
if ( $product->is_on_sale() ) {
if ( ! $product->is_type( 'variable' ) ) {
$max_percentage = ( ( $product->get_regular_price() - $product->get_sale_price() ) / $product->get_regular_price() ) * 100;
} else {
$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;
}
}
}
echo "<div class='saved-sale'>-" . round($max_percentage) . "%</div>";
}
}
Upvotes: 1
Views: 901
Reputation: 253784
To display the on sale percentage, on archives pages, for variable products only, try the following:
add_action( 'woocommerce_after_shop_loop_item', 'loop_variable_product_sale_percentage', 25 );
function loop_variable_product_sale_percentage() {
global $product;
if ( $product->is_on_sale() && $product->is_type( 'variable' ) ) {
$max_percentage = 0;
foreach ( $product->get_children() as $child_id ) {
$variation = wc_get_product( $child_id );
$percentage = 0;
$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;
}
}
echo '<div class="saved-sale">-' . round($max_percentage) . '%</div>';
}
}
Code goes in function.php file of your active child theme (or active theme). Tested and works.
Upvotes: 1