1
votes

My code below creates a shortcode that will print the sale percentage of variable and simple products if its on sale.

My problem with this code is that with simple products only, the sale percentage is showing as 100% OFF when the product is not on sale. I.e. no sale price entered

If I set a sale price, so setting the product to be on sale, the percentage shown is correct.

The problem is isolated to simple products that are not on sale. The sale percentage should not be being displayed at all.

add_shortcode( 'sale-percentage', 'add_percentage_to_sale_badge' );
function add_percentage_to_sale_badge() {
   global $product;
   if ( $product->is_type( 'variable' ) ) {
      $percentages = array(); // Get all variation prices
      $prices = $product->get_variation_prices(); // Loop through variation prices
      foreach ( $prices['price'] as $key => $price ) { // Only on sale variations
         if ( $prices['regular_price'][ $key ] !== $price ) {
            // Calculate and set in the array the percentage for each variation on sale
            $percentages[] = round( 100 - ( $prices['sale_price'][ $key ] / $prices['regular_price'][ $key ] * 100 ) );
         }
      }
      $percentage = $percentages ? max( $percentages ) . '% Off' : '';
   } else {
      $regular_price = (float) $product->get_regular_price();
      $sale_price = (float) $product->get_sale_price();
      $percentage = round( 100 - ( $sale_price / $regular_price * 100 ) ) . '% Off SIMPLE';
   }

   $percentage = $percentage ? esc_html__( '', 'woocommerce' ) . ' ' . $percentage : '';

   return $percentage;
}
1

1 Answers

1
votes

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 =...
}