Create your own admin-ajax.php type handler
The admin-ajax.php handler is a bit heavy, especially if you’re using AJAX on every page load. I am working on a project now that has multiple caching mechanisms and the only way to update the original server is to POST to the server. Since admin-ajax.php invokes the admin_init hook, it loads a lot of unnecessary items for AJAX call. Here’s the light-weight version of admin-ajax that I created to handle my plugin’s AJAX calls. Save this as request.php in your plugin folder.
define('DOING_AJAX', true);
if (!isset( $_POST['action']))
die('-1');
//relative to where your plugin is located
require_once('../../../../../wp-load.php');
//Typical headers
header('Content-Type: text/html');
send_nosniff_header();
//Disable caching
header('Cache-Control: no-cache');
header('Pragma: no-cache');
$action = esc_attr($_POST['action']);
//A bit of security
$allowed_actions = array(
'action_1',
'action_2',
'action_3'
);
if(in_array($action, $allowed_actions)){
if(is_user_logged_in())
do_action('plugin_name_ajax_'.$action);
else
do_action('plugin_name_ajax_nopriv_'.$action);
}
else{
die('-1');
}
To use this you obviously would hook into these actions doing the following:
//For logged in users
add_action('plugin_name_ajax_action_name', 'function_callback_name');
//For logged out users
add_action('plugin_name_ajax_nopriv_action_name', 'function_callback_name');
You will need to craft your AJAX request as follows:
jQuery(document).ready(function($){
var data={
action:'action_name',
otherVar: varValue
};
$.post('http://url/to/your/plugin/request.php', data, function(response){
alert(response);
});
});
Two notes:
A) You can set the URl already when using
wp_localize_script().B) You maybe want to run an
array_map( 'trim', $_POST );before using. You know, because …Good points!