Display the discounted price and percentage on Woocommerce products

Asked
Active3 hr before
Viewed126 times

7 Answers

productsdisplay
90%

I want the sales badge to show the discount rate of a product which price is below the base price for example:,Hi @rynald0s How would I do the same thing for Woocommerce blocks ? I have homepage built with gutenburg and woocommerce blocks but sale percent never shows only works on Product Page and Category Pages also not shown on main Shop page loop ??,Instead of saying ” save 12 dollars” make it say “40% off” and let the site itself calculate the discount rate by itself every time the price of a product is changed,This works for simple products but gives me two errors for variable products. In the sale flash on the archive I get NAN% with error “A non-numeric value encountered”.

You can use something like this:

add_filter( 'woocommerce_sale_flash', 'add_percentage_to_sale_badge', 20, 3 );
function add_percentage_to_sale_badge( $html, $post, $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 = max($percentages) . '%';
    } else {
        $regular_price = (float) $product->get_regular_price();
        $sale_price    = (float) $product->get_sale_price();

        $percentage    = round(100 - ($sale_price / $regular_price * 100)) . '%';
    }
    return '<span class="onsale">' . esc_html__( 'SALE', 'woocommerce' ) . ' ' . $percentage . '</span>';
}
88%

How to Display the Discount Percentage on the Sale Badge (single products only)?,Video: How to Add the Discount Percentage on the Woocommerce Sale Badge?,How to Display the Discount Percentage on the Sale Badge for variable products, single products and grouped products?,Therefore, in this post I am going to show you how to display the discount percentage on the Woocommerce sale badge.

add_action( 'woocommerce_sale_flash', 'sale_badge_percentage', 25 );
 
function sale_badge_percentage() {
   global $product;
   if ( ! $product->is_on_sale() ) return;
   if ( $product->is_type( 'simple' ) ) {
      $max_percentage = ( ( $product->get_regular_price() - $product->get_sale_price() ) / $product->get_regular_price() ) * 100;
   } elseif ( $product->is_type( 'variable' ) ) {
      $max_percentage = 0;
      foreach ( $product->get_children() as $child_id ) {
         $variation = wc_get_product( $child_id );
         $price = $variation->get_regular_price();
         $sale = $variation->get_sale_price();
         if ( $price != 0 && ! empty( $sale ) ) $percentage = ( $price - $sale ) / $price * 100;
         if ( $percentage > $max_percentage ) {
            $max_percentage = $percentage;
         }
      }
   }
   if ( $max_percentage > 0 ) echo "<span class='onsale'>-" . round($max_percentage) . "%</span>"; // If you would like to show -40% off then add text after % sign
}
load more v
72%

The original solution: Display the discounted price and percentage on Woocommerce products,For selected product variations on sale price, you can also use the following to get the saving percentage:,PixelCrayons: Being a top software product development company, we are known for providing robust, secure, feature-packed, and scalable Software product engineering solutions as per the specific needs of businesses.,Are you looking for the best plugins for the eCommerce portal to skyrocket the sales on your store? Then this is the ideal place for you to know the WooCommerce plugin features and use.

2) The saving percentage:

add_filter('woocommerce_get_price_html', 'change_displayed_sale_price_html', 10, 2);

function change_displayed_sale_price_html($price, $product) {
   // Only on sale products on frontend and excluding min/max price on variable products
   if ($product - > is_on_sale() && !is_admin() && !$product - > is_type('variable')) {
      // Get product prices
      $regular_price = (float) $product - > get_regular_price(); // Regular price
      $sale_price = (float) $product - > get_price(); // Active price (the "Sale price" when on-sale)
      // "Saving Percentage" calculation and formatting
      $precision = 1; // Max number of decimals
      $saving_percentage = round(100 - ($sale_price / $regular_price * 100), 1).
      '%';

      // Append to the formated html price
      $price. = sprintf(__('&lt;p class="saved-sale"&gt;Save: %s&lt;/p&gt;', 'woocommerce'), $saving_percentage);
   }
   return $price;

}
     // "Saving Percentage" calculation and formatting
     $precision = 1; // Max number of decimals
     $saving_percentage = round(100 - ($sale_price / $regular_price * 100), 1).
     '%';

     // Append to the formated html price
     $price. = sprintf(__('&lt;p class="saved-sale"&gt;Save: %s&lt;/p&gt;', 'woocommerce'), $saving_percentage);
     }
     return $price;
