skip to Main Content

I’m using the following code to add text before the price if the product is on sale on the archive pages in WooCommerce:

function wps_custom_message() {
 
    $product = wc_get_product();
    if ( $product->is_on_sale() ) {
        add_filter( 'woocommerce_get_price_html', 'cw_change_product_price_display' );
        add_filter( 'woocommerce_cart_item_price', 'cw_change_product_price_display' );
        function cw_change_product_price_display( $price ) {
            // Your additional text in a translatable string
            $text = __('<span>Your sale price is:</span><br>');

            // returning the text before the price
            return $text . ' ' . $price;
        }
    }
}
 
add_action( 'woocommerce_archive_description', 'wps_custom_message', 9 );
add_action( 'woocommerce_before_single_product', 'wps_custom_message', 9 );

But the text appears also on products where sale price is not set.
What I’m doing wrong?

enter image description here

As you can see on the screenshot, the text shouldn’t be on the products that haven’t got sale price.

2

Answers


  1. To prepend a text to products on sale price, replace your code simply with the following:

    add_filter( 'woocommerce_get_price_html', 'cw_change_product_price_display', 100, 2 );
    add_filter( 'woocommerce_cart_item_price', 'cw_change_product_price_display', 100, 2 );
    function cw_change_product_price_display( $price_html, $mixed ) {
        $product = is_a($mixed, 'WC_product') ? $mixed : $mixed['data'];
    
        if ( $product->is_on_sale() ) {
            $price_html = sprintf('<span>%s:</span> <br>%s', __('Your sale price is', 'woocommerce'), $price_html);
        }
        return $price_html;
    }
    

    If you don’t want to have this on cart items, remove:

    add_filter( 'woocommerce_cart_item_price', 'cw_change_product_price_display', 100, 2 );
    

    If you want to have this only on WooCommerce archive pages, replace:

    if ( $product->is_on_sale() ) {
    

    with:

    if ( ! is_product() && $product->is_on_sale() ) {
    

    Code goes in functions.php file of your child theme (or in a plugin). Tested and works.

    Login or Signup to reply.
  2. You can use the woocommerce_format_sale_price filter. Have a look at the docs.

    add_filter( 'woocommerce_format_sale_price', 'add_text_to_sales', 100, 3 );
    function add_text_to_sales( $price, $regular_price, $sale_price ) {
        // Your additional text in a translatable string
        $text = __('<span>Your sale price is:</span><br>');
        
        return $text . $price;
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search