Friday, July 6, 2012

How to Force 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.

No comments:

Post a Comment