# 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.

- Type: PHP
- Runs: Run everywhere
- Category: [Security](https://wpide.com/library/category/security/)
- Tags: comments, spam, javascript
- Author: WPIDE Team
- Installs: 0
- Updated: 2026-10-28
- Page: https://wpide.com/library/comment-javascript-token/

## Code

```php
$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 use it

Install the free WPIDE plugin (https://wordpress.org/plugins/wpide/), find "JavaScript Check Against Comment Spam Bots" in its snippet library and add it in one click; or create a new PHP snippet in WPIDE (or any code snippets plugin) and paste the code above. More snippets: https://wpide.com/library/
