Last active
September 5, 2024 01:50
-
-
Save thomasgriffin/86a430c4a7cab0de1b3c to your computer and use it in GitHub Desktop.
API Helper to be used during API requests. Should be used as a must-use plugin in WordPress.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/** | |
* Plugin Name: TGM API Helper | |
* Plugin URI: https://thomasgriffin.io | |
* Description: Whitelists the plugins to be loaded during API requests to reduce overhead. | |
* Author: Thomas Griffin | |
* Author URI: https://thomasgriffin.io | |
* Version: 1.0.0 | |
*/ | |
// Make sure we can target a valid URI endpoint. | |
if ( ! isset( $_SERVER['REQUEST_URI'] ) ) { | |
return; | |
} | |
// Make sure that the endpoint being requested matches a valid API endpoint. | |
if ( strpos( stripslashes( $_SERVER['REQUEST_URI'] ), '/api/v1/' ) === false ) { | |
return; | |
} | |
// Define a constant that we can make use of in any API plugins we create. | |
define( 'TGM_API_REQUEST', true ); | |
// Now that we know this is an API request, let's filter available plugins. | |
add_filter( 'pre_option_active_plugins', 'tgm_whitelist_active_plugins' ); | |
/** | |
* Filters the plugins that should be loaded during this request to reduce overhead. | |
* | |
* since 1.0.0 | |
* | |
* @param array $plugins The active plugins to be loaded in the request. | |
* @retun array $whitelist Whitelisted plugins that should only be loaded during the request. | |
*/ | |
function tgm_whitelist_active_plugins( $plugins ) { | |
// This is my base API plugin to handle all API routes. I want this loaded before everything else. | |
$whitelist = array( | |
'api-routes/api-routes.php' | |
); | |
// You can easily conditionally load plugins based on the URI path. Here is an example for an API endpoint called "update". | |
if ( strpos( stripslashes( $_SERVER['REQUEST_URI'] ), '/api/v1/update/' ) !== false ) { | |
$whitelist[] = 'api-update-helper/api-update-helper.php'; | |
} | |
// Finally, we can load any API plugin that depends on all the others last. | |
$whitelist[] = 'api-depends/api-depends.php'; | |
// Return the whitelist instead of the default plugins. | |
return $whitelist; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment