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.
Opens WPIDE on
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
- Install WPIDE on your WordPress site (it is free) and open Code Snippets.
- Use snippet above adds it from the library in one click. Or copy the code into a new snippet with the same code type.
- It is added inactive: review the code and settings, then switch it on.