Reputation: 2471
I am creating a plugin for Woocommerce and I need to block it from being installed when store country is not in US (for example)
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
}
In my init function, I try to get the store country (got ERROR here) and if it is not US, I show error and not let them install the plugin. However, I got error: Call to a member function get_base_country() on null.
I believe that my function is called when the Woocommerce object is not ready. Could you show me the right hook to achieve that? I want to get the store location to check if my plugin supports that country
Note: what do I mean shop/store country? I refer to the country field that is in the Woocommerce setting.
Upvotes: 0
Views: 1320
Reputation: 253886
To get the shop base country you, don't need to use WC_Countries Class, so replace:
$shop_country = WC()->countries->get_base_country();
By:
$shop_country = wc_get_base_location()['country'];
Or by this too:
$shop_location = get_option( 'woocommerce_default_country' );
$shop_location = explode(':', $shop_location);
$shop_country = reset($shop_location);
As the shop base location is stored in wp_options
table.
Upvotes: 1