Learn How to Add Ajax in WordPress Comment

By Our Bestseller: WordPress Themes

Adding comment feature on blogs is the great way to allow readers to contribute their opinion about your post. Moreover, you can also  improve readers experience by adding ajaxify functionality on comment section.

So, you need to ajaxify your WordPress site!

After reading this post you will get an absolute solution to add Ajax Commenting session on your WordPress site.

Ajaxify Functionality In WordPress Comment

When you submit a comment form in WordPress, then by default it reloads the complete page. But when you add Ajax functionality in the comment form of your WordPress theme, then no page reloads requires on submitting or updating the comments.

What is the need to Ajaxify WordPress Comment ?

Use of Ajax functionality in comment form is advantageous in many ways like-

  • Improves the usability of the comment form by validating and adding comments without page reload.
  • Gives faster response to users.
  • It reduce usage of server resource without loading a whole page on every comment submission.
  • Makes your WordPress website more efficient.

You might be thinking that WordPress already offers some best plugins like WordPress Ajaxify Comments to ajaxify WordPress comments then why one would need to do such tedious coding.

Let me justify the above one. You can customize the code as per your needs and add more functionality using jQuery. Moreover, you can use the code in any theme without dependency on any plugin.

Additionally, every plugin add a bit of complexity to your site. Installing too many plugins will slow down your site and affects its performance.

Therefore, you can easily implement ajax functionality on WordPress comment section by following below piece of code.

commenting in wordpress using ajax

JavaScript File : ajaxcomments.js

Create a new javascript file named, ajaxcomments.js and saved it under js folder of your WordPress theme. This file include codes for following functions- 

  • To find the comment form.
  • Add info panel before the form.
  • Serialize and store form data in a variable.
  • Add a status message.
  • Extract action URL from comment form.
  • Post formdata and url to function ajaxify_comments_jaya of function.php file
  • Output return from above function will catch and display in front end.


/** Author InkThemes ***/
jQuery('document').ready(function($){
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 info panel
var list ;
$('a.comment-reply-link').click(function(){
list = $(this).parent().parent().parent().attr('id');
});

commentform.submit(function(){
//serialize and store form data in a variable
var formdata=commentform.serialize();
//Add a status message
statusdiv.html('<p>Processing...</p>');
//Extract action URL from commentform
var formurl=commentform.attr('action');
//Post Form with data

$.ajax({
type: 'post',
url: formurl,
data: formdata,
error: function(XMLHttpRequest, textStatus, errorThrown)
{
statusdiv.html('<p class="ajax-error" >You might have left one of the fields blank, or be posting too quickly</p>');
},
success: function(data, textStatus){
if(data == "success" || textStatus == "success"){
statusdiv.html('<p class="ajax-success" >Thanks for your comment. We appreciate your response.</p>');
//alert(data);

if($("#commentsbox").has("ol.commentlist").length > 0){
if(list != null){
$('div.rounded').prepend(data);
}
else{
$('ol.commentlist').append(data);
}
}
else{
$("#commentsbox").find('div.post-info').prepend('<ol class="commentlist"> </ol>');
$('ol.commentlist').html(data);
}
}else{
statusdiv.html('<p class="ajax-error" >Please wait a while before posting your next comment</p>');
commentform.find('textarea[name=comment]').val('');
}
}
});
return false;
});
});

PHP File: function.php

 function.php is a ajax comment function file can be used to add features and extend the functionality of both the theme and the WordPress installation. 

You can found this file under the selected theme folder of your WordPress. So include below piece of code at the end of the function.php file.

Code includes following functions-

  • ajaxcomments_load_js() :

Include javascript file in the theme on page load.

  • ajaxify_comments_jaya() :

This is the basic function to implement ajaxify functionality which includes code to check comment status and notify admin for a new comment.

When the comment is submitted, user will get a success message. And without admin approval, comment will not be published in front end.

Code to create a div to show comment with an author gravatar image, author name, comment time, and reply option, similar as the below image.

make commenting easy using Ajax

When you kept the required fields empty then you will get an error message, same as the below image.

error message in comment form

 

Code :



<?php

// Include Ajaxscript - Add this code at the end of the function.php file of your selected WordPress theme.

/*
Ajaxify Comments -> hooks into your comment form and adds AJAX functionality - no page reloads required.
When the comment form is submitted, the code will sends the data to the WordPress backend without reloading the entire page.
You can customize this code according to your requirement.
Author: InkThemes
*/

add_action('init', 'ajaxcomments_load_js');

function ajaxcomments_load_js() {
//wp_enqueue_script('ajaxcomments', get_stylesheet_directory_uri().'js/ajaxcomments.js');

wp_enqueue_script('ajaxcomments', get_template_directory_uri() . "/js/ajaxcomments.js", array('jquery'));
}

