问题描述
我需要在价格后的 Woocommerce order-total 单元格中显示一条消息,但前提是客户所在的国家/地区是美国或加拿大。我有这个
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;
}
如果客户所在的国家/地区是美国或加拿大,我如何仅添加文本?
解决方法
如果您正在使用 Geolocation 函数并拥有相应的 API 密钥,则可以使用 WC_Geolocation
类。
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;
}
,
要在代码中定位特定国家/地区,您将使用 WC_Customer get_shipping_country()
方法(对未登录用户使用地理定位国家/地区),如下所示:
add_filter( 'woocommerce_cart_totals_order_total_html',1 );
function custom_total_message_html( $value ) {
if( in_array( WC()->customer->get_shipping_country(),'CA') ) ) {
$value .= '<small>' . __('My text.','woocommerce') . '</small>';
}
return $value;
}
代码位于活动子主题(或活动主题)的functions.php 文件中。经测试有效。