Skip to content

Instantly share code, notes, and snippets.

@chrisakelley
Last active February 18, 2019 10:57
Show Gist options
  • Save chrisakelley/516d0702e0d055296faa5d83d598fc35 to your computer and use it in GitHub Desktop.
Save chrisakelley/516d0702e0d055296faa5d83d598fc35 to your computer and use it in GitHub Desktop.
<?php
/**
* Plugin Name: Offload API Helper
* Plugin URI: iwritecode.blog
* Description: Offload plugins during API requests to reduce overhead.
* Author: Chris Kelley
* Author URI: iwritecode.blog
* Version: 1.0.0
*/
$request_uri = parse_url( $_SERVER['REQUEST_URI'], PHP_URL_PATH );
$is_json_request = strpos( $request_uri, 'wp-json' );
// add filter in json requests only
// this assumes we dont have a post with 'wp-json' in the slug.
if( false !== $is_json_request ){
add_filter( 'option_active_plugins', 'prefix_offload_plugins' );
}
function prefix_offload_plugins( $plugins ) {
// You can use this to offload by route.
global $request_uri;
$unnecessary_plugins = [];//or array() if on old php.
$unnecessary_plugins[] = 'yourplugin/yourplugin_slug.php';
foreach ( $unnecessary_plugins as $plugin ) {
$key = array_search( $plugin, $plugins );
if( false !== $key ){
unset( $plugins[$key] );
}
}
return $plugins;
}
@cabrerahector
Copy link

A quick heads-up for anyone reading this: strpos() returns the position of the substring when found (0, 1, etc) or FALSE if not found.

This doesn't get executed:

if( true === $is_json_request ){
	add_filter( 'option_active_plugins', 'prefix_offload_plugins' );
}

This works:

if( false !== $is_json_request ){
	add_filter( 'option_active_plugins', 'prefix_offload_plugins' );
}

@chrisakelley
Copy link
Author

@cabrerahector I updated it, sorry I did it super quick as an example.

@cabrerahector
Copy link

No need to apologize. You already are doing enough by sharing this with others. I just pointed out a minor bug in your code :)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment