Replace WooCommerce 0 sale price with custom text and keep regular price strikethrough
P粉190883225
P粉190883225 2024-03-22 10:51:29
0
1
415

I've been trying to change the sales price of my WooCommerce products to just "Members Free" instead of 0. I want to change the sales price to custom text, for example:

I searched on the internet and found a code snippet that does the same thing, but the problem is that it also changes the sale price and regular price.

This is the code I found 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 that this code also removes the strikethrough on the normal price. This is the result when I try to add some inline CSS to add strikethrough:

What I want to achieve is to change the sales price as shown in the screenshot below:

P粉190883225
P粉190883225

reply all(1)
P粉420868294

When a product is on sale with a 0 (zero) price, try using the following simplified code to display the regular price with strikethrough in custom text:

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.

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template