An anti-spam validation script for WordPress comment forms.

/**
 * Anti-spam measure:  checks Post Title entered by user against Post Title in database
 */
 
    $redirect = $_POST['redirect_to'];
    
    // Get the post's ID
    $get_post_ID = (int) $_POST['comment_post_ID'];
    
    // Get Post data
    $get_post_ID = get_post($get_post_ID);
    
    // Init a variable for the post title
    $title = $get_post_ID->post_title;
    
    // Count the words in the Post Title (returns an array)	
    $title_words = str_word_count($title, 1);
    
    // Init a variable for the first word in the Post Title
    $first_title_word = array_slice( $title_words, 0, 1);
    
    // Init a variable for the title the user entered
    $ptitle = $_POST['ptitle'];
    
    // Count the words in the title the user entered(returns an array)	
    $ptitle_words = str_word_count($ptitle, 1);
    
    // Init a variable for the first word in the title the user entered
    $first_ptitle_word = array_slice( $ptitle_words, 0, 1);
    
    // Case-sensitive match the titles	
    if ( $first_title_word != $first_ptitle_word ) {
    
        // unset all cookies used for validation
        setcookie('err_ptitle', '', time() - 30, COOKIEPATH, COOKIE_DOMAIN);
        
        // ..define an error message to display to alert the user,
        $msg = 'The title you entered is incorrect.  Please re-enter the validation info requested.';
        
        // ..set a temporary cookie to display error msg (for 10 sec.) on Post page
        setcookie('err_ptitle', $msg, time() + 10, COOKIEPATH, COOKIE_DOMAIN);
        
        wp_redirect( $redirect . '#comment-error' );
        
        exit;
     }
Tagged: