While developing a theme or a plugin we sometimes need to check if a certain third-party plugin is available for use. Here you’ll learn a simple way to detect not only if the plugin is active in a single site but also if it’s network-wide enabled.
Overview
WordPress stores the list of active plugins in different options in database whether they are plugins enabled throughout the entire network or plugins enabled in a single site of the network:
- active_sitewide_plugins: contains the plugins network-wide enabled plugins
- active_plugins: contains the plugins enabled in the current site of the network.
Function Definition
With this, we can code something like this to check if a certain plugin is enabled in network or single site:
if ( ! function_exists( 'elio_is_plugin_active' ) ) {
/**
* Checks if a certain plugin is active
* @param string $plugin Plugin folder and main file to check.
* @return bool
*/
function elio_is_plugin_active( $plugin = '' ) {
$network_active = false;
if ( is_multisite() ) {
$plugins = get_site_option( 'active_sitewide_plugins' );
if ( isset( $plugins[$plugin] ) )
$network_active = true;
}
return in_array( $plugin, get_option( 'active_plugins' ) ) || $network_active;
}
}
As an example, we’ll check if the plugin Jetpack is active. You can now use the function we wrote like this, passing as parameter the plugin root directory, jetpack, and the plugin main file, jetpack.php:
<?php
if ( elio_is_plugin_active( 'jetpack/jetpack.php' ) ) {
// do something if Jetpack is active in network or single site
}
?>
Let’s see another example with WooCommerce plugin:
<?php
if ( tr_is_plugin_active( 'woocommerce/woocommerce.php' ) ) {
// do something if WooCommerce is active in network or single site
}
?>
With this simple method you’ll be safe when adding functionality that is meant to work with a particular plugin since you’ll always be able to check if the plugin is enabled.