Security PHP Intermediate

Stop Registration Spam With a Honeypot

Add a hidden field and a time check to the WordPress registration form, rejecting bots that fill it in or submit instantly.

Tested on WordPress 7.1 PHP 8.3 No plugin needed Updated
functions.php 15 lines
add_action( 'register_form', function (): void {
	echo '<p style="position:absolute;left:-9999px" aria-hidden="true"><label>Leave this empty <input type="text" name="nahnu_website" value="" tabindex="-1" autocomplete="off"></label></p>';
	printf( '<input type="hidden" name="nahnu_form_time" value="%d">', time() );
} );

add_filter( 'registration_errors', function ( WP_Error $errors ): WP_Error {
	$filled = ! empty( $_POST['nahnu_website'] );
	$time   = (int) ( $_POST['nahnu_form_time'] ?? 0 );
	$fast   = $time > 0 && ( time() - $time ) < 3;

	if ( $filled || $fast ) {
		$errors->add( 'nahnu_spam', '<strong>Error:</strong> Registration failed. Please try again.' );
	}
	return $errors;
} );

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 “Anyone can register” is on, bots will create accounts on your site. A honeypot is a field humans never see but bots fill in. This snippet adds one to the registration form, plus a check for forms submitted faster than a person could type.

How it works

The register_form action adds a text field moved off-screen and hidden from screen readers, and a hidden timestamp. The registration_errors filter rejects the registration if the hidden field has any value, or if the form came back less than three seconds after it was shown.

Real visitors never see the extra field, so there’s no CAPTCHA to solve.

Things to watch

  • Targeted bots can learn to skip honeypots. For heavy spam, add a CAPTCHA such as Cloudflare Turnstile.
  • This covers wp-login.php?action=register. WooCommerce’s My Account registration uses woocommerce_register_post instead.

How to test it

Register normally in a private window. It should work. Then use DevTools to fill in the hidden field and submit: you should get the error.

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