load more v
65%

Displaying the percentage of amount saved is easy for simple products once the regular and the sale price is known. In normal cases, these prices for a simple product are displayed as follows:,The saved amount as well as the percentage will now be displayed below the price:,If you wish, you can display the You Save text along with the percentage saved below the product title instead of above the “Add to Cart” button by adding some more code snippets to the ones mentioned above.,Thus, you will now see “You Save”, along with the percentage of amount saved, below the price of the variation.

Adding the code below to the functions.php file of your child theme will display the “You Save x%” below the price of the simple product, so that the user immediately gets an idea of how good or bad the deal is.

function ts_you_save() {
  
  global $product;
  
   if( $product->is_type('simple') || $product->is_type('external') || $product->is_type('grouped') ) {
      
     	$regular_price 	= get_post_meta( $product->get_id(), '_regular_price', true ); 
        $sale_price 	= get_post_meta( $product->get_id(), '_sale_price', true );
     
     	if( !empty($sale_price) ) {
  
              $amount_saved = $regular_price - $sale_price;
              $currency_symbol = get_woocommerce_currency_symbol();

              $percentage = round( ( ( $regular_price - $sale_price ) / $regular_price ) * 100 );
              ?>
              <p style="font-size:24px;color:red;"><b>You Save: <?php echo number_format($percentage,0, '', '').'%'; ?></b></p>				
              <?php		
        }
   }
}

add_action( 'woocommerce_single_product_summary', 'ts_you_save', 11 );
load more v
75%

3 Both of them (the discounted price and percentage):,On the image below, it shows the discounted price and percentage ,How can I display the correct formatted discounted price? How can I display also the discounted percentage?, Meta Stack Overflow

1) The saving price:

add_filter( 'woocommerce_get_price_html', 'change_displayed_sale_price_html', 10, 2 );
function change_displayed_sale_price_html( $price, $product ) {
    // Only on sale products on frontend and excluding min/max price on variable products
    if( $product->is_on_sale() && ! is_admin() && ! $product->is_type('variable')){
        // Get product prices
        $regular_price = (float) $product->get_regular_price(); // Regular price
        $sale_price = (float) $product->get_price(); // Active price (the "Sale price" when on-sale)

        // "Saving price" calculation and formatting
        $saving_price = wc_price( $regular_price - $sale_price );

        // Append to the formated html price
        $price .= sprintf( __('<p class="saved-sale">Save: %s</p>', 'woocommerce' ), $saving_price );
    }
    return $price;
}
load more v
40%

WooCommerce: Set / Override Product Price Programmatically ,WooCommerce: Disable Variable Product Price Range $$$-$$$ ,WooCommerce: Always Show Single Variation Price @ Single Product ,WooCommerce: Display Stock Status/Quantity @ Shop Page

WooCommerce Snippet: Display Discount Percentage @ Loop Pages – WooCommerce

/**
 * @snippet       Display Discount Percentage @ Loop Pages - WooCommerce
 * @how-to        Get CustomizeWoo.com FREE
 * @sourcecode    https://businessbloomer.com/?p=21997
 * @author        Rodolfo Melogli
 * @compatible    WooCommerce 3.5.4
 * @donate $9     https://businessbloomer.com/bloomer-armada/
 */ 

add_action( 'woocommerce_before_shop_loop_item_title', 'bbloomer_show_sale_percentage_loop', 25 );
 
