在第三方 WooCommerce 插件中获取商店基地国家

Get the shop base country in a third party WooCommerce plugin

我正在为 Woocommerce 创建一个插件,我需要阻止它在商店国家/地区不在美国时安装(例如)

function init(){
    if (in_array( 'woocommerce/woocommerce.php', apply_filters( 'active_plugins', get_option( 'active_plugins' )))) {

        $shop_country = WC()->countries->get_base_country(); // FAIL: Call to a member function get_base_country() on null 

        if ($shop_country !== 'US') {
            add_action( 'admin_notices', 'show_error' ); return;
        }

        /**
         * The core plugin class that is used to define internationalization,
         * admin-specific hooks, and public-facing site hooks.
         */

        init_my_plugin();
    }
    else{
        add_action( 'admin_notices', 'show_error' );
    }
}
add_action('plugins_loaded','init');

function show_error(){
    ?>
    <div class="error">
        <p><?php _e( 'This plugin requires WooCommerce in order to work.', 'plugin' ); ?></p>
    </div>
    <?php
}

在我的 init 函数中,我尝试获取商店所在的国家/地区(此处出现错误),如果不是美国,我将显示错误并且不让他们安装插件。但是,我收到错误:Call to a member function get_base_country() on null.

我相信我的函数是在 Woocommerce 对象未准备好时调用的。你能告诉我实现这一目标的正确钩子吗?我想获取商店位置以检查我的插件是否支持该国家/地区

注意:shop/store 国家/地区是什么意思?我指的是 Woocommerce 设置中的国家/地区字段。

要获取您的商店基地国家,不需要使用 WC_Countries Class,因此替换为:

$shop_country = WC()->countries->get_base_country(); 

作者:

$shop_country = wc_get_base_location()['country'];

或者也可以这样:

$shop_location = get_option( 'woocommerce_default_country' ); 
$shop_location = explode(':', $shop_location);
$shop_country  = reset($shop_location); 

由于商店基地位置存储在 wp_options table.