Delete SPAM Comments Automatically in WordPress

One big issue with any WordPress site is the growing number of SPAM comments. It takes a lot of time to screen and delete the SPAM comments. Fortunately, there are WordPress plugins like akismet that automatically detects SPAM comments and move them to WordPress SPAM section. You can then delete all the SPAM comments in a single click.

Akismet is a great solution but unfortunately its a very resource heavy plugin. So if you are on a very small shared server, this plugin may make your WordPress site very slow. Also, akismet if free for individual users, but you may have to purchase a premium akismet key if you are an enterprise user.

If you don’t want to use akismet or any other SPAM control WordPress plugins, and still want to delete the SPAM comments automatically, then here’s a way out.

Open functions.php file in your theme editor (Appearance > Editor) and paste the following code snippet in it,

function in_comment_post_like($string, $array) {
    foreach($array as $ref) { if(strstr($string, $ref)) { return true; } }
    return false;
function drop_bad_comments() {
    if (!empty($_POST['comment'])) {
        $post_comment_content = $_POST['comment'];
        $lower_case_comment = strtolower($_POST['comment']);
        $bad_comment_content = array(
            'bad word 1 here',
            'bad word 2 here',
        if (in_comment_post_like($lower_case_comment, $bad_comment_content)) {
            $comment_box_text = wordwrap(trim($post_comment_content), 80, "\n  ", true);
            $txtdrop = fopen('/var/log/httpd/wp_post-logger/', 'a');
            fwrite($txtdrop, "  --------------\n  [COMMENT] = " . $post_comment_content . "\n  --------------\n");
            fwrite($txtdrop, "  [SOURCE_IP] = " . $_SERVER['REMOTE_ADDR'] . " @ " . date("F j, Y, g:i a") . "\n");
            fwrite($txtdrop, "  [USERAGENT] = " . $_SERVER['HTTP_USER_AGENT'] . "\n");
            fwrite($txtdrop, "  [REFERER  ] = " . $_SERVER['HTTP_REFERER'] . "\n");
            fwrite($txtdrop, "  [FILE_NAME] = " . $_SERVER['SCRIPT_NAME'] . " - [REQ_URI] = " . $_SERVER['REQUEST_URI'] . "\n");
            fwrite($txtdrop, '--------------**********------------------'."\n");
            header("HTTP/1.1 406 Not Acceptable");
            header("Status: 406 Not Acceptable");
            header("Connection: Close");
            wp_die( __('bang bang.') );
add_action('init', 'drop_bad_comments');</pre>

You can also update $bad_comment_content array to add more stop words in it. Note that if you see that the number of SPAM comments are decreasing on your posts, you should remove the code from functions.php file. If you keep the code in functions.php, it will always try to delete all SPAM comments automatically, thus maing your site slow.


Your email address will not be published. Required fields are marked *