【问题标题】:Disable default country in WooCommerce if geolocation fails如果地理定位失败,请在 WooCommerce 中禁用默认国家/地区
【发布时间】:2022-01-21 02:48:19
【问题描述】:

WooCommerce 设置了客户的默认国家/地区。它可以被禁用,设置为商店地址国家,或按地理位置设置。

我的问题是,当使用地理定位选项时,如果无法返回商店允许的国家/地区,它现在将恢复使用商店地址国家/地区。

我想要的是在地理定位失败时没有默认选择的国家/地区。

我知道这应该可以通过functions.php 中的一些代码实现。我使用过更改默认国家/地区的代码,例如找到here 的代码。它还具有测试它是否是现有客户的优势,他们的账户上有一个国家(我想包括的东西)。我还发现了一些代码可以测试地理位置是否设置了国家,例如:

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;
}

来源:WooCommerce: Set default Country in Billing (using Geo Location) but not in Shipping in checkout page答案码。

我尝试将这些东西拼凑在一起,但没有奏效。

例如

add_filter( 'default_checkout_billing_country', 'change_default_checkout_country', 10, 1 );

function change_default_checkout_country( $country ) {
    // If the user already exists, don't override country
    if ( WC()->customer->get_is_paying_customer() ) {
        return $country;
    }

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

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

    else {
        return null;
    }
}

这不起作用。虽然我怀疑它很接近。我对 PHP 的了解相当基础,所以我可能犯了一些明显的错误。

【问题讨论】:

    标签: php wordpress woocommerce geolocation


    【解决方案1】:

    您的代码本身没有问题,只有 如果满足 elseif 条件,但不满足 elseif 中的 if 条件,您不应假设执行 else 条件。

    基本上,你的 elseif 条件中缺少一个 else

    所以你得到:

    function filter_default_checkout_billing_country( $default ) {  
        // If the user already exists, don't override country
        if ( WC()->customer->get_is_paying_customer() ) {
            return $default;
        } elseif ( class_exists( 'WC_Geolocation' ) ) {
            // Get location country
            $location = WC_Geolocation::geolocate_ip();
            
            if ( isset( $location['country'] ) ) {
                return $location['country'];
            } else {
                $default = null;
            }
        } else {
            $default = null;
        }
        
        return $default;
    }
    add_filter( 'default_checkout_billing_country', 'filter_default_checkout_billing_country', 10, 1 );
    

    【讨论】:

    • 谢谢。使用它的站点有另一个自定义结帐的插件。我以为它仍在使用标准的 WooCommerce 函数等。我现在意识到它必须使用自己的一组函数等,因此我的代码中的过滤器因此没有生效。我将不得不与该插件的开发人员一起讨论。我很高兴知道我的解决方案几乎是正确的。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多