在Woocommerce 3中获取用户所在地的国家名称

9
我希望根据用户的地理位置国家名称,在WooCommerce页眉中添加“我们发送到{国家名称}

我想在我的WooCommerce商店的页眉中编写HTML内容,例如我们发送到“您的国家名称”

如果有任何帮助,将非常感激?

我已经启用了WooCommerce地理定位。

1个回答

17

你可以这样基于WC_Geolocation来创建自定义函数:

function get_user_geo_country(){
    $geo      = new WC_Geolocation(); // Get WC_Geolocation instance object
    $user_ip  = $geo->get_ip_address(); // Get user IP
    $user_geo = $geo->geolocate_ip( $user_ip ); // Get geolocated user data.
    $country  = $user_geo['country']; // Get the country code
    return WC()->countries->countries[ $country ]; // return the country name

}

将代码添加到您活动的子主题(或活动主题)的function.php文件中。已经测试并且有效。


使用方法

您将在子主题的header.php文件中添加以下代码:

1) 在html代码之间:

<?php printf( '<p>' . __('We ship to %s', 'woocommerce') . '</p>', get_user_geo_country() ); ?>

2) 或在 PHP 代码中间:

printf( '<p>' . __('We ship to %s', 'woocommerce') . '</p>', get_user_geo_country() );

将此转换为短代码:

function get_user_geo_country(){
    $geo      = new WC_Geolocation(); // Get WC_Geolocation instance object
    $user_ip  = $geo->get_ip_address(); // Get user IP
    $user_geo = $geo->geolocate_ip( $user_ip ); // Get geolocated user data.
    $country  = $user_geo['country']; // Get the country code
    return sprintf( '<p>' . __('We ship to %s', 'woocommerce') . '</p>', WC()->countries->countries[ $country ] );
}
add_shortcode('geoip_country', 'get_user_geo_country');

将代码放入您的活动子主题(或活动主题)的function.php文件中。 已测试并且有效。

在后端文本编辑器中的常规简码用法

[geoip_country]

或者在 PHP 代码中:

echo do_shortcode( "[geoip_country]" );

1
我已经删除了 "<?php",现在它可以工作了,这样可以吗?或者请告诉我如何关闭标签,因为它似乎已经关闭了。 - Kristina
非常感谢Loic,现在我正在尝试将这个PHP代码添加到我的菜单中,您有任何想法如何将其添加到WordPress菜单中吗? - Kristina
@Kristina WordPress主题并不是我的强项,所以我现在还不知道,这取决于你的主题。虽然可以用它来制作短代码,但这不会给你带来更多帮助... - LoicTheAztec
我想我会将它转换为一个短代码,这可能会更好。现在试一试。非常感谢你,Loic。你真是太好了 :) - Kristina
Loic是个天才! - Juan
显示剩余2条评论

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接