仅限结帐页面中的1个国家/地区使用wordpress和woocommerce

ken*_*ter 4 wordpress woocommerce

我正在使用wordpress和woocommerce.在结帐页面中,我如何仅限于1个国家/地区?说澳大利亚.

在此输入图像描述

小智 8

您好,您可以通过插件设置限制为只有一个国家/地区

woocommerce插件设置

你可以在Woocommerce - > 设置 - > Genral标签中找到


Ahm*_*ani 5

只需通过钩子覆盖类,

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' );
Run Code Online (Sandbox Code Playgroud)

这将帮助您在下拉列表中仅显示 1 个国家/地区。将此代码添加到主题中的functions.php。


hor*_*gaz 5

另外,也许您想向多个国家/地区销售产品,但您也想仅显示用户连接所在的国家/地区(通过 IP 地址进行地理定位)。因此,通过这种方式,法国用户只会在国家/地区下拉列表中看到法国,澳大利亚用户只会在国家/地区下拉列表中看到澳大利亚,依此类推...以下是代码:

/**
 * @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 );
Run Code Online (Sandbox Code Playgroud)