WordPress install / activate plugin using WP API and JavaScript

Install plugin function:

const installPlugin = ( slug, successCb, errorCb ) => {
	apiFetch( {
		path: '/wp/v2/plugins',
		method: 'POST',
		data: {
			slug,
			status: 'active',
		},
	} ).then( function( res ) {
		successCb( res );
	} ).catch( function( res ) {
		errorCb( res );
	} );
};

Uses:

installPlugin( 'contact-form-7', () => {
				window.location.reload();
			}, () => {
				$this.html( 'Error in action. Refresh page to try again.' );
			} );

Activate plugin function.

const activatePlugin = ( path, successCb, errorCb ) => {
	apiFetch( {
		path: `/wp/v2/plugins/${ path }`,
		method: 'POST',
		data: {
			status: 'active',
		},
	} ).then( function( res ) {
		successCb( res );
	} ).catch( function( res ) {
		errorCb( res );
	} );
};

Uses:

activatePlugin( `contact-form-7/wp-contact-form-7`, () => {
				window.location.reload();
			}, () => {
				$this.html( 'Error in action. Refresh page to try again.' );
			} );


Comments

Leave a Reply

Your email address will not be published. Required fields are marked *