Halloween Sale 15% off Ends in See the plans
PHP

Required Privacy Consent Checkbox on Comments

Adds a required "I agree to the privacy policy" checkbox to the comment form and rejects comments that are submitted without it, with a link to your privacy page.

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

Code

add_filter( 'comment_form_submit_field', function ( $field ) {
    if ( is_user_logged_in() ) {
        return $field;
    }

    $policy = get_privacy_policy_url();
    $label  = $policy ? sprintf( 'I agree to the storage of my data as described in the <a href="%s" target="_blank" rel="noopener">privacy policy</a>.', esc_url( $policy ) ) : 'I agree to the storage of my data for handling this comment.';

    return '<p class="comment-form-privacy-consent"><input type="checkbox" id="wpide-comment-consent" name="wpide_comment_consent" value="1" required> <label for="wpide-comment-consent">' . $label . '</label></p>' . $field;
} );

add_filter( 'preprocess_comment', function ( $commentdata ) {
    if ( is_user_logged_in() || ( isset( $commentdata['comment_type'] ) && in_array( $commentdata['comment_type'], array( 'pingback', 'trackback' ), true ) ) ) {
        return $commentdata;
    }

    if ( empty( $_POST['wpide_comment_consent'] ) ) {
        wp_die( 'Please tick the privacy consent box to post your comment.', 'Consent required', array( 'response' => 400, 'back_link' => true ) );
    }

    return $commentdata;
} );

Notes

Links to the privacy policy page set under Settings > Privacy; logged-in users are not asked.

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.