Php WooCommerce:在帐单(使用地理位置)中设置默认国家/地区,但在签出页面中不设置发货

Php WooCommerce:在帐单(使用地理位置)中设置默认国家/地区,但在签出页面中不设置发货,php,ajax,wordpress,woocommerce,Php,Ajax,Wordpress,Woocommerce,我目前使用下面的代码来设置默认国家(基于用户当前的地理位置) 上述代码不仅影响计费部分,还影响发货部分。在这种情况下,美国用户只能向我们发货;来自加拿大的用户只能发送到加拿大等 如果有一种方式,它仍然默认为账单上的国家,但用户可以发送到其他国家?我检查了每个钩子/过滤器,没有发现任何有用的东西。所以我想出了这个解决方案。将此代码添加到子主题functions.php文件: add_action( 'wp_enqueue_scripts', 'wp_enqueue_scripts_action'

我目前使用下面的代码来设置默认国家(基于用户当前的地理位置)

上述代码不仅影响计费部分,还影响发货部分。在这种情况下,美国用户只能向我们发货;来自加拿大的用户只能发送到加拿大等


如果有一种方式,它仍然默认为账单上的国家,但用户可以发送到其他国家?

我检查了每个钩子/过滤器,没有发现任何有用的东西。所以我想出了这个解决方案。将此代码添加到子主题
functions.php
文件:

add_action( 'wp_enqueue_scripts', 'wp_enqueue_scripts_action' );
function wp_enqueue_scripts_action() {
    wp_register_script( 'test-script', get_stylesheet_directory_uri() . '/test.js', [ 'jquery', ] );
    wp_enqueue_script( 'test-script' );

    wp_localize_script( 'test-script', 'test_script', [
            'customer_country' => get_customer_geo_location_country()
        ]
    );
}

/**
 * Returns the customer country
 *
 * @return string|null
 */
function get_customer_geo_location_country(): ?string {
    if ( class_exists( 'WC_Geolocation' ) ) {
        $location = WC_Geolocation::geolocate_ip();

        if ( isset( $location['country'] ) ) {
            return $location['country'];
        }
    }

    return null;
}

add_action( 'woocommerce_after_checkout_validation', 'woocommerce_after_checkout_validation_action', 10, 2 );
function woocommerce_after_checkout_validation_action( $fields, $errors ) {
    $billing_country = $fields['billing_country'];

    if ( ! empty( $billing_country ) && $billing_country !== get_customer_geo_location_country() ) {
        $errors->add( 'validation', 'You are not allowed to select this billing country!' );
    }
}
首先,我们添加一个新脚本。如果已经有脚本,只需复制
wp\u localize\u script
函数并更改处理程序和对象名称

使用此函数,我们可以将客户的当前国家/地区传递给我们的JavaScript文件。在这个文件中,我们执行以下操作:

(function ( $ ) {
    $( document ).ready( function () {
        if (test_script.customer_country) {
            $( '#billing_country option' ).each( function () {
                if ($( this ).val() !== test_script.customer_country) {
                    $( this ).remove();
                }
            } );
        }
    } );
})( jQuery );
这个小功能将从我们的账单选择中删除与客户国家不匹配的所有国家。如果需要,您可以在
else
语句中删除所有国家/地区,以确保在没有可用国家/地区的情况下客户无法订购

客户现在应该只在帐单国家/地区下拉列表中看到其本国

为了确保他不会攻击我们,我们在结帐中添加了一点验证,再次验证所选国家

如果您在本地主机上测试此功能,则没有国家/地区可用,因此请确保它位于web上的实时网站上(甚至登台)


这是一个基本的想法。您需要对其进行测试,或者根据需要进行调整。

顺便问一下,您的网站证书无效。我的回答对您有帮助吗?如果有,请勾选它。先生,我花了一些时间把一切弄清楚。是的,先生!它就像一个符咒!
(function ( $ ) {
    $( document ).ready( function () {
        if (test_script.customer_country) {
            $( '#billing_country option' ).each( function () {
                if ($( this ).val() !== test_script.customer_country) {
                    $( this ).remove();
                }
            } );
        }
    } );
})( jQuery );