Next, I will share with you two pieces of code, which can add verification codes to the WordPress login page and registration page respectively.
Similarly, you only need to add it to the Functions.php file of the current wordpress website building theme, or you can add it to the Code Snippets plugin.
//Background login math verification code
function rhymo_add_login_fields() {
//Get two random numbers, range 0~9
$num1=rand(0,9);
$num2=rand(0,9);
//specific content in the final page
echo "<p><label for='math' class='small'>Verification Code
</label><br /> <input type='text' name='sum' placeholder='$num1 + $num2 = ?' class='input' value='' size='25' tabindex='4'>"
."<input type='hidden' name='num1' value='$num1'>"
."<input type='hidden' name='num2' value='$num2'></p>";
}
add_action('login_form','rhymo_add_login_fields');
function login_val() {
$sum=$_POST['sum'];//User Submitted Calculations
switch($sum){
//Get the correct calculation result and jump out directly
case $_POST['num1']+$_POST['num2']:break;
//Error message when no result is filled
case null:wp_die('wrong: please enter verification code.');break;
//Error message when calculation is wrong
default:wp_die('wrong: Verification code error, please try again.');
}
}
add_action('login_form_login','login_val');
//Wordpress new user registration random math captcha
function add_security_question_fields() {
//Get two random numbers, range 0~9
$num1=rand(0,9);
$num2=rand(0,9);
//specific content in the final page
echo "<p><label for='math' class='small'>verification code:$num1 + $num2 = ? </label><input type='text' name='sum' class='input' value='' size=
'25'>" ."<input type='hidden' name='num1' value='$num1'>"
."<input type='hidden' name='num2' value='$num2'></p>";}
add_action('register_form','add_security_question_fields');
add_action( 'register_post', 'add_security_question_validate', 10, 3 );
function add_security_question_validate( $sanitized_user_login, $user_email, $errors) {
$sum=$_POST['sum'];//User Submitted Calculations
switch($sum){
//Get the correct calculation result and jump out directly
case $_POST['num1']+$_POST['num2']:break;
//Error message when no result is filled
case null:wp_die('Error: Please enter the verification code!');break;
//Error message when calculation is wrong
default:wp_die('Error: Verification code error, please try again!');}}
add_action( 'add_security_question','register_form' );