Block Spam Comments with Simple PHP Logic

Home / Code Scripts / Block Spam Comments with Simple PHP Logic

Resource Type

Code Scripts

Complexity Level

Beginner

Last Updated

July 29, 2025

Description

This PHP snippet helps you block common spam comments in WordPress without using heavy anti-spam plugins. It checks for specific patterns in comments (like too many links, banned keywords, or empty user agents) and rejects them before they are stored. This is a lightweight solution for small blogs and portfolio sites.

PHP

				
					/**
 * Simple Anti-Spam Logic for WordPress Comments
 */
function rcwebkit_block_spam_comments( $commentdata ) {
    // 1. Block comments with more than 2 links
    if ( substr_count( $commentdata['comment_content'], 'http' ) > 2 ) {
        wp_die( 'Too many links. Your comment looks like spam!' );
    }

    // 2. Block if user agent is empty
    if ( empty( $_SERVER['HTTP_USER_AGENT'] ) ) {
        wp_die( 'Invalid comment. Please try again.' );
    }

    // 3. Block comments containing banned words
    $banned_words = array( 'viagra', 'casino', 'loan', 'hack', 'porn' );
    foreach ( $banned_words as $word ) {
        if ( stripos( $commentdata['comment_content'], $word ) !== false ) {
            wp_die( 'Your comment contains restricted words.' );
        }
    }

    return $commentdata;
}
add_filter( 'preprocess_comment', 'rcwebkit_block_spam_comments' );

				
			

Key Features:

 

  • Blocks comments with too many links

  • Rejects empty or suspicious user agents

  • Checks for banned keywords

  • Improves site performance by reducing spam entries

 

Steps to Use:

  1. Add the snippet to your theme’s functions.php file or a custom plugin.

  2. Customize the banned words list as needed.

  3. Test by submitting a comment with too many links or banned keywords.

Search

Connect with us

Blog Categories

recent posts

Scroll to Top