Athon
Athon

Reputation: 130

Show discount percentage in WooCommerce sale button

I'm looking for a way to show the percentage of discount in the sale bubble in WooCommerce. Here is an image how the button looks now:

enter image description here

So, basically, the button will show: -20%

Upvotes: 4

Views: 4874

Answers (1)

Frits
Frits

Reputation: 7614

You should be able to hook into the woocommerce_sale_flash filter, grab the product object, work out the percentage and add it to the HTML.

Something like this:

add_filter( 'woocommerce_sale_flash', 'add_percentage_to_sale_bubble' );
function add_percentage_to_sale_bubble( $html ) {
    global $product;
    $percentage = round( ( ( $product->regular_price - $product->sale_price ) / $product->regular_price ) * 100 );
    $output =' <span class="onsale">VERKOOP -'.$percentage.'%</span>';
    return $output;
}

Edit - Variable Products:

With variable products getting thrown into the mix, you will need to include a check using is_type('simple|variable') and adjust your calculations from there, like this:

add_filter( 'woocommerce_sale_flash', 'add_percentage_to_sale_bubble', 20 );
function add_percentage_to_sale_bubble( $html ) {
    global $product;

    if ($product->is_type('simple')) { //if simple product
        $percentage = round( ( ( $product->regular_price - $product->sale_price ) / $product->regular_price ) * 100 ).'%';
    } else { //if variable product
        $percentage = get_variable_sale_percentage( $product );
    }
    
    $output =' <span class="onsale">-'.$percentage.'</span>';
    return $output;
}

function get_variable_sale_percentage( $product ) {
    //get variables
    $variation_min_regular_price    = $product->get_variation_regular_price('min', true);
    $variation_max_regular_price    = $product->get_variation_regular_price('max', true);
    $variation_min_sale_price       = $product->get_variation_sale_price('min', true);
    $variation_max_sale_price       = $product->get_variation_sale_price('max', true);

    //get highest and lowest percentages
    $lower_percentage   = round( ( ( $variation_min_regular_price - $variation_min_sale_price ) / $variation_min_regular_price ) * 100 );
    $higher_percentage  = round( ( ( $variation_max_regular_price - $variation_max_sale_price ) / $variation_max_regular_price ) * 100 );
    
    //sort array
    $percentages = array($lower_percentage, $higher_percentage);
    sort($percentages);

    if ($percentages[0] != $percentages[1] && $percentages[0]) {
        return $percentages[0].'% - '.$percentages[1].'%';
    } else {
        return $percentages[1].'%';
    }
}

Upvotes: 7

Related Questions