Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Strict to 1 country only in checkout page with wordpress and woocommerce

I am using wordpress and woocommerce. In checkout page, how do I restrict to only 1 country only? Say Australia.

enter image description here

like image 766
kenpeter Avatar asked Jul 29 '17 05:07

kenpeter


3 Answers

Hello you can restrict to only one country by plugin settings

woocommerce plugin settings

you can find in Woocommerce->Settings-> Genral tab

like image 78
akshay saxena Avatar answered Nov 15 '22 13:11

akshay saxena


Just override the class by hook,

function woo_override_checkout_fields_billing( $fields ) { 

    $fields['billing']['billing_country'] = array(
        'type'      => 'select',
        'label'     => __('My New Country List', 'woocommerce'),
        'options'   => array('AU' => 'Australia')
    );

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

function woo_override_checkout_fields_shipping( $fields ) { 

    $fields['shipping']['shipping_country'] = array(
        'type'      => 'select',
        'label'     => __('My New Country List', 'woocommerce'),
        'options'   => array('AU' => 'Australia')
    );

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

This will help you to show only 1 country in dropdown. Add this code to functions.php in theme.

like image 23
Ahmed Ginani Avatar answered Nov 15 '22 13:11

Ahmed Ginani


Also maybe you want to sell to several countries but also you want to show ONLY the country where the user is connecting from (geolocated from IP address). Thus, in this way, a french user will only see France in the country dropdown, an australian user will only see Australia in the country dropdown and so on... Here is the code:

/**
 * @param array $countries
 * @return array
 */
function custom_update_allowed_countries( $countries ) {

    // Only on frontend
    if( is_admin() ) return $countries;

    if( class_exists( 'WC_Geolocation' ) ) {
        $location = WC_Geolocation::geolocate_ip();

        if ( isset( $location['country'] ) ) {
            $countryCode = $location['country'];
        } else {
            // If there is no country, then return allowed countries
            return $countries;
        }
    } else {
        // If you can't geolocate user country by IP, then return allowed countries
        return $countries;
    }

    // If everything went ok then I filter user country in the allowed countries array
    $user_country_code_array = array( $countryCode );

    $intersect_countries = array_intersect_key( $countries, array_flip( $user_country_code_array ) );

    return $intersect_countries;
}
add_filter( 'woocommerce_countries_allowed_countries', 'custom_update_allowed_countries', 30, 1 );
like image 36
hormigaz Avatar answered Nov 15 '22 13:11

hormigaz