【问题标题】:Get the shop base country in a third party WooCommerce plugin在第三方 WooCommerce 插件中获取商店基础国家/地区
【发布时间】:2020-06-18 11:12:07
【问题描述】:

我正在为 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
}

在我的初始化函数中,我尝试获取商店国家/地区(此处出现错误),如果不是美国,我会显示错误并且不让他们安装插件。但是,我得到了错误:在 null 上调用成员函数 get_base_country()。

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

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

【问题讨论】:

    标签: php wordpress woocommerce plugins country


    【解决方案1】:

    要获得你的商店基地国家,不需要使用 WC_Countries 类,所以替换:

    $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 表中。

    【讨论】:

      猜你喜欢
      • 2014-09-22
      • 1970-01-01
      • 1970-01-01
      • 2021-03-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-07-09
      • 2018-12-17
      相关资源
      最近更新 更多