function bbloomer_show_sale_percentage_loop() {
	global $product;
	if ( ! $product->is_on_sale() ) return;
	if ( $product->is_type( 'simple' ) ) {
		$max_percentage = ( ( $product->get_regular_price() - $product->get_sale_price() ) / $product->get_regular_price() ) * 100;
	} elseif ( $product->is_type( 'variable' ) ) {
		$max_percentage = 0;
		foreach ( $product->get_children() as $child_id ) {
			$variation = wc_get_product( $child_id );
			$price = $variation->get_regular_price();
			$sale = $variation->get_sale_price();
			if ( $price != 0 && ! empty( $sale ) ) $percentage = ( $price - $sale ) / $price * 100;
			if ( $percentage > $max_percentage ) {
				$max_percentage = $percentage;
			}
		}
	}
	if ( $max_percentage > 0 ) echo "<div class='sale-perc'>-" . round($max_percentage) . "%</div>"; 
}

And a bit of CSS:

.sale - perc {
   background - color: #D9534F;
   display: inline;
   padding: .2 em .6 em .3 em;
   font - size: 75 % ;
   font - weight: bold;
   color: #fff;
   text - align: center;
   border - radius: .25 em;
}
load more v
22%

With the sale prices added, the products on the front end will display as such:, Change the WooCommerce Sale Badge to Display a Percentage Discount ,Sales are great marketing strategies. By offering an often time-sensitive discount, sales encourage customers to make rapid purchase decisions. If you’re running a WooCommerce store, you’ll know that the WooCommerce sale badge is easy to set up. All you need to do is enter a sale price in the product setting, and a badge stating ‘Sale!’ will automatically display.,Anna Kurowska on Change the WooCommerce Sale Badge to Display a Percentage Discount

PHP

/* Replace text of Sale! badge with percentage */

  add_filter( 'woocommerce_sale_flash', 'ds_replace_sale_text' );
 
function ds_replace_sale_text($text) {
 global $product; 
 $stock = $product->get_stock_status();
 $product_type = $product->get_type();
 $sale_price  = 0;
 $regular_price = 0;
 if($product_type == 'variable'){
  $product_variations = $product->get_available_variations();
  foreach ($product_variations as $kay => $value){
   if($value['display_price'] < $value['display_regular_price']){
    $sale_price = $value['display_price'];
    $regular_price = $value['display_regular_price'];
   }
  }
  if($regular_price > $sale_price && $stock != 'outofstock') {
   $product_sale = intval(((intval($regular_price) - floatval($sale_price)) / floatval($regular_price)) * 100);
   if ($product_sale > 5 ) {
   return '<span class="onsale"> <span class="sale-icon" aria-hidden="true" data-icon="&#xe0da"></span> ' . esc_html($product_sale) . '% OFF</span>';
   }
   if ($product_sale <= 5 ) {
       return '<span class="onsale"> <span class="sale-icon" aria-hidden="true" data-icon="&#xe0da"></span>Sale!</span>';
   }
  }else{
   return  '';
  }
 }else{
  $regular_price = get_post_meta( get_the_ID(), '_regular_price', true);
  $sale_price = get_post_meta( get_the_ID(), '_sale_price', true);
  if($regular_price > 5) {
   $product_sale = intval(((floatval($regular_price) - floatval($sale_price)) / floatval($regular_price)) * 100);
   return '<span class="onsale"> <span class="sale-icon" aria-hidden="true" data-icon="&#xe0da"></span> ' . esc_html($product_sale) . '% OFF</span>';
  }
  if($regular_price >= 0 && $regular_price <= 5 ) {
   $product_sale = intval(((floatval($regular_price) - floatval($sale_price)) / floatval($regular_price)) * 100);
   return '<span class="onsale"> <span class="sale-icon" aria-hidden="true" data-icon="&#xe0da"></span>Sale!</span>';
  }

  else{
   return '';
  }
 }
}
load more v

Other "products-display" queries related to "Display the discounted price and percentage on Woocommerce products"