Add sale percentage to products on sale with a shortcode in WooCommerce

You actually already have the answer yourself in your question:

  • “when the product is not on sale. I.e. no sale price entered..”

If this is not filled in, no calculations can be made with that number, Therefore you must add an if condition before you calculate the percentage.

So change

$regular_price = (float) $product->get_regular_price();
$sale_price = (float) $product->get_sale_price();
$percentage = round( 100 - ( $sale_price / $regular_price * 100 ) ) . '% Off SIMPLE';

To

// Get regular price
$regular_price = (float) $product->get_regular_price();

// Get sale price
$sale_price = (float) $product->get_sale_price();

// Condition, isset 
if ( isset ( $regular_price ) && isset ( $sale_price ) ) {
    $percentage = round( 100 - ( $sale_price / $regular_price * 100 ) ) . '% Off SIMPLE';   
}
  • isset — Determine if a variable is declared and is different than NULL

Could also be used, or a combination of both

  • empty — Determine whether a variable is empty

Like

// NOT empty
if ( ! empty ( $sale_price ) ) {
    // $percentage =...
}

CLICK HERE to find out more related problems solutions.

Leave a Comment

Your email address will not be published.

Scroll to Top