【问题标题】:Get user geolocated country name in Woocommerce 3在 Woocommerce 3 中获取用户地理定位的国家/地区名称
【发布时间】:2018-07-10 22:58:12
【问题描述】:

我想根据用户 geoip 国家/地区名称在 WooCommerce 标头中添加 “We ship to {country name}”?

我想在我的 WooCommerce 商店的标题中写入 html 内容,例如 We ship to "Your Country name"

任何帮助将不胜感激?

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

【问题讨论】:

    标签: php html wordpress woocommerce geoip


    【解决方案1】:

    您可以通过这种方式基于WC_Geolocation Class 制作自定义函数:

    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]" );
    

    【讨论】:

    • @loiceTheAztec,谢谢你的帮助,我试过了,我得到了这个错误“解析错误:语法错误,意外'
    • 我已经删除了“
    • 非常感谢 Loic,现在我正在尝试将此 php 代码添加到我的菜单中,您知道如何将其添加到 wordpress 菜单中吗?
    • @Kristina Wordpress 主题不是我的强项……所以我现在还不知道,这取决于你的主题。可以用它制作一个简码,但它不会帮助你更多......
    • 我想我会将其转换为可能更好的简码。现在试一试。非常感谢你,洛伊克。你说的太好了:)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多