Creating AJAX Functions in WordPress

AJAX Action Hooks

Adding an AJAX callback to WordPress 2.8+ is pretty simple – you just need to hook in the wp_ajax_(action) action for admin callbacks, and the wp_ajax_nopriv_(action) action for front-end callbacks. One caveat however is that the ajaxurl property (which holds the URL for admin-ajax.php where the AJAX call is submitted) is not automatically included. You will have to add it manually by adding admin_url( 'admin-ajax.php' ) to make it available on the front-end. The (action) in the callback matches up with the action: my_action that should be passed in your AJAX call, for example wp_ajax_my_action.

// process all my_action for admin only
add_action( 'wp_ajax_my_action', 'my_action_callback_function' );

// process my_action for the front-end too
admin_url( 'admin-ajax.php' );
add_action( 'wp_ajax_nopriv_my_action', 'my_action_callback_function' );

For versions of WordPress older than 2.8, add an action on init to handle the AJAX requests. When called the function will attempt to call do_action() for the key "wp_ajax_" + $_REQUEST['action'], so if the “action” in the $_REQUEST was “get_post” the resulting key would be “wp_ajax_get_post”. This effectively reproduces the functionality of the wp_ajax_nopriv_(action) action hook in WordPress 2.8+.

// process all wp_ajax_* calls
function core_add_ajax_hook() {
	/* Theme only, we already have the wp_ajax_ hook firing in wp-admin */
	if ( ! defined( 'WP_ADMIN' ) && isset( $_REQUEST['action'] ) ) {
		do_action( 'wp_ajax_' . $_REQUEST['action'] );
	}
}
add_action( 'init', 'core_add_ajax_hook' );

Now you are free to add as many wp_ajax_* functions as you would like. To continue with the example above, we will create a function for “wp_ajax_get_post”.

AJAX Callback Functions

This is the PHP function that handles your AJAX callback. Noted that it takes no arguments, and that you will have to grab the values submitted using $_GET, $_POST, or the more generic $_REQUEST (though not really recommended) depending on your HTTP type used.

// get a post by its post.ID
function wp_ajax_get_post_callback_function() {
	// default response
	$response = array( "success"=>false );

	/* get the 'post_id' from the $_REQUEST and sanitize, if post can be loaded
	   set success to true and assign post */
	$post_id = filter_input( INPUT_POST, 'post_id', FILTER_SANITIZE_NUMBER_INT );
	if ( $post_id && $post = get_post( $post_id, ARRAY_A ) ){
		$response = array( "success"=>true, "post"=>$post );
	}

	// set the content type and return json encode response, then exit
	header( 'Content-type: application/json' );
	die( json_encode( $response ) );
}
add_action( 'wp_ajax_get_post', 'wp_ajax_get_post_callback_function' );

jQuery AJAX Call

And now to call this AJAX method using jQuery.

$(document).ready(function(){
	// the post id to query
	var my_post_id = 123;

	// add a click event to our anchor link that will post the id and get back the post data.
	$('#anchor').on('click', function(){
		$.post(
			ajaxurl,
			{
				action: 'get_post', // the action to pass to the WordPress hook, and then do_action()
				post_id: my_post_id // the post id to query
			},
			success: function(response){
				if (response.success==true){
					alert('The post title is ' + response.post.post_title);
				}
			}
		);
	}
});

This can be triggered by clicking a link like the following.

<a href="#" id="anchor">Click Me</a>

You may also like...

Leave a Reply

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