Control Activation of a WooCommerce Extension

When creating a WooCommerce extension, it’s important to consider that when the extension is activated, the user may not have WooCommerce installed or active.

And though an extension might activate, it won’t do anything. This can ultimately provide a level of confusion for the user.

WooCommerce Extension

In cases like this, I think it’s important to make sure an extension can only be activated if the core plugin is installed and active.

Activating a WooCommerce Extension

Though some extensions for WooCommerce are similar to others, the implementation from one to the other can vary. That is, the way one extension is written might use an entirely different paradigm the other.

Whatever the case, if you opt to do something like this, here’s something to consider:

  1. Define a class that starts when the plugin starts,
  2. Check to see if WooCommerce is active,
  3. If so, then load all of the other dependences,
  4. If not, then automatically deactivate the plugin.

It sounds like a lot of work, but it’s not that much code. You may also want to consider adding a custom plugin notice when activation is denied but I’ll cover how to do that in a future post.

1. Define a Class

Generally, I think it’s a good idea to have a function for starting and for stopping the plugin. If WooCommerce is active, then you can start the entire extension; otherwise, we have to stop its activation.

To do this, we can hook into the admin_init hook for each of the functions.

When the plugin is started from the WordPress admin, the init function will need to be called programmatically from the main plugin’s entry function.

2. Check if WooCommerce Is Active

Before implementing either function, though, we need to check to see if the WooCommerce plugin is active. It’s usually safe to assume that WooCommerce is located in a fixed directory which is what this code does:

However, if WooCommerce is located elsewhere, you may need to do some other checking until you find it.

3. Load the Dependencies

In the start function, if WooCommerce is active, then we can load the rest of the components for the plugin:

But WooCommerce may not be active.

4. Or Stop Activation

And if WooCommerce isn’t active, then we need to stop activation of this plugin:

Note that even if you do bulk activation of the plugin this code, this code may not work. Here’s why:

  1. WordPress will work through the list of plugins that it needs to activate.
  2. If WooCommerce hasn’t been activated before the extension, then the extension will fail to activate.

So another way of approaching this would be to activate WooCommerce if it’s not already active.

Custom Messages

As mentioned earlier, I think it’s a good idea to give some type of administration notice when plugin activation is denied, but that’s beyond the scope of this tutorial.

Whatever the case, the above code provides one way to control activation of a WooCommerce extension potentially.