I’ve been recently playing with implementing AJAX into WordPress. I know there is many plugins available but I wanted to make it on my own.
In articles regarding to AJAXified WordPress most people recommend using admin-ajax.php to process AJAX requests. My first idea how to make it was to simply create custom get_header() and get_footer()
1st way
// Boolean function ?ajax=true
function is_ajax () {
if($_REQUEST['ajax']) {
return true;
} else {
return false;
}
}
function ajax_get_header () {
if(is_ajax()) {
get_header('ajax');
/* Insert header-ajax.php which
includes only google analytics tracking code and some minor stuff */
return true;
} else {
get_header();
// Standard header
return true;
}
}
/* Function ajax_get_footer() pretty much the same */
Then, page templates would look like
<?php ajax_get_header(); ?>
<!-- Content -->
<?php ajax_get_footer(); ?>
And making ajax calls the standard way, of course.
This method looks for me simple and clean.
On the other hand, many people recommend using built-in function, by creating a hook to catch AJAX calls.
2nd way
function process_ajax(){
/* Show the page or whatever */
}
add_action('wp_ajax_nopriv_ajax', 'process_ajax');
add_action('wp_ajax_ajax', 'process_ajax');
And pointing AJAX calls to admin-ajax.php
Which one to use?
I have tried both these methods and discovered that the first way is loading remarkably faster then the latter one. In same conditions the 1st way (ajax_get_header) took approximately 400ms to load a page (almost no content) and the 2nd way (admin-ajax.php) about 800ms. I dont know why, both ways load WP core and do thing almost the same.
So, I am asking you, is there a serious reason to make AJAX calls through admin-ajax.php? Is it nessesary? And why it takes more time to process a call through the recommended way?
Your 1st way is always going to be faster than WordPress’s own ajax since admin-ajax.php takes care of lot of other things like core admin hooks and other function calls which in turn makes the whole ajax call pretty huge.
in the first way, You are not bothering about anything else other than your own functions and output. That increases the performance.
There is no hard and fast rule what to use, The first way you can do things faster but they won’t be hookable with wordpress’s core admin functions which may be a disadvantage for some purpose.
See admin-ajax.php