Last Updated: September 27, 2021
· cub3

Fixing Wordpress Comments

"The default Wordpress comments system is awful when it comes to handling errors, you can easily fix this issue with some simple AJAX."

On the back of the very many articles out there that help with AJAX'ifying your comments I decided to write this mini script and have released it as a plugin here >

If you're itching to know how it works, as I said its pretty simple...

First we setup our actions to load jQuery (if it dosent exist) and a nice javascript file in another location:

add_action('wp_print_scripts', 'google_jquery');
add_action('init', 'ajaxcomments_load_js', 10);

function ajaxcomments_load_js(){
        wp_enqueue_script('ajaxcomments', plugins_url('silk-ajax-comments/ajaxcomments.js'), array(), false, true);

function google_jquery() {
    if ( ! jQuery ) {
        wp_register_script('jquery',(""), false);

Then we build the PHP handler that listens for the comment button press, checks the post data and feeds back our AJAX

add_action('comment_post', 'ajaxify_comments',20, 2);
function ajaxify_comments($comment_ID, $comment_status){
    if(!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest'){
            case "0":
            case "1": //Approved comment
            echo "success";
            $commentdata =& get_comment($comment_ID, ARRAY_A);
            $post =& get_post($commentdata['comment_post_ID']);
            wp_notify_postauthor($comment_ID, $commentdata['comment_type']);
            echo "error";

Ok now the PHP is set... lets run our ajaxcomments.js file that we loaded before (the comments should explain the rest)

if (typeof jQuery != 'undefined') {

var commentform=$('#commentform'); // find the comment form
commentform.prepend('<div id="comment-status" ></div>'); // add info panel before the form to provide feedback or errors
var statusdiv=$('#comment-status'); // define the infopanel

//serialize and store form data in a variable
var formdata=commentform.serialize();
//Add a status message
//Extract action URL from commentform
var formurl=commentform.attr('action');
//Post Form with data
type: 'post',
url: formurl,
data: formdata,
error: function(XMLHttpRequest, textStatus, errorThrown){
statusdiv.html('<p class="wdpajax-error" >You might have left one of the fields blank, or be posting too quickly</p>');
success: function(data, textStatus){
statusdiv.html('<p class="ajax-success" >Thanks for your comment. We appreciate your response.</p>');
statusdiv.html('<p class="ajax-error" >Please wait a while before posting your next comment</p>');
return false;



And there we have it, as I said, not very revolutionary but simple and effective.

Have a fresh tip? Share with Coderwall community!

Post a tip