Skip to content

Instantly share code, notes, and snippets.

@cristianp6
Last active November 16, 2016 04:17
Show Gist options
  • Save cristianp6/c2fd4d6301c25cd7dd77 to your computer and use it in GitHub Desktop.
Save cristianp6/c2fd4d6301c25cd7dd77 to your computer and use it in GitHub Desktop.
WordPress Block Spam Comments: no plugin, no dependencies, pure JavaScript, place in your functions.php
<?php
/* Block Spam Comments - BEGIN */
/* source: http://davidwalsh.name/wordpress-comment-spam */
add_action( 'wp_footer', 'catch_new_comment_submit' );
add_filter( 'preprocess_comment', 'preprocess_new_comment' );
function catch_new_comment_submit(){
global $post;
if( comments_open( $post->ID ) && (is_single() || is_page()) ){ ?>
<script type="text/javascript">
window.onload = function() { 'use strict';
var commentForm = document.getElementById('commentform');
function serialize(obj, prefix) {
var str = [];
for(var p in obj){
if(obj.hasOwnProperty(p)){
var k = prefix ? prefix + '[' + p + ']' : p, v = obj[p];
str.push( typeof v == 'object' ? serialize(v, k) : encodeURIComponent(k) + '=' + encodeURIComponent(v) );
}
}
return str.join("&");
}
function processCommentForm(e) {
if(e.preventDefault) e.preventDefault();
commentForm.elements['submit'].disabled = 'disabled';
commentForm.elements['submit'].style.visibility = 'hidden';
var formData={};
for(var i=0; i<commentForm.elements.length; i++)
formData[commentForm.elements[i].name] = commentForm.elements[i].value;
formData['is_legit'] = 1;
formData = serialize( formData );
var request = new XMLHttpRequest();
request.open('POST', commentForm.action, true);
request.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8');
request.send( formData );
commentForm.elements['submit'].disabled = false;
commentForm.elements['submit'].style.visibility = 'visible';
location.reload();
return false;
}
if(commentForm.length){
if(commentForm.attachEvent){
commentForm.attachEvent('submit', processCommentForm);
} else {
commentForm.addEventListener('submit', processCommentForm);
}
}
};
</script><?php
}
}
function preprocess_new_comment( $commentdata ){
if( !isset($_POST['is_legit']) )
wp_die();
return $commentdata;
}
/* Block Spam Comments - END */
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment