Forcing a WordPress plugin to be loaded before all other plugins

When you activate a plugin via the WordPress admin panel it calls the action hook “activated_plugin“, which updates the “active_plugins” site option stored in the database to determine which plugins your site should load.

The option value is a serialized array of the active plugins saved in alphabetical order according to the plugin directory and file name, for example:

Array
(
	[0] => akismet/akismet.php
	[1] => example-plugin/index.php
)

You can however alter the order of the plugins in the array, which will in turn set the order in which the plugins are loaded by WordPress.

The first step towards adjusting the order is to add the following action to your plugin file, which is most likely to be /my-plugin/index.php or /my-plugin/my-plugin.php.

add_action( 'activated_plugin', 'my_plugin_load_first' );

Next you need to include the functionality to perform the actual re-ordering. The following function will fetch the existing list, check that your plugin is in the array and if so remove then append it to the beginning, before finally saving the altered list to the database.

function my_plugin_load_first()
{
	$path = str_replace( WP_PLUGIN_DIR . '/', '', __FILE__ );
	if ( $plugins = get_option( 'active_plugins' ) ) {
		if ( $key = array_search( $path, $plugins ) ) {
			array_splice( $plugins, $key, 1 );
			array_unshift( $plugins, $path );
			update_option( 'active_plugins', $plugins );
		}
	}
}

It should not be necessary for you to adjust anything specified here other than modifying the name of the function used to suit the namespace used by your plugin.

One final thing to consider is only adding this action when the dashboard or administration panels are being displayed, by making use of the is_admin() conditional tag.

Please note that modifying this option is not something I recommend people do unless absolutely necessary, and it my situation it proved to be very useful.

4 thoughts on “Forcing a WordPress plugin to be loaded before all other plugins

  1. This may surely prove helpful for those who write Plugin extensions for the Plugins. Like, we’ve NextGen Image Gallery Plugin and also several other plugins which hook into the NextGen actions and filters. Certainly, all these NextGen extensions will need to have NextGen loaded before these plugins are loaded so to make sure the functions which they’re calling are available to their Plugin classes.

  2. I know this thread is old, but just in case anyone else stumbles upon this seeking a solution I’ve found the best way to require another plugin is not to adjust the order in which they are loaded, but to use an include for the plugin file you need.

    Example:

    include_once plugin_dir_path(dirname(__FILE__)).’/pluginfolder/plugin.php';
    // now run code

Leave a Reply