Skip to content

Instantly share code, notes, and snippets.

@mishterk
Created November 24, 2021 21:28
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mishterk/03adb16586930acaf63246e6e18fc0aa to your computer and use it in GitHub Desktop.
Save mishterk/03adb16586930acaf63246e6e18fc0aa to your computer and use it in GitHub Desktop.
A simple, custom SPAM filter for WooCommerce registration forms. This just prevents registration form submissions unless the custom field has the expected value in it.
<?php
include 'SimpleWooRegistrationSpamFilter.php';
\PhilKurth\SimpleWooRegistrationSpamFilter::init();
<?php
namespace PhilKurth;
use WP_Error;
/**
* Class adds a simple math equation to the registration form in order to help combat SPAM submissions.
*/
class SimpleWooRegistrationSpamFilter {
private static $question = 'One plus three equals?';
private static $answer = 4;
private static $field_name = 'reg_test_human';
public static function init() {
// Add the field to the form.
add_action( 'woocommerce_register_form', [ __CLASS__, '_render_field' ] );
// Validate the input.
add_filter( 'woocommerce_registration_errors', [ __CLASS__, '_validate_field' ], 10, 3 );
}
public static function _render_field() {
?>
<p class="woocommerce-form-row woocommerce-form-row--wide form-row form-row-wide">
<label for="reg_test_human"><?= self::$question ?>&nbsp;<span class="required">*</span></label>
<input type="number"
required
class="woocommerce-Input woocommerce-Input--text input-text"
name="<?= self::$field_name ?>"
id="reg_test_human"/>
</p>
<?php
}
public static function _validate_field( WP_Error $errors, $username, $email ) {
// If the field isn't in the request, don't validate. This ensures new customers being created during checkout
// aren't affected by the field.
if ( ! isset( $_REQUEST[ self::$field_name ] ) ) {
return $errors;
}
if ( empty( $_REQUEST[ self::$field_name ] ) ) {
$errors->add( 'registration-error-invalid-math-equation', 'The answer to the math equation is missing — try again.' );
} elseif ( $_REQUEST[ self::$field_name ] != self::$answer ) {
$errors->add( 'registration-error-invalid-math-equation', 'The answer to the math equation is incorrect — try again.' );
}
return $errors;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment