Monday, October 21, 2013

WordPress AJAX Comments

There are many functionalities on the web that were just begging to be AJAXified.  Whether it be voting on a poll or simply commenting on a blog post, there's really no reason to reload an entire page for something so simple.  This blog has featured AJAX comments in WordPress for years, but only recently did I find the most optimized way to process those comments.  Here's how to handle the WordPress PHP side of AJAX comment systems.

The PHP

Add the following function with your theme's function.php file:
// Method to handle comment submission
function ajaxComment($comment_ID, $comment_status) {
 // If it's an AJAX-submitted comment
 if(isset($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest'){
  // Get the comment data
  $comment = get_comment($comment_ID);
  // Allow the email to the author to be sent
  wp_notify_postauthor($comment_ID, $comment->comment_type);
  // Get the comment HTML from my custom comment HTML function
  $commentContent = getCommentHTML($comment);
  // Kill the script, returning the comment HTML
  die($commentContent);
 }
}
The function above receives the new comment ID (the comment is already posted to the DB at this point) and comment_status, if you care to know it.  If the comment was submitted via AJAX, the comment metadata is retrieved, wp_notify_postauthor is called to send an email notification about the new comment to the author, and the last step is outputting the formatted comment HTML, which my formatComment function completes.  The last step is adding a WordPress actions to trigger the function above:
// Send all comment submissions through my "ajaxComment" method
add_action('comment_post', 'ajaxComment', 20, 2);
Now all new AJAX-submitted comments get filtered through the ajaxComment method, outputting just the specific comment HTML, allowing you to insert the comment content into the relevant parent OL/UL element on the client side.
In the past, I've allowed the entire page to load and that was....slow.  Very slow.  The method described above allows for easy PHP/AJAX comment handling, allows other relevenat comment processing methods (including emailing the author of the post), and immediately outputs the comment HTML.  Who thought it could be so easy?!