Last active
July 5, 2021 16:43
-
-
Save jayseventwo/5855972 to your computer and use it in GitHub Desktop.
Ajaxify your WordPress comments - no more submitting to a new page.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* ------------------------------------------------------------------ajax comments - add to functions.php ------- */ | |
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'){ | |
switch($comment_status){ | |
case "0": | |
wp_notify_moderator($comment_ID); | |
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']); | |
break; | |
default: | |
echo "error"; | |
} | |
exit; | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* add ajax on comments so no need to submit to new page */ | |
if (typeof jQuery != 'undefined') { | |
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 infopanel | |
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") | |
statusdiv.html('<p class="ajax-success" >Thanks for your comment. We appreciate your response.</p>'); | |
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; | |
}); | |
}); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
It does not show that comment immediately.