WordPress and AJAX

Today I was working with the WordPress and AJAX combined for the first time. I was tasked with adding the ability to sort a specific categories posts by sub-category, author and post type (we had sub-types allowing us to separate these posts by the type of content inside, video and text).

AJAX wasn’t originally the plan, but as I developed the functionality I realized I had certain restrictions to observe – once a user has selected a filter (type, author or category) a user could select what type of post to view by author in a category. The original site that we’re upgrading was using javascript to allow users to filter by category and view author profiles, so that was my starting point.

I decided that I wanted to do it all in AJAX and gracefully degrade it for our 10% of non-javascript users. I had yet to work with WordPress and AJAX so it was kind of new to me, the documentation wasn’t as clear as it could have been but it made sense to me. To use AJAX with WordPress all I needed was some jQuery code to make the request, an action (function) to handle the request and a template file.

I started by writing the jQuery code, built my variables and sent the request to wp-admin/admin-ajax.php. Then defined the function in my themes functions.php file hooking into the wp_ajax_$action action. The function would respond back with a template file containing the loop code for the page after reprocessing the WP_Query.

It was amazingly simple once I looked at the source of wp-admin/admin-ajax.php and saw how I could hook in to process my own code.

The JavaScript code looked something like this:

var ajax_loader = function( page_num ){
	var page_val = page_num;
	var category_val = jQuery("#sort-controls select[name=category]").val();
	var url = "/wp-admin/admin-ajax.php";

	jQuery.get(
		url,
		{
			action: "mybrowser",
			category: category_val,
			page: page_val
		},
		function(data){
			jQuery("#browser").replaceWith(data);
		});
}

Don’t forget to load this using ajax_loader(1) where 1 is the page number. I created controllers to handle that.

The PHP function looked something like this:

function wp_ajax_mybrowser()
{
	global $is_ajax;
	$is_ajax = true;

	$category = esc_attr( $_GET['category'] );
	$page = esc_attr( $_GET['page'] );

	$args = wp_query_args();

	if( !empty( $category ) )
		$args['cat'] = $category;
	else
		$args['cat'] = 120;

	if( !empty( $page ) ):
		$args['paged'] = $page;
	else:
		$args['paged'] = 1;
	endif;

	$args['posts_per_page'] = 8;

	query_posts( $args );

	get_template_part( 'loop', 'browser' );
	die();
} // function

Which was hooked in using add_action( 'wp_ajax_mybrowser', array( &$this, 'wp_ajax_mybrowser' );

2 Responses to “WordPress and AJAX”

  1. Note that you should use ajaxurl instead of “/wp-admin/admin-ajax.php”;

    According to the codex:


    // since 2.8 ajaxurl is always defined in the admin header and points to admin-ajax.php
    jQuery.post(ajaxurl, data, function(response) {
    alert('Got this from the server: ' + response);
    });

    • Jay Fortner says:

      You’re right Joel. I forgot to mention this completely. It is true, that when in the admin section of WordPress there is a javascript variable known as ajaxurl however this variable is not set automatically on every front-end screen.

Leave a Reply

  • Follow Me On

    Follow w3prodigy on Twitter