Create a gist now

Instantly share code, notes, and snippets.

This must-use plugin whitelists plugins that should be loaded during an admin-ajax.php request in WordPress.
<?php
/**
* Plugin Name: Custom admin-ajax.php Helper
* Plugin URI: https://thomasgriffin.io
* Description: Whitelists the plugins to be loaded during admin-ajax.php requests for performance.
* Author: Thomas Griffin
* Author URI: https://thomasgriffin.io
* Version: 1.0.0
*/
// Check against the request URI.
if ( ! isset( $_SERVER['REQUEST_URI'] ) ) {
return;
}
// If it does not match the admin-ajax.php route, do nothing.
if ( strpos( stripslashes( $_SERVER['REQUEST_URI'] ), 'admin-ajax.php' ) === false ) {
return;
}
// Ok, this is an admin-ajax.php request. Filter available plugins.
add_filter( 'pre_option_active_plugins', 'tgm_whitelist_admin_ajax_plugins' );
function tgm_whitelist_admin_ajax_plugins( $plugins ) {
// Only modify the ajax requests performed by our own plugin.
$action = isset( $_REQUEST['action'] ) ? stripslashes( $_REQUEST['action'] ) : false;
if ( ! $action ) {
return $plugins;
}
// For this example, we will target the heartbeat ajax request.
if ( 'heartbeat' !== $action ) {
return $plugins;
}
// Prevent any plugins from loading during the request.
$whitelist = array(
// my-custom-plugin/my-custom-plugin.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