Show percentage discount simple and variable product

I use this code to show percentage discount in simple and variable products in WooCommerce.

<?php
/**
 * Single Product Sale Flash
 *
 * @version     1.6.4
 */

if ( ! defined( 'ABSPATH' ) ) {
exit;
}

global $post, $product, $porto_settings;

$labels = '';
if ($porto_settings['product-hot']) {
$featured = get_post_meta($post->ID, '_featured', 'true') == 'yes' ? true : 
false;
if ($featured) {
    $labels .= '<div class="onhot">'. ((isset($porto_settings['product-hot-
label']) && $porto_settings['product-hot-label']) ? 
$porto_settings['product-hot-label'] : __('Hot', 'porto')) .'</div>';
}
}

if ( $porto_settings['product-sale'] && $product->is_on_sale() ) {
$percentage = 0;
if ($product->regular_price && $product->product_type == 'simple')

    $percentage = - round( ( ( $product->regular_price - $product->sale_price ) / $product->regular_price ) * 100 );
if ($porto_settings['product-sale-percent'] && $percentage)

    $labels .= '<div class="onsale">'. $percentage .'%</div>';

 if ($product->is_on_sale() && $product->product_type == 'variable') 
    $available_variations = $product->get_available_variations();                               
        $maximumper = 0;
        for ($i = 0; $i < count($available_variations); ++$i) {
            $variation_id=$available_variations[$i]['variation_id'];
            $variable_product1= new WC_Product_Variation( $variation_id );
            $regular_price = $variable_product1->regular_price;
            $sales_price = $variable_product1->sale_price;
            $percentage= round((( ( $regular_price - $sales_price ) / $regular_price ) * 100),1) ;
                if ($percentage > $maximumper) {
                    $maximumper = $percentage;
                }
            }


    $labels .= apply_filters( 'woocommerce_sale_flash', '<span 
class="onsale">' . ((isset($porto_settings['product-sale-label']) && 
$porto_settings['product-sale-label']) ? $porto_settings['product-sale-
label'] : __('Sale', 'porto')) . '&nbsp;' . $maximumper . '%' . '</span>', 
$post, $product );
}

echo '<div class="labels">';

echo $labels;

echo '</div>';
?>

with variable products works, but not for simple because don’t entry in if ($product->regular_price && $product->product_type == ‘simple’) … you can help me ?

thanks

Read more here: Show percentage discount simple and variable product

Leave a Reply

Your email address will not be published. Required fields are marked *