Example Code for Calculating Percentage Value in Sale Badge
If you have a wrong displaying of the percentage value of the sale badge, please, replace your code for hook “woocommerce_sale_flash” by this modified one:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 |
add_filter('woocommerce_sale_flash', 'adp_savings_on_sales_flash', 10, 3); function adp_savings_on_sales_flash($flash, $post, $product) { $percentage = ''; if ($product->get_type() == 'variable') { $processedProduct = adp_functions()->calculateProduct($product, 1); if ($processedProduct instanceof \ADP\BaseVersion\Includes\PriceDisplay\ProcessedVariableProduct && !is_null($processedProductLowestPrice = $processedProduct->getLowestPriceProduct()) && $processedProduct->areRulesApplied()) { $minVariationPrice = $processedProductLowestPrice->getCalculatedPrice(); $initialPrice = $processedProductLowestPrice->getOriginalPrice(); $percentage = round((($initialPrice - $minVariationPrice) / $initialPrice) * 100); } elseif ($product->is_on_sale()) { $available_variations = $product->get_variation_prices(); $max_percentage = 0; foreach ($available_variations['regular_price'] as $key => $regular_price) { $sale_price = $available_variations['sale_price'][$key]; if ($sale_price < $regular_price) { $percentage = round((($regular_price - $sale_price) / $regular_price) * 100); if ($percentage > $max_percentage) { $max_percentage = $percentage; } } } $percentage = $max_percentage; } } elseif ($product->get_type() == 'simple' || $product->get_type() == 'external' || $product->get_type() == 'variation') { $processedProduct = adp_functions()->calculateProduct($product, 1); if ($processedProduct instanceof \ADP\BaseVersion\Includes\PriceDisplay\ProcessedProductSimple && $processedProduct->areRulesApplied()) { $initialPrice = $processedProduct->getOriginalPrice(); $calculatedPrice = $processedProduct->getCalculatedPrice(); $percentage = round((($initialPrice - $calculatedPrice) / $initialPrice) * 100); } elseif ($product->is_on_sale()) { $percentage = round((($product->get_regular_price() - $product->get_sale_price()) / $product->get_regular_price()) * 100); } } return $percentage ? '<span class="onsale"> - ' . $percentage . '%</span>' : $flash; } |