Better ajax handler for WordPress – Super fast ajax

Ernest Marcinko jQuery, Tutorials, Wordpress 1 Comment

Raz Ohad made an article about faster ajax requests in WordPress, which I'm currently using in my plugins and let me tell you, it's working very well.

Do you want to cut your ajax requests response time to half? Here is what you do:

Create a php file

Yep. Create a php file for the handler in your template/plugin anywhere you want. Then put this in there:

    //mimic the actuall admin-ajax
    define('DOING_AJAX', true);

    if (!isset( $_POST['action']))

    //make sure you update this line 
    //to the relative location of the wp-load.php

    //Typical headers
    header('Content-Type: text/html');

    //Disable caching
    header('Cache-Control: no-cache');
    header('Pragma: no-cache');

    $action = esc_attr(trim($_POST['action']));

    //A bit of security
    $allowed_actions = array(

    //For logged in users
    add_action('SOMETEXT_custom_action1', 'handler_fun1');
    add_action('SOMETEXT_custom_action2', 'handler_fun1');

    //For guests
    add_action('SOMETEXT_nopriv_custom_action2', 'handler_fun2');
    add_action('SOMETEXT_nopriv_custom_action1', 'handler_fun1');

    if(in_array($action, $allowed_actions)) {
    } else {


As you can see it's simple. There is a minimal security check as well. Don't forget to edit the “SOMETEXT” for something unique.

Using the custom handler

For better access you should localize the script that you are planning to make the ajax requests to this file:

wp_localize_script( 'some-script', 'some_variable', array( 'customajax' => plugins_url('my_custom_ajax.php' , __FILE__) ) );

Then, all you need to do is make the ajax request:

var data = {
  action: 'custom_action1',
  something: 'something'
var x = $.post(some_variable.customajax, data, function(response) {

That's it!

Ernest Marcinko

WordPress developer, javascript enthusiast, photoshop clicker and the founder of

Stay connected

Related Posts
Filter by
Post Page
Blog Commercial Plugins Wordpress Developer Notes Tutorials jQuery Wordpress Free Plugins
Sort by

Comments 1

Leave a Reply

Your email address will not be published. Required fields are marked *