Skip to content

Instantly share code, notes, and snippets.

@KevinBatdorf
Last active June 1, 2022 17:57
Show Gist options
  • Save KevinBatdorf/ec4ca0fc7bc2c9c7192a38ee3dcf478b to your computer and use it in GitHub Desktop.
Save KevinBatdorf/ec4ca0fc7bc2c9c7192a38ee3dcf478b to your computer and use it in GitHub Desktop.
WordPress REST API install and activate by slug
// You need to set up `window.myPlugin.nonce` and `window.myPlugin.wpRoot` in PHP
/*
\wp_add_inline_script('script-name',
'window.myPlugin = ' . wp_json_encode([
'wpRoot' => \esc_url_raw(\rest_url()),
'nonce' => \wp_create_nonce('wp_rest')
]);
);
*/
export const installPlugin = async (slug) => {
// Fail silently if no slug is provided
if (!slug) return
const headers = {
'Content-type': 'application/json',
'X-WP-Nonce': window.myPlugin.nonce,
}
const url = `${window.myPlugin.wpRoot}wp/v2/plugins`
const response = await fetch(url, {
method: 'POST',
headers,
body: JSON.stringify({ slug, status: 'active' }),
})
if (response.status >= 200 && response.status < 300) {
return await response.json()
}
// The above could fail if the plugin is already installed
// But we at least want to try and activate it if that's the case
return await activatePlugin(slug)
}
export const activatePlugin = async (slug) => {
const headers = {
'Content-type': 'application/json',
'X-WP-Nonce': window.myPlugin.nonce,
}
const endpoint = `${window.myPlugin.wpRoot}wp/v2/plugins`
const response = await fetch(`${endpoint}?search=${slug}`, { headers })
const plugin = (await response.json())?.[0]?.plugin
const response2 = await fetch(`${endpoint}/${plugin}`, {
method: 'POST',
headers,
body: JSON.stringify({ status: 'active' }),
})
return await response2.json()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment