Created
November 24, 2021 21:28
-
-
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
include 'SimpleWooRegistrationSpamFilter.php'; | |
\PhilKurth\SimpleWooRegistrationSpamFilter::init(); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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 ?> <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