StackExchange Community,
I am working on some Block Editor formats and blocks and would like to add a check to see if a certain plugin is installed. This would be specific to the back-end admin area of WordPress. For example something along the lines of:
if ( isPluginActive('plugin-name') ) {
console.log('Plugin is active.')
}
I am aware that I could localize the data from PHP to my script but it would be much better to use any built in functions or packages if it is available. I did come across the getPlugins() method from the plugins package but this seems to refer to gutenberg plugins rather than WordPress plugins.
Update:
I attempted to use apiFetch and was able to retrieve a list of installed plugins along with the status of each.
const isPluginActive = () => {
apiFetch( { path: '/wp/v2/plugins' } ).then( ( plugins ) => {
plugins.forEach( ( plugin ) => {
const name = plugin.plugin
const status = plugin.status
if ( name === 'plugin-name/plugin-name' && status === 'active') {
return true
}
})
})
}
However, I am unsure how to use this to return a boolean response as a variable or function which I can use on my conditionals. It currently returns undefined.
Answers:
Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.
Method 1
None of Gutenberg’s data stores expose selectors for this purpose yet, to the best of my knowledge. If any did, I would have expected to find it on core. If and when the Gutenberg experience expands to the plugin management screen I reckon we’ll see such a thing implemented.
For the time being, if the relevant users have the activate_plugins capability, you could acquire this data from the Plugins REST API endpoint using the @wordpress/api-fetch package:
import apiFetch from '@wordpress/api-fetch';
// ...
const plugins = await apiFetch( { path: '/wp/v2/plugins' } );
The objects produced by the request will have the fields described by the endpoint’s schema, including the relative path to the main file, the name, version number, and active/inactive status.
It is possible to modify the permissions check callback for a core REST endpoint in order to expose this functionality to more users – but it’s not very direct, and generally inadvisable. Creating a new endpoint or controller would probably be a better solution if you need to customize it’s behavior.
All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0