On Display a custom message based on customer shipping zone in Woocommerce answer, I found a solution to show a message in cart based on the shipping zone.
I want to show a message based on shipping zones and only if the cart amount is smaller than a specific amount, like:
- Shipping Zone 1 and Cart amount is smaller than €29: it should show Text 1
and - Shipping Zone 2 and Cart amount is smaller than €49: it should show Text 2
This is what I tried to edit the PHP code by myself:
add_action( 'woocommerce_cart_totals_after_shipping', 'shipping_notice_displayed', 20 );
add_action( 'woocommerce_review_order_after_shipping', 'shipping_notice_displayed', 20 );
function shipping_notice_displayed() {
if ( did_action( 'woocommerce_cart_totals_after_shipping' ) >= 2 ||
did_action( 'woocommerce_review_order_after_shipping' ) >= 2 ) {
return;
}
// Chosen Shipping Method
$chosen_shipping_zone_id = WC()->session->get( 'chosen_shipping_methods' )[0];
$chosen_shipping_zone = explode(':', $chosen_shipping_method_id)[0];
$cart_subtotal = WC()->cart->subtotal;
// Settings
$cart_maximum1 = 29;
$cart_maximum2 = 49;
// HERE define the cart maximum
if ( $cart_subtotal < $cart_maximum2 && $chosen_shipping_zone != 'Shipping Zone I' ) {
$cart_maximum = $cart_maximum1;
} elseif ( $cart_subtotal < $cart_maximum2 && $chosen_shipping_method == 'Shipping Zone I' ) {
$cart_maximum = $cart_maximum2;
}
// Display a message
if( isset($cart_maximum) ){
// The message
$message = sprintf( 'Above 29,00 € cart total save 5 €!' ,
is_cart() ? 'Maximum' : 'Max',
strip_tags( wc_price( $cart_maximum, array('decimals' => 2 ) ) )
);
// Display
echo '</tr><tr class="shipping info"><th> </th><td data-title="Delivery info">'.$message.'</td>';
}
}
But get some errors and my code doesn’t work. How I can display different Cart Messages based on shipping zones and a max cart subtotal?
2
Answers
I added your code to my page an changed the Names of Zone 1 and 2 to my Zone names. As you can see with "...Rheinbach..." and "...Irrel...".
There are some mistakes and missing things in your code, try the following instead, to display a dynamic Cart Message based on the shipping zone and a threshold cart amount:
Code goes in functions.php file of your child theme (or in a plugin). Tested and works.