Better ajax handler for WordPress – Super fast ajax

Ernest Marcinko jQuery, Tutorials, Wordpress 2 Comments

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:

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

    if (!isset( $_POST['action']))
        die('-1');

    //make sure you update this line 
    //to the relative location of the wp-load.php
    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(trim($_POST['action']));

    //A bit of security
    $allowed_actions = array(
        'custom_action1',
        'custom_action2'
    );

    //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)) {
        if(is_user_logged_in())
            do_action('SOMETEXT_'.$action);
        else
            do_action('SOMETEXT_nopriv_'.$action);
    } else {
        die('-1');
    } 

?>

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) {
    console.log(response);
});

That’s it!

Comments 2

Leave a Reply

Your email address will not be published.