Privacy PHP Intermediate

Add a Privacy Consent Checkbox to Comments

Require visitors to tick "I agree to the privacy policy" before their comment is accepted.

Tested on WordPress 7.1 PHP 8.3 No plugin needed Updated
functions.php 24 lines
add_filter( 'comment_form_default_fields', function ( array $fields ): array {
	$policy = get_privacy_policy_url();
	$label  = $policy
		? sprintf( 'I have read the <a href="%s" target="_blank">privacy policy</a> and agree to my name, email and comment being stored.', esc_url( $policy ) )
		: 'I agree to my name, email and comment being stored.';

	$fields['nahnu_privacy'] = sprintf(
		'<p class="comment-form-nahnu-privacy"><input id="nahnu_privacy" name="nahnu_privacy" type="checkbox" value="1" required> <label for="nahnu_privacy">%s</label></p>',
		wp_kses( $label, [ 'a' => [ 'href' => [], 'target' => [] ] ] )
	);

	return $fields;
} );

// Check it on the server too. Runs only for comments submitted through the form.
add_action( 'pre_comment_on_post', function (): void {
	if ( ! is_user_logged_in() && empty( $_POST['nahnu_privacy'] ) ) {
		wp_die(
			'Please tick the privacy box to post your comment.',
			'Privacy consent needed',
			[ 'response' => 400, 'back_link' => true ]
		);
	}
} );

Where to add this

Recommended A code snippets plugin Survives theme changes and is easy to switch off.
Child theme At the end of your child theme's functions.php file.
Must-use plugin As a .php file in wp-content/mu-plugins, starting with <?php.

Always add PHP to a staging site first, or have FTP or file manager access ready, so you can undo it if something goes wrong.

If you need recorded consent before storing commenters’ personal data, a required checkbox does the job. This snippet adds one with a link to your privacy policy page.

How it works

comment_form_default_fields adds the checkbox to the comment form for logged-out visitors. It uses the privacy policy page set under Settings → Privacy, and the required attribute stops the browser sending the form without it.

Browsers can be bypassed, so pre_comment_on_post checks again on the server. It runs only when a comment is submitted through wp-comments-post.php, and stops with a friendly message if the box wasn’t ticked.

Things to watch

  • Logged-in users aren’t shown the checkbox. They agreed when they registered.
  • Set a privacy policy page under Settings → Privacy for the link to appear.

How to test it

Log out, write a comment and submit it without ticking the box. The browser should stop you. With the box ticked, the comment should post.

This website uses cookies to enhance your browsing experience and ensure the site functions properly. By continuing to use this site, you acknowledge and accept our use of cookies.

Accept All Accept Required Only