Halloween Sale 15% off Ends in See the plans
PHP

JavaScript Check Against Comment Spam Bots

Adds a hidden field to the comment form that only a real browser running JavaScript fills in; comments without it go to the spam queue instead of moderation.

Don’t have WPIDE yet? Install it on your site

Code

$wpide_cjs_token = function ( $offset = 0 ) {
    return substr( wp_hash( 'comment-js-' . gmdate( 'Ymd', time() - $offset * DAY_IN_SECONDS ) ), 0, 16 );
};

add_action( 'comment_form', function () use ( $wpide_cjs_token ) {
    printf(
        '<input type="hidden" name="wpide_cjs" id="wpide-cjs" value=""><script>document.getElementById("wpide-cjs").value=%s;</script>',
        wp_json_encode( $wpide_cjs_token() )
    );
} );

add_filter( 'pre_comment_approved', function ( $approved, $commentdata ) use ( $wpide_cjs_token ) {
    if ( 'spam' === $approved || is_user_logged_in() || ( isset( $commentdata['comment_type'] ) && in_array( $commentdata['comment_type'], array( 'pingback', 'trackback' ), true ) ) ) {
        return $approved;
    }
    if ( defined( 'REST_REQUEST' ) && REST_REQUEST ) {
        return $approved;
    }

    $sent = isset( $_POST['wpide_cjs'] ) ? sanitize_text_field( wp_unslash( $_POST['wpide_cjs'] ) ) : '';

    if ( '' !== $sent && ( hash_equals( $wpide_cjs_token(), $sent ) || hash_equals( $wpide_cjs_token( 1 ), $sent ) ) ) {
        return $approved;
    }

    return 'spam';
}, 20, 2 );

Notes

Comments are sent to spam, never deleted, so you can rescue a real one; works with page caching because the token changes only once a day.

How to add this snippet

  1. Install WPIDE on your WordPress site (it is free) and open Code Snippets.
  2. Use snippet above adds it from the library in one click. Or copy the code into a new snippet with the same code type.
  3. It is added inactive: review the code and settings, then switch it on.

Have a snippet worth sharing?

Publish it to the library from WPIDE or right here. Sign in with any WordPress site that runs WPIDE, free or Pro. Public snippets are reviewed by the WPIDE team before they appear.

Which site should get this snippet?

Enter the address of your WordPress site. WPIDE opens there in a new tab with the snippet ready to review and save.

Remembered in this browser only, so you are asked once.

Report this snippet

Tell the WPIDE team what is wrong: broken code, something harmful, spam or copied work.