It happens during plugin development, we try to extend another plugin, but our plugin loads earlier than the other one, so we get an error as a result. The error is present because WP loads the plugins in name order and if you are not aware how do you name your plugin, got can quickly get an error.

Describing the problem

Let’s say we are creating a payment gateway for Woocommerce. What if, the plugin’s name is acme-gateway? That means we load first the gateway and later the Woocommerce. We will get an error because the functionalities are not defined what we would use.

We should know that every time when we turn on or off a plugin, WP runs an action what saves the fresh list of plugins to the database. Fortunately, we can hook into the action and filter the list of the plugins as we want.

Hook ’em out!

The hook what we will use is the pre_update_option_active_plugins. We can add a filter and implement our logic in a function or method. Now we want to put the acme-gateway plugin at the end of the plugins, what means WP will load it at the last place.

add_filter('pre_update_option_active_plugins', 'sort_plugins');
function sort_plugins($plugins)
{
    unset($plugins[array_search('acme-gateway/acme-gateway.php', $plugins)]);
    $plugins[] ='acme-gateway/acme-gateway.php';

    return $plugins;
}

So, what is happening here? We search for the index of the plugin in the plugins array; then we remove it by its index. In the end, we append it to the end.

Also, we have a problem here. Even if we want to turn the acme plugin off, we will append it every time to the end. But of course, we don’t want that. So what we may consider, to use the deactivation hook to cure the issue. We can set a variable what controls if the plugin is getting deactivated or not and make a check in our sort function. Let’s see the whole code:

//acme-gateway/acme-gateway.php

$isActive = true;

add_filter('pre_update_option_active_plugins', 'sort_plugins');
function sort_plugins($plugins)
{
    if ($isActive) {
        unset($plugins[array_search('acme-gateway/acme-gateway.php', $plugins)]);
        $plugins[] ='acme-gateway/acme-gateway.php';
    }

    return $plugins;
}

register_deactivation_hook(__FILE__, 'deactivate');
function deactivate()
{
    $isActive = false;
}

What we do here is nothing more, just when the deactivation triggered we turn the $isActive variable false and we don’t run the sorting. Of course, when the plugin is turned off, none of this code will run.

When we turn the plugin on, the $isActive is true automatically, so we sort the plugins how we want.

Summary

This is a nice and clean way to make sure your dependencies are loaded earlier than your theme or plugin. Since you don’t have to check if some functions, classes or constants are existing anymore, you can focus to keep your plugin cleaner and neater.