Show message on cart based on total order value on WooCommerce

Viewed 58

I am trying to display a notice on cart based on total order value: (for each 28.50€ spent, the costumer is donating 1 product to hospitals)

Here's what I did so far (without success)

  function wc_donation_message() {


// Get some variables
$cart_total     = (float) WC()->cart->total; // Total cart amount

// Conditional messages
if ( $cart_total >= 28.50 ) {
    wc_add_notice( sprintf(
        __("Thank you! You just donated 1 meal", "woocommerce"), // Text message
        )
}
if ( $cart_total >= 57 ) {
    wc_add_notice( sprintf(
        __("Thank you! You just donated 2 meals", "woocommerce"), // Text message
        )
}

}

1 Answers

Here is the solution (updated based on comment):

// show a notice in the cart based on the total amount
add_action( 'woocommerce_before_cart', 'boozers_count_cart_bottles' );
function boozers_count_cart_bottles() {
    // gets the total of the cart
    $total = WC()->cart->total;
    // set the step
    $step = 28.5;
    // calculate the number of meals
    $meals = floor( $total / $step );

    // show a different message if "$meals" is less than 1
    if ( $meals < 1 ) {
        wc_print_notice( 'Thank you! Your order contributed to our solidarity initiative.', 'notice' );
        return;
    }

    if ( $meals > 1 ) {
        $text = 'meals';
    } else {
        $text = 'meal';
    }
    // show the notice in the cart
    wc_print_notice( sprintf( __( 'Thank you! You just donated %u %s.' ), $meals, $text ), 'notice' );
}

The message will be shown at this point:

enter image description here

The code has been tested and works. Add it to your active theme's functions.php file.

Related