Search code examples
phpwordpresswoocommerceproduct

Replace WooCommerce 0 sale price with a custom text keeping regular price strike-through


I have been trying to change WooCommerce product's sale price only to "Free for members" instead of 0. I wanted to change the sale price to a custom text like:

enter image description here

I have searched the internet & found code snippets which does the same thing, but the problem is that it changes both sale price & regular price too.

This was the code I found here on Stack Overflow:

function my_wc_custom_get_price_html( $price, $product ) {
    if ( $product->get_price() == 0 ) {
        if ( $product->is_on_sale() && $product->get_regular_price() ) {
            $regular_price = wc_get_price_to_display( $product, array( 'qty' => 1, 'price' => $product->get_regular_price() ) );

            $price = wc_format_price_range( $regular_price, __( 'Free for members!', 'woocommerce' ) );
        } else {
            $price = '<span class="amount">' . __( 'Free!', 'woocommerce' ) . '</span>';
        }
    }

    return $price;
}

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

The problem is this code removes the strike-through on regular price too. Here is the result when I try to add some inline CSS to add strike-through:

enter image description here

What I am trying to achieve is to change the sale price like in this screenshot:

enter image description here


Solution

  • Try the following simplified code to display a strike-through regular price with a custom text, when a product is on sale with a 0 (zero) price:

    add_filter( 'woocommerce_get_price_html', 'custom_formatted_sale_price_html', 10, 2 );
    function custom_formatted_sale_price_html( $price_html, $product ) {
        if ( $product->is_on_sale() && $product->get_price() !== 0 ) {
            $regular_price   = wc_get_price_to_display( $product, array( 'price' => $product->get_regular_price() ) );
            $sale_price_text = $regular_price > 0 ? __( 'Free only for members!', 'woocommerce' ) : __( 'Free!', 'woocommerce' );
            $style           = $regular_price > 0 ? ' style="background-color:#08A04B;color:white;padding:0 5px;"' : '';
     
            return '<del aria-hidden="true">' . wc_price( $regular_price ) . '</del> <span'.$style.'>' .  $sale_price_text . '</span>';
        }
        return $price_html;
    }
    

    It should work as you expect.