Skip to content

Instantly share code, notes, and snippets.

@gonzalesc
Created February 28, 2025 07:32
Show Gist options
  • Save gonzalesc/ca253a968349da8ef478ba9765722ddd to your computer and use it in GitHub Desktop.
Save gonzalesc/ca253a968349da8ef478ba9765722ddd to your computer and use it in GitHub Desktop.
Create custom endpoint to WordPress
<?php
/**
* Create custom RestAPI
* @link http://wpplugins.local/wp-json/letsgo/v1/activatePlugin
* @return void
*/
add_action( 'rest_api_init', function (): void {
register_rest_route(
'letsgo/v1', '/activatePlugin', [
'methods' => 'POST',
'callback' => 'activatePlugin',
'permission_callback' => function () {
return current_user_can( 'manage_options' );
},
]
);
});
/**
* Activate plugin
* @param WP_REST_Request $request
* @return WP_REST_Response
*/
function activatePlugin( WP_REST_Request $request ): WP_REST_Response {
$plugin = $request->get_param('plugin');
$result = processActivatePlugin( $plugin );
$response = new WP_REST_Response( $result );
if ( $result['success'] ) {
$response->set_status( 200 );
} else {
$response->set_status( 400 );
}
return $response;
}
/**
* Process activate plugin
* @param string $plugin
* @return array
*/
function processActivatePlugin( string $plugin ) : array {
if ( empty( $plugin ) ) {
return [
'success' => false,
'message' => esc_html__( 'Please enter a valid plugin slug', 'letsgo' ),
];
}
$result = activate_plugin( $plugin );
if ( is_wp_error( $result ) ) {
return [
'success' => false,
'message' => $result->get_error_message(),
];
}
return [
'success' => true,
'message' => sprintf( esc_html__( 'Plugin activated: %s', 'letsgo' ), $plugin ),
];
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment