Conditional content loading in WordPress with AJAX, Part 3 – The PHP Response

This is the third and final step in our rambling exploration of “lazy loading” content within WordPress using AJAX. Part 1 (the Setup) is here, and Part 2 (the Javascript) is here.

We return to the functions.php file for our theme, and start coding immediately after the two “do_action” functions that we added in Part 1.

First, we add two actions for this specific AJAX request, one for general users and another for users who are logged in.

// if both logged in and not logged in users can send this AJAX request,
// add both of these actions, otherwise add only the appropriate one
add_action( 'wp_ajax_nopriv_gallery-large', 'gallery_large' );
add_action( 'wp_ajax_gallery-large', 'gallery_large' );

The first argument for each action (that begins with “wp_ajax”) ends with the action name that we chose in our Javascript in Part 2:

  action : 'gallery-large',
  postID : $(this).attr('id')
function( response ) {

This action name needs to be unique for each AJAX call that you’re going to make for the site.

The second argument, “gallery_large” (notice the underscore separating the words instead of a hyphen), will be the name of a php function that we’re about to create. It also needs to be a unique name for each AJAX request, so I keep them essentially identical.

Then we write the function to receive the request and send back the response:

function gallery_large() {
  // get the submitted parameters
  $postID = $_POST['postID'];

  // response output from the get_slideshowTEST() function
  get_gallery_large( $postID, 'large' );

  // IMPORTANT: don't forget to "exit"
} // end myajax_submit()

There are three parts to this function.
First, any data we need to get from the Javascript request comes in with the $_POST variable. In this case, we assign the ‘postID’ value to a new PHP variable. Second, we call another function that we’re about to write that will query the database and generate the markup. The function has two arguments: the size of the image we want to load, and the $postID variable. Third, we exit to tell the server that we’re all done.

Next, we start the function that writes the markup:

function get_gallery_large( $postID, $size ) {	

We discussed two cases for the Javascript in Part 2: one where we want to use our AJAX data to completely replace the non-Javascript markup, and another where we just want to insert an image into each list item in the original markup.

In the first case, we would fill this new function with an entirely new loop using WP_Query.

In the second case, we can just grab and echo the featured image for each individual item:

function get_gallery_large( $postID, $size ) {	
  echo get_the_post_thumbnail( $postID, $size );

Either way, this second function is our end point. Anything returned or echoed out of this function is what will get sent back to our Javascript and added to our final markup with jQuery.