WordPress AJAX Comments

By  on  

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?!

Recent Features

  • By
    Write Simple, Elegant and Maintainable Media Queries with Sass

    I spent a few months experimenting with different approaches for writing simple, elegant and maintainable media queries with Sass. Each solution had something that I really liked, but I couldn't find one that covered everything I needed to do, so I ventured into creating my...

  • By
    I’m an Impostor

    This is the hardest thing I've ever had to write, much less admit to myself.  I've written resignation letters from jobs I've loved, I've ended relationships, I've failed at a host of tasks, and let myself down in my life.  All of those feelings were very...

Incredible Demos

Discussion

  1. That’s a great script.
    Thanks for sharing!
    (btw, im testing your ajax-comment right now.)

  2. chrismccoy

    no actual js code to hook into?

    • There are too many considerations; levels of nesting, comment format, which JS framework, etc. I’d never please anyone.

  3. nice

    This is great! :)

  4. Great tutorial David. Thanks.

  5. It’s good tutorial!

  6. Hello david. if i add this code snippet my comments gonna use ajax posting ? rhanks.

    • You’ll need to code your client side handlers; this will take care of the server side.

  7. Matth

    I cannot tell if this displays the new comment via ajax? Or just submits it via ajax. Cuz that’s only half the battle.

    • Matth

      Dude, the 2nd to last sentence says “immediately outputs the comment HTML.” Can’t you read the article first before commenting? WTF!

  8. Matth

    Well, it works. But it breaks paged comments.

    Any suggestions for how to retain paged comments with this code?

    • Matth

      Yes, I seem to be smoking crack. Paged commenting is now working fine again, even with this function in place.
      David, please ban me from your site. Sigh.

      Thanks for the amazing code!

  9. Alex

    Nice!

  10. sei

    where i past the last code please ?

    add_action('comment_post', 'ajaxComment', 20, 2);
    

    Ty :)

  11. Cool

  12. Wow!

  13. So does this work?
    Looks like it does :)

  14. farzad

    where should I paste the code?

  15. Nice! What do you think about the following. Is it possible? Make Mr. WordPress show on first page not only one comment after it splits the page for achieving the ‘X’ nr of comments but all of them and thus making wp insert one by one from the bottom onto the next page. Hope I am clear enough. I am asking and wondering about this because anyone that I’ve asked told me it can’t be done. Cheers!

    • Done it. Nvm!

  16. Dan Martin

    Sweet!

  17. Hi David! Thanks for the fully explained code :)

  18. Kaki

    Ajax comments rule! Thanks

  19. Kaki

    Boom, comment in

  20. Hi David,

    this is very interesting, but what do you need to do on the client/HTML/JavaScript side – how do you make the comment submission happen over AJAX/XmlHttpRequest rather than a full page postback/refresh? That’s not apparent from the source code of this page.

    Cheers,
    Rick

    • I didn’t include the JavaScript piece because some people prefer jQuery, some people prefer MooTools, Dojo, YUI, etc. Additionally, some blogs use nested comments of variable level. It’s best that the individual blogger create JS for themselves.

  21. Hi and thanks for sharing !

    Shouldn’t all ajax calls in WordPress be made like :

    add_action('wp_ajax_functionName', 'functionName');
    add_action('wp_ajax_nopriv_functionName', 'functionName');  
    
    • Yes, but not in this case. Requesting directly wp-post-comment.php helps with not rebuilding the whole process of posting a comment, in which a lot is involved.

  22. Hi David,

    I’m thinking of AJAXifying the displayed comments too so that the page loads even faster, is it a good idea ?

    • I’ve thought of doing that in the past, but never pulled the trigger. I may do so in my next redesign.

  23. The scipt not working for me on Ifeature theme.
    I send the comment and page is reload:S

  24. Ajax is the King … We rule. Thanks.

  25. mark toce

    Any idea how I can implement this if the comment was made when the post is being pulled into a modal box? Thanks for any thoughts!!!

  26. abatu

    Thank you,But not working for me!!!
    Wordpress v 3.6.1

  27. Henry

    Thanks David, this was helpful – comments are front end so ‘ajaxifying’ them makes sense

  28. Do you use die() to output a HTML code? Is it serious?
    Why don’t you do
    print $commentContent;
    After you can cut the execution, but I think only if wordpress doesn’t provide a wrapper for ajax requests.

  29. Mazsola

    What about comments respond via ajax?

  30. Thanks for sharing David! Creating elements using ajax can be very beneficial to the overall user experience on your site. Comments or chat is really fun to implement with ajax..

  31. Best tutorial i found on web. Simple and effective. I wanted to comment to see if you implemented too :D

    • One more question. I see that after I submit my comment it automatically appears on the comment section but on my page after implementing the code it doesn’t appear. I have to refresh the page for the comment to appear.

    • This post covers on the PHP side, not the JavaScript side. Since so many people use their own JS frameworks, I decided not to tackle that.

  32. josh

    Thanks!

  33. Thanks for sharing!! Testing ajax comments =D

  34. Rado

    Thanks for sharing, I’ll hope this works for me

  35. Johnny

    Thanks, I’m not sure whether it’s working fine in the ajax loaded content.

  36. Tim Bunch

    wp_notify_postauthor appears to be defunct now. It was depreciated in 3.8
    https://codex.wordpress.org/Function_Reference/wp_notify_postauthor

    • Actually it looks like only the second argument is deprecated, not the entire function. You only need $comment_ID as the argument now: wp_notify_postauthor( $comment_ID )

  37. Nimi

    Testing :P Time to write some jQuery AJAX then.

  38. Paul

    Can you do it with raw AJAX without jquery?

  39. Drappa

    Is wp_notify_postauthor still relevant to this method ?

Wrap your code in <pre class="{language}"></pre> tags, link to a GitHub gist, JSFiddle fiddle, or CodePen pen to embed!