I use the following code in WooCommerce, to replace the displayed product zero price with a custom text:
add_filter( 'woocommerce_get_price_html', 'wtwh_price_free_zero', 9999, 2 );
function wtwh_price_free_zero( $price, $product ) {
if ( $product->is_type( 'variable' ) ) {
$prices = $product->get_variation_prices( true );
$min_price = current( $prices['price'] );
if ( 0 == $min_price ) {
$max_price = end( $prices['price'] );
$min_reg_price = current( $prices['regular_price'] );
$max_reg_price = end( $prices['regular_price'] );
if ( $min_price !== $max_price ) {
$price = wc_format_price_range( 'FREE', $max_price );
$price .= $product->get_price_suffix();
} elseif ( $product->is_on_sale() && $min_reg_price === $max_reg_price ) {
$price = wc_format_sale_price( wc_price( $max_reg_price ), 'FREE' );
$price .= $product->get_price_suffix();
} else {
$price = 'FREE';
}
}
} elseif ( 0 == $product->get_price() ) {
$price = '<span class="woocommerce-Price-amount amount">Contact us for a unique quote!</span>';
}
return $price;
}
The problem is that this doesn't work for my variable products, and I would like to have a similar behavior for those variable products, replacing zero formatted price with "FREE" string.
How to replace product displayed zero price by a text for WooCommerce variable products?
You were near. You can use str_replace()
PHP function to replace the zero formatted price with "FREE" string for your variable products. This way, the required code will e simpler and compact.
Try the following revised code replacement:
add_filter( 'woocommerce_get_price_html', 'custom_display_for_product_with_zero_price', 9999, 2 );
function custom_display_for_product_with_zero_price( $price_html, $product ) {
if ( $product->is_type( 'variable' ) ) {
// Replace any formatted zero price with "FREE" string
$price_html = str_replace( wc_price(0), esc_html__('FREE', 'woocommerce'), $price_html );
} elseif ( 0 == $product->get_price() ) {
$price_html = sprintf(
'<span class="woocommerce-Price-amount amount">%s</span>',
esc_html__('Contact us for a unique quote!', 'woocommerce')
);
}
return $price_html;
}
Now it should work for your variable product(s).