Basic No JavaScript Honeypot for WordPress Comments

if ( !class_exists( 'jemsCommentHoneypot' ) ) {
	class jemsCommentHoneypot {
		
		function __construct() {
			add_filter( 'comment_form_default_fields', array( $this, 'add_honeypot_field_to_form' ) );
			add_filter( 'preprocess_comment', array( $this, 'process_honeypot_field' ), 1 );
		}
		
		/*
		 * adds our honeypot to the comment field defaults, wrapped in noscript; the likelihood of a genuine commenter 
		 * seeing this these days is slim to none
		 */
		function add_honeypot_field_to_form( $fields ) {
			$fields['telephone'] = '<noscript><p class="comment-form-telephone"><label for="telephone">' . __( 'Telephone' ) .'</label><input id="telephone" name="telephone" value=""></p></noscript>';
			return $fields;
		}
		
		/*
		 * detect presence of our honeypot field
		 * if exists, redirect to the post (preferably) or home as fallback
		 */
		function process_honeypot_field( $commentdata ) {
			if ( isset( $_POST['telephone'] ) ) {
				$redirect_to = isset( $_SERVER['HTTP_REFERER'] ) ? $_SERVER['HTTP_REFERER'] : home_url();
				wp_safe_redirect( esc_url_raw( $redirect_to ) );
				die();
			}
			
			return $commentdata;
		}
	}
	$jemsCommentHoneypot = new jemsCommentHoneypot();
}

Comments are closed.