I’m developing a WordPress Woocommerce plugin. On my local environment it works fine but I have problems when adding the plugin to a replica of the prod environment. I am new to wordpress and not very familiar with web dev (I’m a Java programmer).
In the plugin file, I instantiate a class from the Woocommerce plugin package like this:
$coupon = new WC_Coupon($some_code);
In the local environment (php 5.4.10 , Woocommerce 2.0.13, WordPress 3.6) it’s fine. In the production environment (php 5.4.10 , Woocommerce 1.6.5.2, WordPress 3.4.2) I have the following error:
Fatal error: Class 'WC_Coupon' not found
I have tried including the file where the WC_Coupon class is defined but then the error becomes
Fatal error: Cannot redeclare class WC_Coupon
So what is the proper way to use classes declared in another plugin?
Note: upgrading is not an option at the moment.
You have to check if the class exists, but before that you have to wait that all plugin are loaded: no one can assure that your plugin is loaded after WooCommerce.
For run a code from plugin when all plugin are loaded hook into
plugins_loaded
hook.Be aware that you cannot use this hook in a theme, because when theme load that hook was already fired.
This is too late but I would like to share how to use woocommerce and its classes without having an error class not found.
First is to check if woocommerce is installed and use the
woocommerce_loaded
action hook.I hope this helps someone.
The proper way would be :
It’s better to check if class exists before using it, it avoids fatal error if the plugin is disabled.
You can’t redeclare a class it’s not allowed in PHP.
You can also extend class :
But most of the time and in this case with WooCommerce you’d better find a hook in documentation that will handle the job.