Halloween Sale 15% off Ends in See the plans
PHP

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.

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

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

  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.