Skip to content
Advertisement

Add a free shipping notice based on WooCommerce product price

I’m trying to make a custom code for two situations (considering both simple & variable products) :

  • 1 free shipping notice if the price is lower than 25 €
  • 1 free shipping notice if the price is higher than 25 €

This is my code attempt:

/**
 * FREE SHIPPING NOTICE IF PRICE BELOW 25 €
 */
add_action( 'woocommerce_single_product_summary', 'custom_text1', 15 );
function custom_text1() {
    // We retrieve the minimum of the product
    $min_price = $product->get_variation_price( 'min', true );

    // If price is lower than 25, show first label
    if ($min_price < 25) {
        print '<p class="custom_text1">+ livraison gratuite à partir de 25 €</br>(Belgique, France, Pays-Bas)</p>';
    }
}

/**
 * FREE SHIPPING NOTICE IF PRICE ABOVE 25 €
 */
add_action( 'woocommerce_single_product_summary', 'custom_text2', 15 );
function custom_text2() {
    // We retrieve the minimum of the product
    $min_price = $product->get_variation_price( 'min', true );

    // If price is higher than 25, show second label
    if ($min_price >= 25) {
        print '<p class="custom_text2">+ livraison gratuite</br>(Belgique, France, Pays-Bas)</p>';
    }
}

I don’t have enough experience, and it’s not working.

What I am doing wrong? Can someone help me to better achieve this?

Advertisement

Answer

The WC_Product Object $product need to be defined and you can merge both functions into one, for variable products and other product types, like:

add_action( 'woocommerce_single_product_summary', 'custom_single_product_summary_text', 15 );
function custom_single_product_summary_text() {
    global $product;
    
    $price_threshold = 25;

    // Avoid 'cadeaux' product category
    if( has_term( array('Cadeaux'), 'product_cat', $product->get_id() ) ) {
        return;
    }
    
    if( $product->is_type('variable') ) {
        $price = $product->get_variation_price( 'min', true ); // Min price
    } else {
        $price = wc_get_price_to_display( $product );
    }


    // If price is lower than 25
    if ( $price < $price_threshold ) {
        $message = __("+ livraison gratuite jusqu'à 25€</br>(Belgique, France, Pays-Bas)", "text_domain");
    } 
    // If price is up to 25
    else {
        $message = __("+ livraison gratuite à partir de 25 € </br>(Belgique, France, Pays-Bas)", "text_domain");
    }
    echo '<p class="custom_text1">' . $message . '</p>';
}

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

User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement