Skip to content

Instantly share code, notes, and snippets.

@fgilio
Forked from thomasgriffin/api-helper.php
Created October 5, 2015 00:25
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save fgilio/9f1b48a68d028e0ebc5a to your computer and use it in GitHub Desktop.
Save fgilio/9f1b48a68d028e0ebc5a 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.
<?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