Display a text after cart and checkout totals for specific countries in Woocommerce

Viewed 445

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?

2 Answers

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;
}

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.

Related