Get user geolocated country name in Woocommerce 3

前端 未结 1 1990
执念已碎
执念已碎 2020-12-09 14:19

I would like to add "We ship to {country name}" in WooCommerce header based on user geoip country name?

I would like to write

1条回答
  •  离开以前
    2020-12-09 15:10

    You can make a custom function based on WC_Geolocation Class this way:

    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
    
    }
    

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


    USAGE

    You will add the following code in your child theme's header.php file:

    1) in between html code:

    ' . __('We ship to %s', 'woocommerce') . '

    ', get_user_geo_country() ); ?>

    2) or in between php code:

    printf( '

    ' . __('We ship to %s', 'woocommerce') . '

    ', get_user_geo_country() );

    Converting this to Shortcode:

    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( '

    ' . __('We ship to %s', 'woocommerce') . '

    ', WC()->countries->countries[ $country ] ); } add_shortcode('geoip_country', 'get_user_geo_country');

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

    Normal shortcode usage (in the backend text editor):

    [geoip_country]
    

    or in php code:

    echo do_shortcode( "[geoip_country]" );
    

    0 讨论(0)
提交回复
热议问题