I am building a dynamic Gutenberg block that needs to render differently according to active plugins. I know there is the PHP function is_plugin_active
. Is there an equivalent or a "workaround" to find it out from JavaScript? Or do I need to pass it to JS from PHP?
As Tony said you could use localization to pass data from PHP into your script.
Another way to go about it is to hook into the body_class filter hook and add custom CSS classes to it if one or more plugins are active:
/**
* Adds additional CSS classes to the body tag if a given plugin is active.
*
* @param array $classes An array of CSS classes that will be added to the body tag
* @return array $classes An array of CSS classes that will be added to the body tag
*/
function wp76641_active_plugins_body_classes($classes) {
include_once( ABSPATH . 'wp-admin/includes/plugin.php' );
if ( is_plugin_active('plugin-x-directory/plugin-x-file.php') ) {
$classes[] = 'plugin-x-is-active';
}
return $classes;
}
add_filter('body_class', 'wp76641_active_plugins_body_classes');
Then, in your JS you could do something like this:
if ( document.body.classList.contains('plugin-x-is-active') ) {
// Do your thing
}