2

I need to display a message in the Woocommerce order-total cell after the price, but only if the customer's country is US or Canada. I have this

add_filter( 'woocommerce_cart_totals_order_total_html', 'custom_total_message_html', 10, 1 );
function custom_total_message_html( $value ) {
    $value .= __('<small>My text.</small>');

return $value;
}

How can I only add the text if the customer's country is US or Canada?

LoicTheAztec
  • 229,944
  • 23
  • 356
  • 399
hara55
  • 67
  • 5

2 Answers2

2

To target specific countries in your code, you will use WC_Customer get_shipping_country() method (that use geolocation country for unlogged users), as follows:

add_filter( 'woocommerce_cart_totals_order_total_html', 'custom_total_message_html', 10, 1 );
function custom_total_message_html( $value ) {
    if( in_array( WC()->customer->get_shipping_country(), array('US', 'CA') ) ) {
        $value .= '<small>' . __('My text.', 'woocommerce') . '</small>';
    }
    return $value;
}

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

LoicTheAztec
  • 229,944
  • 23
  • 356
  • 399
  • Sorry I just realized that I forgot to mention that it shoudl also be displayedafter the totals in order emails - could the snippet be adapted? – hara55 Jan 04 '21 at 19:05
  • @hara55… First search a bit in stack overflow answers for similar questions… Then you should ask a new question if you don't find the right way to do it. – LoicTheAztec Jan 05 '21 at 03:31
  • I did lots of research...could not get it to work. I opened another question: https://stackoverflow.com/questions/65581987/adding-custom-text-after-order-totals-in-woocommerce-plain-emails – hara55 Jan 07 '21 at 06:17
1

If you're using the Geolocation functions and have an API key for it, you can use the WC_Geolocation class.

add_filter( 'woocommerce_cart_totals_order_total_html', 'custom_total_message_html', 10, 1 );
function custom_total_message_html( $value ) {
    $geolocation = WC_Geolocation::geolocate_ip();
    if (in_array($geolocation['country'], array('US', 'CA'))){
        $value .= __('<small>My text.</small>');
    }
    return $value;
}
Howard E
  • 5,454
  • 3
  • 15
  • 24