2
votes

In Woocommerce I'm trying to add text before price if is higher than 59€

I tried the following code (and others one) but they didn't work:

    add_filter( 'woocommerce_get_price_html', 'custom_price_message' );
function custom_price_message( $price ) {
if ($price>='59'){
$new_price = $price .__('(GRATIS!)');
}
return $new_price;
}

How can I do to add (GRATIS!) text before product price if it's higher than 59?

1

1 Answers

2
votes

Updated: You should try the following revisited function code:

add_filter( 'woocommerce_get_price_html', 'prepend_text_to_product_price', 20, 2 );
function prepend_text_to_product_price( $price_html, $product ) {
    // Only on frontend and excluding min/max prices on variable products
    if( is_admin() || $product->is_type('variable') ) 
        return $price_html;

    // Get product price
    $price = (float) $product->get_price(); // Regular price

    if( $price > 15 )
        $price_html = '<span>'.__('(GRATIS)', 'woocommerce' ).'</span> '.$price_html;
    
    return $price_html;
}

Code goes in function.php file of the active child theme (or active theme).

Tested and works.


For single product pages only you will replace this line:

if( $price > 15 ){

By this:

if( $price > 15 && is_product() ){

For single product pages and archives pages you will replace this line:

if( $price > 15 ){

By this:

if( $price > 15 && ( is_product() || is_shop() || is_product_category() || is_product_tag() ){