Reject Comments Submitted Too Fast
Rejects comments sent within a few seconds of the page loading, which only bots manage, using a signed timestamp in the form.
Opens WPIDE on
Code
// Minimum seconds between loading the page and submitting a comment.
$wpide_comment_min_seconds = 5;
add_action( 'comment_form', function () {
if ( is_user_logged_in() ) {
return;
}
$time = time();
printf(
'<input type="hidden" name="wpide_ct" value="%1$d"><input type="hidden" name="wpide_cs" value="%2$s">',
(int) $time,
esc_attr( hash_hmac( 'sha256', (string) $time, wp_salt( 'nonce' ) ) )
);
} );
add_filter( 'preprocess_comment', function ( $commentdata ) use ( $wpide_comment_min_seconds ) {
$type = isset( $commentdata['comment_type'] ) ? $commentdata['comment_type'] : '';
if ( is_user_logged_in() || ( '' !== $type && 'comment' !== $type ) ) {
return $commentdata;
}
$time = isset( $_POST['wpide_ct'] ) ? (int) $_POST['wpide_ct'] : 0;
$sig = isset( $_POST['wpide_cs'] ) ? sanitize_text_field( wp_unslash( $_POST['wpide_cs'] ) ) : '';
if ( ! $time || ! hash_equals( hash_hmac( 'sha256', (string) $time, wp_salt( 'nonce' ) ), $sig ) || time() - $time < $wpide_comment_min_seconds ) {
wp_die( 'Your comment could not be submitted. Please go back, wait a moment and try again.', 'Comment rejected', array( 'response' => 403, 'back_link' => true ) );
}
return $commentdata;
}, 1 );
Notes
Works with page caching because the check only sets a minimum age.
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.