Simple Way to Get Plugin Status in WordPress

Active plugin volcano.

I have previously written on how to determine if a widget is active. This is helpful for widgets, but not for plugins.

WordPress has a couple of different functions that help you determine plugin status. They are both located in wp-includes/plugin.php

  • validate_plugin() spits out an error if the plugin file does not  exist or has an invalid header. This lets you know that the file is there.
  • is_plugin_inactive() lets you know if the plugin is not active (using the is_plugin_active() function)

A function to get plugin status

Using these two functions, I put together a one-size-fits-all function get_plugin_status().

The function returns 1 if the plugin is active; 2 if the plugin is inactive; 0 if the plugin is not installed.

/**
 * Check the status of a plugin.
 *
 * @param string $location Base plugin path from plugins directory.
 * @return int 1 if active; 2 if inactive; 0 if not installed
 */
function get_plugin_status($location = '') {

	if(is_plugin_active($location)) {
		return 1;
	}

	if(!file_exists(trailingslashit(WP_PLUGIN_DIR). $location)) {
		return false;
	}

	if(is_plugin_inactive($location)) {
		return 2;
	}
}

Usage example

$status = get_plugin_status('akismet/akismet.php');
switch($status) {
	case 1: echo 'Akismet is active.'; break;
	case 2: echo 'Akismet is installed but inactive.'; break;
	case 0: echo 'Akismet is not installed or active.'; break;
}

Update: validate_plugin was slow…

I changed from using validate_plugin because I was experiencing 300 milliseconds of processing time. This updated method is much faster.

This entry was posted in Web Development, WordPress and tagged , , , , . Bookmark the permalink.