Display a custom message based on customer shipping zone in Woocommerce Display a custom message based on customer shipping zone in Woocommerce wordpress wordpress

Display a custom message based on customer shipping zone in Woocommerce


Updated

Try the following code based on a shipping Zones name (with postcodes restrictions) that will display your message on the shipping total lines (but that will not generate a woocommerce notice):

add_action( 'woocommerce_cart_totals_after_shipping' , 'shipping_zone_targeted_postcodes_custom_notice' );add_action( 'woocommerce_review_order_after_shipping' , 'shipping_zone_targeted_postcodes_custom_notice' );function shipping_zone_targeted_postcodes_custom_notice() {    // HERE DEFINE YOUR SHIPPING ZONE NAME(S)    $targeted_zones_names = array('France'); // <======  <======  <======  <======  <======      // Get the customer shipping zone name    $chosen_methods    = WC()->session->get( 'chosen_shipping_methods' ); // The chosen shipping mehod    $chosen_method     = explode(':', reset($chosen_methods) );    $shipping_zone     = WC_Shipping_Zones::get_zone_by( 'instance_id', $chosen_method[1] );    $current_zone_name = $shipping_zone->get_zone_name();    if( in_array( $current_zone_name, $targeted_zones_names ) ){        echo '<tr class="shipping">            <td colspan="2" style="text-align:center">' . sprintf(                __( "You'll be charged %s more for %s zip code", "woocommerce"),                '<strong>10%</strong>',                '<strong>' . WC()->customer->get_shipping_postcode() . '</strong>'            ) . '</td>        </tr>';    }}

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

enter image description here


Using @LoicTheAztec's solution above, I modified it to give a message based on customer's country.

add_action( 'woocommerce_cart_totals_after_shipping' , 'out_of_zone_shipping_notice' );add_action( 'woocommerce_review_order_after_shipping' , 'out_of_zone_shipping_notice' );function out_of_zone_shipping_notice() {    // HERE DEFINE YOUR SHIPPING COUNTRY NAMES    $targeted_country_names = array("CA", "US"); //     // Get the customer shipping country    $shipping_country    = WC()->customer->get_shipping_country();        if( !in_array( $shipping_country, $targeted_country_names ) ){        echo '<tr class="shipping"><td colspan="2" style="text-align:center">You are outside of our regular shipping zone. Please <a href="../contact/">contact us</a> with your address so we can get an accurate cost to ship.</td></tr>';    }}

In order to see what format the $shipping_country showed up in, I used

echo $shipping_country

just below $shipping_country = WC()->customer->get_country(); to show on the cart page what the actual country code syntax was so that I could match it with the if statement. However, this code segment was removed prior to deployment to avoid random characters on the screen for the customer.