How to work out the current state of a plugin

It’s a rare instance where you need to know, from your own code, the state of a plugin but, for instance, this may be something particularly relevant to a theme.

The usual way is to use the PHP command functions_exists to check whether a specific function is present. Of course, hard-coding this is probably not the best idea as function names change. Instead the WordPress function is_plugin_active is a better solution and you only need to specify the (non-changing) plugin slug for this to work.

Now, this will tell you if the plugin is active but what if you also want to know if it’s installed or not?

Here you can use get_plugins. Specify a plugin directory and it will tell if the plugin is installed or not. Combine that with the previous function and you can tell 2 states – whether a plugin is installed and whether it’s active.

All of this can be combined, as I’ve done here into a simple routine that you can call at will…

<?php
function check_plugin_status( $plugin_dir, $plugin_name = '' ) {
if ( '' == $plugin_name ) { $plugin_name = $plugin_dir . '.php'; }
if ( is_plugin_active( $plugin_dir . '/' . $plugin_name ) ) {
$status = 2;
} else {
$plugins = get_plugins( '/' . $plugin_dir );
if ( $plugins ) {
$status = 1;
} else {
$status = 0;
}
}
return $status;
}
?>

There are two input parameters – the plugin directory name and the name. The second doesn’t have to be specified if they’re both the same. It will return a value of either 0, 1 or 2. 0=not installed, 1=installed but not active and 2 = installed and active.

So, to check my plugin YouTube Embed you’d call check_plugin_status( 'youtube-embed' ) – I’m using just one parameter as the plugin folder and name are the same.

Talk to me!

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Discover more from David Artiss

Subscribe now to keep reading and get access to the full archive.

Continue reading