Cloudflare Turnstile is an alternative to Google reCAPTCHA that loads faster, and It provides a user-friendly experience without the need for user interaction.
In this post, I will guide you on how to add Cloudflare Turnstile to your WordPress website without using plugins, using just code.

How to Add Cloudflare Turnstile CAPTCHA in WordPress without Plugins

Get a site key and a secret key from Cloudflare

To access this information, simply open a new browser tab and navigate to the Cloudflare login page. If you don’t have an account yet, you’ll need to create one using your email address.

Once you’ve successfully logged into your Cloudflare dashboard, locate the ‘Turnstile’ option in the left-hand menu and click on it.

Then click on the ‘Add site’ button.

On this screen, start by typing in a ‘Site Name.’
Next, type your website’s domain name into the ‘Domain’ field.

In the next step, we need to add some codes to WordPress.
To do this, you can either add these codes to the functions.php file of your child theme or use the Code Snippets plugin for this purpose.

Place the code below in your child theme’s functions file and replace the site_key and secret_key with the ones you obtained in the previous step.

function cloudflare_key(){
	$sitekey= "00000000000000000000000";
	$secretkey= "000000000000000000000";
	return [$sitekey,$secretkey]; 	
}

add_action("wp_head", function(){	
	wp_enqueue_script('cloudflare-turnstile', 'https://challenges.cloudflare.com/turnstile/v0/api.js');
	} );
	

Adding Cloudflare Turnstile to WordPress Login Form

Show code

To add Cloudflare Turnstile to your login form, simply copy the code below into the functions.php file of your child theme or into the code snippets plugin.

/*
 * Adding Cloudflare Turnstile to Login Form by wpcookie
 * https://redpishi.com/wordpress-tutorials/cloudflare-turnstile-captcha-wordpress/
 */	
function login_style() {
    wp_register_script('login-recaptcha', 'https://challenges.cloudflare.com/turnstile/v0/api.js', false, NULL);
    wp_enqueue_script('login-recaptcha');
	echo "<style>p.submit, p.forgetmenot {margin-top: 10px!important;}.login form{width: 303px;} div#login_error {width: 322px;}</style>";
}
add_action('login_enqueue_scripts', 'login_style');

add_action('login_form', function(){
	echo '<div class="cf-turnstile" data-sitekey="'.cloudflare_key()[0].'"></div>';
	} );

add_action('wp_authenticate_user', function($user, $password) {
	$captcha=$_POST['cf-turnstile-response'];
	if (!$captcha) {
     return new WP_Error('Captcha Invalid', __('<center>Captcha Invalid! Please check the captcha!</center>'));
	   die();
           exit;
   }
   $secretKey = cloudflare_key()[1];
   $ip = $_SERVER['REMOTE_ADDR'];

   $url_path = 'https://challenges.cloudflare.com/turnstile/v0/siteverify';
   $data = array('secret' => $secretKey, 'response' => $captcha, 'remoteip' => $ip);
	
	$options = array(
		'http' => array(
		'method' => 'POST',
		'content' => http_build_query($data))
	);
	
	$stream = stream_context_create($options);
	
	$result = file_get_contents(
			$url_path, false, $stream);
	
	$response =  $result;
   
   $responseKeys = json_decode($response,true);
	  if(intval($responseKeys["success"]) !== 1) {
		   return new WP_Error('Captcha Invalid', __('<center>Captcha Invalid! Please check the captcha!</center>'));
		  die();
		   exit;
	  } else { 
		  return $user;
}
	
	} , 10, 2);

Adding Cloudflare Turnstile to WordPress Comment

Show code

To add Cloudflare Turnstile to your comment form, simply copy the code below into the functions.php file of your child theme or into the code snippets plugin.

/*
 * Adding Cloudflare Turnstile to WordPress Comment
 * https://redpishi.com/wordpress-tutorials/cloudflare-turnstile-captcha-wordpress/
 */	
function is_valid_captcha($captcha) {
	
   if (!$captcha) {
     return false;
   }
   $secretKey = cloudflare_key()[1];
   $ip = $_SERVER['REMOTE_ADDR'];

   $url_path = 'https://challenges.cloudflare.com/turnstile/v0/siteverify';
   $data = array('secret' => $secretKey, 'response' => $captcha, 'remoteip' => $ip);
	
	$options = array(
		'http' => array(
		'method' => 'POST',
		'content' => http_build_query($data))
	);
	
	$stream = stream_context_create($options);
	
	$result = file_get_contents(
			$url_path, false, $stream);
	
	$response =  $result;
   
   $responseKeys = json_decode($response,true);
	  if(intval($responseKeys["success"]) !== 1) {
		   return false;
	  } else { 
		  return true;
}
}
	
add_action('init', function(){
	if (!is_user_logged_in() ) {
    add_action('pre_comment_on_post', function(){
		$recaptcha = $_POST['cf-turnstile-response'];
	if (empty($recaptcha))
    wp_die( __("<b>ERROR:</b> please select <b>I'm not a robot!</b><p><a href='javascript:history.back()'>« Back</a></p>"));
	else if (!is_valid_captcha($recaptcha))
    wp_die( __("<b>please select I'm not a robot!</b>"));
		
		} );

    add_filter('comment_form_defaults',function ($submit_field) {

		    $submit_field['submit_field'] = '<div class="cf-turnstile" data-sitekey="'.cloudflare_key()[0].'"></div><br>'.$submit_field['submit_field'];
    return $submit_field;	
	});
}	
	});

Adding Cloudflare Turnstile to WordPress Lost Password page

Show code

To add Cloudflare Turnstile to to WordPress Lost Password form, simply copy the code below into the functions.php file of your child theme or into the code snippets plugin.

This code is for WPCookie PLUS+ members only.

Join WPCookie PLUS+

Adding Cloudflare Turnstile to WordPress Registration Form

To activate registration in WordPress, first go to the admin dashboard and select the “General” option from the “Setting” menu. Then, check the box next to the “Anyone can register” option.

Show code

To add Cloudflare Turnstile to to WordPress Registration Form, simply copy the code below into the functions.php file of your child theme or into the code snippets plugin.

This code is for WPCookie PLUS+ members only.

Join WPCookie PLUS+

If this article is difficult for you to read in text, you can watch the video version below.

Share this post
Maya
Maya

Hi, my name is Maya and I’m a WordPress plugin developer. I created this website to share some of the helpful codes that I’ve used in my own projects.
If you’re looking for a custom plugin for your website, you can contact me by clicking on Hire a developer in the menu. I’d love to hear from you.

Articles: 53

One comment

Leave a Reply

Your email address will not be published. Required fields are marked *