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.
![Cloudflare turnstile for WordPress](https://redpishi.com/wp-content/uploads/2023/12/Cloudflare-turnstile-for-wordpress.webp)
Table of Contents
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.
![cloudflare add site](https://redpishi.com/wp-content/uploads/2023/12/cloudflare-add-site.png)
On this screen, start by typing in a ‘Site Name.’
Next, type your website’s domain name into the ‘Domain’ field.
![Cloudflare Turnstile Site_Key Secret_Key](https://redpishi.com/wp-content/uploads/2023/12/Cloudflare-Turnstile-Site_Key-Secret_Key.png)
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
![Adding Cloudflare Turnstile to WordPress Login Form](https://redpishi.com/wp-content/uploads/2023/12/Adding-Cloudflare-Turnstile-to-WordPress-Login-Form.png)
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
![Adding Cloudflare Turnstile to WordPress Comment](https://redpishi.com/wp-content/uploads/2023/12/Adding-Cloudflare-Turnstile-to-WordPress-Comment.png)
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
![Adding Cloudflare Turnstile to WordPress Lost Password page](https://redpishi.com/wp-content/uploads/2023/12/Adding-Cloudflare-Turnstile-to-WordPress-Lost-Password-page.png)
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.
Adding Cloudflare Turnstile to WordPress Registration Form
![Adding Cloudflare Turnstile to WordPress Registration Form](https://redpishi.com/wp-content/uploads/2023/12/Adding-Cloudflare-Turnstile-to-WordPress-Registration-Form.png)
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.
Adding Cloudflare Turnstile to contact form 7 forms
![Adding Cloudflare Turnstile to cf7 forms](https://redpishi.com/wp-content/uploads/2023/12/Adding-Cloudflare-Turnstile-to-cf7-forms-635x1024.webp)
First, edit the form you want to add Cloudflare Turnstile to and add the following snippet before the submit button:
[c][text c]
![add Cloudflare Turnstile to wordpress form](https://redpishi.com/wp-content/uploads/2023/12/add-Cloudflare-Turnstile-to-wordpress-form.webp)
Next copy the code below into the functions.php file of your child theme or into the code snippets plugin.
Show code
add_action("wp_footer", function(){ ?>
<style>
.wpcf7 input[name="c"] {
display: none;
}
.wpcf7 .cf-turnstile {
margin-top: -10px;
}
</style>
<?php
} );
function add_custom_element_before_submit( $form ) {
$cf = '<div class="cf-turnstile" data-sitekey="'.cloudflare_key()[0].'"></div>';
$form = preg_replace('/\[\s*c\s*\]/', $cf, $form);
return $form;
}
add_filter( 'wpcf7_form_elements', 'add_custom_element_before_submit' );
add_filter('wpcf7_validate', function($result, $tag){
$turnstile_token = isset($_POST['cf-turnstile-response']) ? sanitize_text_field($_POST['cf-turnstile-response']) : '';
$ct = "c";
if (empty($turnstile_token)) {
$result->invalidate($ct, 'You must complete the Turnstile challenge to submit this form.');
return $result;
}
$secret_key = cloudflare_key()[1];
$remote_ip = $_SERVER['REMOTE_ADDR'];
$response = wp_remote_post('https://challenges.cloudflare.com/turnstile/v0/siteverify', array(
'body' => array(
'secret' => $secret_key,
'response' => $turnstile_token,
'remoteip' => $remote_ip,
),
));
if (is_wp_error($response)) {
$result->invalidate($ct, 'The Turnstile token is invalid. Please try again.');
return $result;
}
$body = wp_remote_retrieve_body($response);
$data = json_decode($body, true);
if (!$data['success']) {
$result->invalidate($ct, 'There was an error validating the Turnstile challenge. Please try again.');
return $result;
}
return $result;
}, 10, 2);
If this article is difficult for you to read in text, you can watch the video version below.
next tutorial, please! How to add Cloudflare Turnstile on bbpress forums without plugins
I am not familiar with bbPress, but if I get the chance to work with it, I may create a tutorial about it. Thank you for the suggestion!
Is it possible to add a parameter for the theme to force it to be \”light\”?
Hi rtsutton
Check this out:
https://pastecode.io/s/iveb1urs
Hi,
Please also share the PHP code snippet for contact form submission.
Thank You,