Black Friday & Cyber Monday SUPER SALE ALL WEEK:
Grab 40% OFF on plugins
Days
Hours
Minutes
Seconds

How to Display Before and After Prices for Products on Sale in WooCommerce

It’s a good practice to offer discounts on your web store from time to time, as they are a great way to boost sales, and though, by default, WooCommerce displays the new price after slashing the old price for on-sale products (refer to the image below), a lot of stores instead write “Before” and “After” before displaying prices. This is often done to highlight the price difference and emphasise on the fact that there is a good deal on the product. In this post, we’ll explore how to display Before and After prices for products on sale in WooCommerce using hook.

display Before and After prices for products on sale in WooCommerce - Default display of the price of a simple product on sale
Default style of displaying the price for a product on sale in WooCommerce.

Just by using a simple code snippet, you can display the price in the format “Before: ” and “After: ” instead of slashing the prices. Paste the below code snippet in the functions.php file of your child theme to see how:

add_filter( 'woocommerce_get_price_html', 'ts_custom_price', 10, 2 );
function ts_custom_price() {
    global $product;
  
  if ($product->is_on_sale())
  {
  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) ) {
      print '<p class="custom_text"><b>Before:</b> ₹'.$regular_price.'</p><p class="custom_text"><b>After:</b> ₹'.$sale_price.'</p>';
    }
  }  
} 

}

The woocommerce_get_price_html filter helps to change the way the price is displayed on the product page in WooCommerce stores. We have added a function to this filter which checks to see if the product is on sale and if so, then it changes the way the price gets displayed:

display Before and After prices for products on sale in WooCommerce - Before and After prices displayed for a simple product on sale

You can always add some custom CSS to the class “custom_text” (mentioned in the code snippet) to apply styles to the changed text:

display Before and After prices for products on sale in WooCommerce - adding CSS styles to Before and After prices

Displaying Before and After prices for variable products on sale in WooCommerce

While the above code snippet works for simple products (i.e. with no variations), the code snippet for variable products is different due to there being different prices for different variations such as size or colour. For example, the price of a t-shirt of Size S (Small) would be less than that of a t-shirt of Size XL (Extra Large).

For variable products, you would need to add code snippets to both the functions.php and the footer.php files of  your child theme.

The code snippet that you will add in the footer.php file contains a function that is triggered when the variation is changed. In our case, this is triggered when the size variation is selected or changed using the Size dropdown. This function captures the particular variation id and sends it to functions.php via an ajax call.

<script>
jQuery(document).ready(function($) {
             
  $('input.variation_id').change( function(){
    	
    if( '' != $('input.variation_id').val() ) {
                     
        	var var_id = $('input.variation_id').val(); // Your selected variation id
      $.ajax({

// replace <your_woocommerce_site_url> with your woocommerce site url
        url: "https://<your_woocommerce_site_url>/wp-admin/admin-ajax.php", 
        		data: {'action':'ts_before_after_variable','vari_id': var_id} ,
        		success:function(data) {
                                console.log(data);
                                $( ".woocommerce-variation-price" ).append(data);					
        		},
        		error: function(errorThrown){
           			console.log(errorThrown);
        		}
    		});                       
          }
   });

});
</script>

You need to replace <your_woocommerce_site_url> with the base URL of your WooCommerce website.

The following code snippet that you will add in the functions.php file contains a function ts_before_after_variable that fetches the regular price & sale price of the product based on the variation id, prints the same along with the texts “Before” and “After” and returns this output to the ajax function in the footer.php file.

//This is how you hook a function called by ajax, in WordPress
add_action("wp_ajax_ts_before_after_variable", "ts_before_after_variable");

//The function below is called via an ajax script in footer.php
function ts_before_after_variable(){

       The $_REQUEST contains all the data sent via ajax
       if ( isset($_REQUEST) ) {
                        $variation_id = sanitize_text_field($_REQUEST['vari_id']);
                        $variable_product = wc_get_product($variation_id);
                        $regular_price = $variable_product->get_regular_price();
                        $sale_price = $variable_product->get_sale_price();
     
                        if( !empty($sale_price) ) {
  
                             $datastr='<p class="custom_text"><b>Before:</b> ₹'.$regular_price.'</p><p class="custom_text"><b>After:</b> ₹'.$sale_price.'</p>';
      
                             // Display the output 
                             echo $datastr; 
                        }
        }
}

The sanitize_text_field() function is a WordPress function that helps to sanitize the input we receive from the client side.

Now, when you change the size variation in the dropdown, you will see the “Before” and “After” prices accordingly:

display Before and After prices for products on sale in WooCommerce - Display Before and After prices for a variable product on sale upon changing the size variation

In order to display the percentage of amount saved, please refer to the post How to display “You Save x%” below sale prices for simple and variable products in WooCommerce.

Browse more in: Code Snippets, WooCommerce How Tos, WooCommerce Tutorials

Share It:

Subscribe
Notify of
2 Comments
Newest
Oldest
Inline Feedbacks
View all comments
José Carlos Amaral
2 years ago

This code is good in 2022?

alex
2 years ago

usando elementor não esta funcionando? 🙁

2
0
Would love your thoughts, please comment.x
()
x