woocommerce offtopic - Shipping Location based on IP (Geolocation)

admin2025-06-04  2

I want to limit the Countries in the Shippiment to another address and Billing (Checkout) to the User IP Address location. Say the user is in USA I only want this country to show as a option under the dropdown country list or disable the option of changing the country. How would I do that? Thanks in advance.

I want to limit the Countries in the Shippiment to another address and Billing (Checkout) to the User IP Address location. Say the user is in USA I only want this country to show as a option under the dropdown country list or disable the option of changing the country. How would I do that? Thanks in advance.

Share Improve this question asked Nov 28, 2017 at 22:35 Denise PereiraDenise Pereira 211 silver badge2 bronze badges
Add a comment  | 

1 Answer 1

Reset to default 2

First of all to make geolocation work properly go to WooCommerce > Status and check MaxMind GeoIP database option, if there is red checkmark follow the provided instructions to download the database.

Then you can add this code to your theme (at the bottom of functions.php) or add it as a plugin or code snippet as changes in theme might get lost when you update it.

function wpse_287199_woo_checkout_country( $fields ) {
    $geoData = WC_Geolocation::geolocate_ip();
    $countries = WC()->countries->get_countries();

    $fields['billing']['billing_country'] = array(
        'type' => 'select',
        'label'     => __('Country', 'woocommerce'),
        'options' => array(
            $geoData['country'] => $countries[$geoData['country']]
        ),
        'class' => array(
            'form-row-wide',
            'address-field',
            'update_totals_on_change'
        )
    );

    $fields['shipping']['shipping_country'] = array(
        'type' => 'select',
        'label'     => __('Country', 'woocommerce'),
        'options' => array(
            $geoData['country'] => $countries[$geoData['country']]
        ),
        'class' => array(
            'form-row-wide',
            'address-field',
            'update_totals_on_change'
        )
    );

    return $fields;
}
add_filter( 'woocommerce_checkout_fields' , 'wpse_287199_woo_checkout_country' );

This code checks the client's IP geolocation and determines his country then it is used for shipping and billing as an only option.

转载请注明原文地址:http://conceptsofalgorithm.com/Algorithm/1748971816a315274.html

最新回复(0)