pgilpat
pgilpat

Reputation: 21

Replace zero or empty displayed prices with a custom text label in Woocommerce

I've added this code which works for empty price fields, but I also need it to work for values of 0.

add_filter('woocommerce_empty_price_html', 'custom_call_for_price');

function custom_call_for_price() {

    return 'Enquire';
}

Upvotes: 2

Views: 5526

Answers (1)

LoicTheAztec
LoicTheAztec

Reputation: 253929

Here is the complete way to do it for BOTH empty and zero displayed prices, so this code replace also your actual code (to be removed).

It handle simple, variable and variation displayed prices (for BOTH empty and zero displayed prices):

// Variable and simple product displayed prices
add_filter( 'woocommerce_get_price_html', 'empty_and_zero_price_html', 20, 2 );
function empty_and_zero_price_html( $price, $product ) {
    $empty_price = __('Enquire', 'woocommerce');

    if( $product->is_type('variable') )
    {
        $prices = $product->get_variation_prices( true );

        if ( empty( $prices['price'] ) ) {
            return $empty_price; // <=== HERE below for empty price
        } else {
            $min_price     = current( $prices['price'] );
            $max_price     = end( $prices['price'] );
            if ( $min_price === $max_price && 0 == $min_price ) {
                return $empty_price; // <=== HERE for zero price
            }
            elseif ( $min_price !== $max_price && 0 == $min_price ) {
                return wc_price( $max_price );
            }
        }
    }
    elseif( $product->is_type('simple') )
    {
        if ( '' === $product->get_price() || 0 == $product->get_price() ) {
            return $empty_price; // <=== HERE for empty and zero prices
        }
    }
    return $price;
}

// Product Variation displayed prices
add_filter( 'woocommerce_available_variation', 'empty_and_zero_variation_prices_html', 10, 3);
function empty_and_zero_variation_prices_html( $data, $product, $variation ) {

    if( '' === $variation->get_price() || 0 == $variation->get_price() )
        $data['price_html'] = __('Enquire', 'woocommerce'); // <=== HERE for empty and zero prices

    return $data;
}

Code goes in function.php file of your active child theme (or active theme). Tested and works.

Upvotes: 7

Related Questions