Tell me more ×
WordPress Answers is a question and answer site for WordPress developers and administrators. It's 100% free, no registration required.

Is there any reason to use admin-ajax.php for ajax requests versus a custom page template?

I didn't know about admin-ajax.php until recently, so what I had been doing is creating a custom page template like this:

<?php
/**
 * Template Name: API
 */

if ( isset( $_GET['ajax_request'] ) ) {
// do stuff
}

And the ajax call would be to the URL http://mysite.com/api/, which is where I've published a blank page using my API page template. This seems to give me access to all my WordPress functions and spit out data.

However, recently I've read up on admin-ajax.php and understand another way to connect to the WordPress database is to call the URL http://mysite.com/wp-admin/admin-ajax.php and have functions like this:

add_action( 'wp_ajax_nopriv_action', 'my_do_stuff' );
add_action( 'wp_ajax_show_action', 'my_do_stuff' );

function my_do_stuff() {
// do stuff
}

Is it wrong to connect the first way? Does admin-ajax.php provide extra security or something? Thanks any input!

share|improve this question
BTW: if you want to make a api on your wordpress site and want a url that make sense as api request url. Then you can do some mod rewrite so http://site.com/api/ maps to http://site.com/wp-admin/admin-ajax.php – Sisir Jul 22 '12 at 20:38

1 Answer

up vote 5 down vote accepted

First, the obvious drawback to the first method is that it depends on your specific page, template, and permalink structure to all work correctly. Using admin-ajax.php will work correctly in any context, theme or plugin, where proper WordPress best practices are followed.

The less obvious drawback to the first method is that it uses more memory than doing WordPress-enabled AJAX calls, since the whole WordPress environment is loaded, as it's presumed that a front-end or admin page will be output.

The addition of NONCEs with admin-ajax.php provides easy, built-in security.

share|improve this answer
1  
To be fair, the entire WordPress environment + the admin area is loaded for admin-ajax.php as well. The only thing that gets skipped is the template loader. admin-ajax.php is still the correct way, of course. :) – chrisguitarguy Jul 22 '12 at 19:03

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.