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.
Opens WPIDE on
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
- 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.