不允许客户在 WooCommerce 结帐中更改国家/地区

Disallow customer to change country in WooCommerce checkout

我正在寻找可以在 woocommerce 结帐页面中找到用户所在国家/地区的解决方案。我正在通过地理定位来做到这一点。但是,用户可以更改它。我要限制它。

我正在使用付费插件向来自特定国家/地区的用户赠送优惠券。该国家/地区已完美加载,并根据国家/地区应用或拒绝优惠券。但是,用户可以在结帐页面手动更改国家/地区并享受折扣。我的服务是在线的,因此没有实物交付,所以输入错误的国家不会对用户造成任何影响。

我试过2-3种不同的优惠券限制插件,但都有同样的问题。有没有人遇到过类似的问题?

已更新

您可以禁用结帐国家/地区下拉字段(只读),如下所示:

add_filter( 'woocommerce_checkout_fields', 'checkout_country_fields_disabled' );
function checkout_country_fields_disabled( $fields ) {
    $fields['billing']['billing_country']['custom_attributes']['disabled'] = 'disabled';
    $fields['billing']['shipping_country']['custom_attributes']['disabled'] = 'disabled';

    return $fields;
}

由于禁用的 select 字段未发布,您还需要以下重复的隐藏字段并设置了正确的值。这将避免错误通知通知国家必填字段值为空。所以也加上这个:

// Mandatory for disable fields (hidden billing and shipping country fields with correct values)
add_filter( 'woocommerce_after_checkout_billing_form', 'checkout_country_hidden_fields_replacement' );
function checkout_country_hidden_fields_replacement( $fields ) {
    $billing_country = WC()->customer->get_billing_country();
    $shipping_country = WC()->customer->get_shipping_country();
    ?>
    <input type="hidden" name="billing_country" value="<?php echo $billing_country; ?>">
    <input type="hidden" name="shipping_country" value="<?php echo $shipping_country; ?>">
    <?php
}

代码进入活动子主题(或活动主题)的 functions.php 文件。已测试并有效。


备注:

如果未完成,您将需要在购物车页面中禁用运费计算器。

如果您想在结账 和“我的帐户编辑地址” 中将国家/地区下拉列表设置为只读,请改用以下内容:

add_filter( 'woocommerce_billing_fields', 'checkout_billing_country_field_disabled' );
function checkout_billing_country_field_disabled( $fields ) {
    $fields['billing_country']['custom_attributes']['disabled'] = 'disabled';

    return $fields;
}

add_filter( 'woocommerce_shipping_fields', 'checkout_shipping_country_field_disabled' );
function checkout_shipping_country_field_disabled( $fields ) {
    $fields['shipping_country']['custom_attributes']['disabled'] = 'disabled';

    return $fields;
}

// Mandatory for disable fields (hidden billing and shipping country fields with correct values)
add_filter( 'woocommerce_after_checkout_billing_form', 'checkout_country_hidden_fields_replacement' );
function checkout_country_hidden_fields_replacement( $fields ) {
    $billing_country = WC()->customer->get_billing_country();
    $shipping_country = WC()->customer->get_shipping_country();
    ?>
    <input type="hidden" name="billing_country" value="<?php echo $billing_country; ?>">
    <input type="hidden" name="shipping_country" value="<?php echo $shipping_country; ?>">
    <?php
}