function ajaxify_comments_jaya($comment_ID, $comment_status) {
if (!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') {
//If AJAX Request Then
switch ($comment_status) {
case '0':
//notify moderator of unapproved comment
wp_notify_moderator($comment_ID);
case '1': //Approved comment
echo "success";
$commentdata = &get_comment($comment_ID, ARRAY_A);
//print_r( $commentdata);
$permaurl = get_permalink( $post->ID );
$url = str_replace('http://', '/', $permaurl);

if($commentdata['comment_parent'] == 0){
$output = '<li class="comment byuser comment-author-admin bypostauthor odd alt thread-odd thread-alt depth-1" id="comment-' . $commentdata['comment_ID'] . '">
<div id="div-comment-' . $commentdata['comment_ID'] . '" class="comment-body">
<div class="comment-author vcard">'.
get_avatar($commentdata['comment_author_email'])
.'<cite class="fn">' . $commentdata['comment_author'] . '</cite> <span class="says">says:</span>
</div>

<div class="comment-meta commentmetadata"><a href="http://localhost/WordPress_Code/?p=1#comment-'. $commentdata['comment_ID'] .'">' .
get_comment_date( 'F j, Y \a\t g:i a', $commentdata['comment_ID']) .'</a>&nbsp;&nbsp;';
if ( is_user_logged_in() ){
$output .= '<a class="comment-edit-link" href="'. home_url() .'/wp-admin/comment.php?action=editcomment&amp;c='. $commentdata['comment_ID'] .'">
(Edit)</a>';
}
$output .= '</div>
<p>' . $commentdata['comment_content'] . '</p>
<div class="reply">
<a class="comment-reply-link" href="'. $url . '&amp;replytocom='. $commentdata['comment_ID'] .'#respond"
onclick="return addComment.moveForm(&quot;div-comment-'. $commentdata['comment_ID'] .'&quot;, &quot;'. $commentdata['comment_ID'] . '&quot;, &quot;respond&quot;, &quot;1&quot;)">Reply</a>
</div>
</div>
</li>' ;

echo $output;

}
else{

$output = '<ul class="children"> <li class="comment byuser comment-author-admin bypostauthor even depth-2" id="comment-' . $commentdata['comment_ID'] . '">
<div id="div-comment-' . $commentdata['comment_ID'] . '" class="comment-body">
<div class="comment-author vcard">'.
get_avatar($commentdata['comment_author_email'])
.'<cite class="fn">' . $commentdata['comment_author'] . '</cite> <span class="says">says:</span> </div>

<div class="comment-meta commentmetadata"><a href="http://localhost/WordPress_Code/?p=1#comment-'. $commentdata['comment_ID'] .'">' .
get_comment_date( 'F j, Y \a\t g:i a', $commentdata['comment_ID']) .'</a>&nbsp;&nbsp;';
if ( is_user_logged_in() ){
$output .= '<a class="comment-edit-link" href="'. home_url() .'/wp-admin/comment.php?action=editcomment&amp;c='. $commentdata['comment_ID'] .'">
(Edit)</a>';
}

$output .= '</div>
<p>' . $commentdata['comment_content'] . '</p>
<div class="reply">
<a class="comment-reply-link" href="'. $url .'&amp;replytocom='. $commentdata['comment_ID'] .'#respond"
onclick="return addComment.moveForm(&quot;div-comment-'. $commentdata['comment_ID'] .'&quot;, &quot;'. $commentdata['comment_ID'] . '&quot;, &quot;respond&quot;, &quot;1&quot;)">Reply</a>
</div>
</div>
</li></ul>' ;

echo $output;
}

$post = &get_post($commentdata['comment_post_ID']);
wp_notify_postauthor($comment_ID, $commentdata['comment_type']);
break;
default:
echo "error";
}
exit;
}
}

add_action('comment_post', 'ajaxify_comments_jaya', 25, 2);

?>

Screenshots

1. User need to fill all the required fields of the comment form like name, email, comment, website (optional) etc in order to successfully submit the comment form.

ajax comment form

2. Once the user click on Post Comment button then the success message appears on the screen.

add easy commenting system to your wordpress blog

3. Now admin can directly leave a reply by click on the Reply option appear on the top right section, similar as the below image.

wordpress comment form

4. Once the reply is posted, it will appear on the front end same as the below image.

easy blog commenting system using ajax

Conclusion

I hope with this tutorial, you will get a easy method to ajaxify WordPress comment section. But if you find any difficulty on executing above steps or regarding code then do share it in the comment section. I will definitely help you out.

Also share your thoughts about the post, I will be glad to know that. :)

 

Posts Of Your Interest-

Data Insertion Using Ajax How To Install WordPress On Amazon aws ec2 WordPress Plugin To Customize Your Dashboard

 

About Malika Rani
sbauthor
I am Malika Rani, a software engineer and a blogger. My hobby is to learn new things, searching exciting and informative discoveries over the web. So blogging is the best platform through which I can share my knowledge and experiences with you. Hope you enjoy reading my blogs and it will be helpful for you.

Comments and Responses