Apply reCAPTCHA v3 WordPress
March 19, 2025 Β· AI Conversations
—
### **Step 1: Get Google reCAPTCHA v3 API Keys**
1. Visit [Google reCAPTCHA Admin Console](https://www.google.com/recaptcha/admin/create).
2. Register your site:
– Choose **reCAPTCHA v3**.
– Enter your domain (e.g., `yourwebsite.com`).
– Accept the terms and create the keys.
3. Copy the **Site Key** and **Secret Key**.
—
### **Step 2: Install and Configure a Plugin**
#### **Option 1: Using a Plugin**
You can use a plugin like:
– **[reCaptcha by BestWebSoft](https://wordpress.org/plugins/google-captcha/)**
– **[Simple Google reCAPTCHA](https://wordpress.org/plugins/simple-google-recaptcha/)**
#### **Steps for Plugin Installation:**
1. Go to **WordPress Dashboard > Plugins > Add New**.
2. Search for **"reCaptcha by BestWebSoft"**.
3. Install and activate it.
4. Navigate to **Settings > reCaptcha**.
5. Enter the **Site Key** and **Secret Key**.
6. Choose **reCAPTCHA v3** and enable it for the whole site (login, comments, registration, etc.).
7. Save changes.
—
### **Step 3: Add reCAPTCHA v3 Manually (For Developers)**
If you prefer to **add reCAPTCHA v3 manually**, follow these steps:
#### **1. Add the reCAPTCHA v3 Script**
Edit your **functions.php** file and enqueue the script:
function add_recaptcha_v3_script() {
?>
<script src="https://www.google.com/recaptcha/api.js?render=your_site_key"></script>
<script>
grecaptcha.ready(function() {
grecaptcha.execute('your_site_key', {action: 'homepage'}).then(function(token) {
document.getElementById('recaptcha-response').value = token;
});
});
</script>
<?php
}
add_action('wp_head', 'add_recaptcha_v3_script');
**Replace `your_site_key`** with your actual **Google reCAPTCHA v3 site key**.
—
#### **2. Add a Hidden Input Field in Forms**
To pass the token to your forms, add this hidden input field inside your forms:
<input type="hidden" id="recaptcha-response" name="recaptcha-response">
—
#### **3. Verify reCAPTCHA Response in PHP**
In your form handler (e.g., `functions.php` or a custom plugin), verify the reCAPTCHA response:
function verify_recaptcha_v3($token) {
$secret_key = 'your_secret_key';
$response = wp_remote_post('https://www.google.com/recaptcha/api/siteverify', [
'body' => [
'secret' => $secret_key,
'response' => $token,
'remoteip' => $_SERVER['REMOTE_ADDR']
]
]);
$response_body = wp_remote_retrieve_body($response);
$result = json_decode($response_body);
return $result->success && $result->score >= 0.5; // Adjust score threshold if needed
}
// Example: Validate before processing a form
if ($_SERVER["REQUEST_METHOD"] === "POST") {
if (isset($_POST['recaptcha-response']) && verify_recaptcha_v3($_POST['recaptcha-response'])) {
// Process form
} else {
wp_die("reCAPTCHA verification failed. Please try again.");
}
}
—
### **Step 4: Test and Debug**
1. Visit your **WordPress website** and check the **Console** (Press F12 > Console) to confirm reCAPTCHA v3 is loading.
2. Submit forms and check if validation is working.
3. If using a plugin, use the built-in reCAPTCHA test mode.
—
This will integrate **Google reCAPTCHA v3 site-wide** across your WordPress site, protecting login forms, comments, and other interactions from spam. π
—
## **Step 1: Get reCAPTCHA v3 API Keys**
1. Go to the [Google reCAPTCHA Admin Console](https://www.google.com/recaptcha/admin/create).
2. Register your site:
– Choose **reCAPTCHA v3**.
– Enter your **domain** (e.g., `yourwebsite.com`).
– Accept the terms and **create the keys**.
3. Copy your **Site Key** and **Secret Key**.
—
## **Step 2: Add reCAPTCHA v3 to Your WordPress Theme**
We will **inject reCAPTCHA v3 globally** into all pages using `wp_head`.
### **1. Load reCAPTCHA v3 in WordPress**
Add the following code to your **themeβs `functions.php` file**:
function add_recaptcha_v3_script() {
?>
<script src="https://www.google.com/recaptcha/api.js?render='your_site_key'"></script>
<script>
grecaptcha.ready(function() {
grecaptcha.execute('your_site_key', {action: 'homepage'}).then(function(token) {
document.querySelectorAll('.recaptcha-response').forEach(function(el) {
el.value = token;
});
});
});
</script>
<?php
}
add_action('wp_head', 'add_recaptcha_v3_script');
β **Replace** `'your_site_key'` with your **Google reCAPTCHA v3 Site Key**.
—
## **Step 3: Add reCAPTCHA Token Field to Forms**
Since reCAPTCHA v3 requires a **hidden input field** in forms, manually add:
<input type="hidden" class="recaptcha-response" name="recaptcha-response">
Add this inside:
– **Login form (`wp-login.php`)**
– **Registration form**
– **Comment form (`comments.php`)**
– **Custom forms**
—
## **Step 4: Verify reCAPTCHA v3 Response in WordPress**
Modify `functions.php` to validate **reCAPTCHA v3** for **login, registration, and comment forms**.
### **1. Verify reCAPTCHA v3 in PHP**
Add this function in `functions.php`:
function verify_recaptcha_v3($token) {
$secret_key = 'your_secret_key'; // Replace with your secret key
$response = wp_remote_post('https://www.google.com/recaptcha/api/siteverify', [
'body' => [
'secret' => $secret_key,
'response' => $token,
'remoteip' => $_SERVER['REMOTE_ADDR']
]
]);
$response_body = wp_remote_retrieve_body($response);
$result = json_decode($response_body);
return $result->success && $result->score >= 0.5; // Adjust threshold if needed
}
β **Replace** `'your_secret_key'` with your **Google reCAPTCHA v3 Secret Key**.
—
### **2. Apply reCAPTCHA v3 to WordPress Login Form**
Add this to `functions.php`:
function validate_recaptcha_on_login($user, $password) {
if ($_SERVER["REQUEST_METHOD"] === "POST") {
if (!isset($_POST['recaptcha-response']) || !verify_recaptcha_v3($_POST['recaptcha-response'])) {
wp_die(__('reCAPTCHA verification failed. Please try again.'));
}
}
return $user;
}
add_filter('wp_authenticate_user', 'validate_recaptcha_on_login', 10, 2);
β This ensures **login attempts** fail if reCAPTCHA **validation fails**.
—
### **3. Apply reCAPTCHA v3 to WordPress Comment Form**
Add this to `functions.php`:
function validate_recaptcha_on_comment($commentdata) {
if ($_SERVER["REQUEST_METHOD"] === "POST") {
if (!isset($_POST['recaptcha-response']) || !verify_recaptcha_v3($_POST['recaptcha-response'])) {
wp_die(__('reCAPTCHA verification failed. Please try again.'));
}
}
return $commentdata;
}
add_filter('preprocess_comment', 'validate_recaptcha_on_comment');
β This blocks **spam comments** using reCAPTCHA.
—
### **4. Apply reCAPTCHA v3 to WordPress Registration Form**
Add this to `functions.php`:
function validate_recaptcha_on_register($errors, $sanitized_user_login, $user_email) {
if ($_SERVER["REQUEST_METHOD"] === "POST") {
if (!isset($_POST['recaptcha-response']) || !verify_recaptcha_v3($_POST['recaptcha-response'])) {
$errors->add('recaptcha_error', __('reCAPTCHA verification failed. Please try again.'));
}
}
return $errors;
}
add_filter('registration_errors', 'validate_recaptcha_on_register', 10, 3);
β This blocks **fake registrations** with reCAPTCHA.
—
## **Step 5: Test Your Setup**
1. Open your **login page**, **comment form**, or **registration page**.
2. Inspect the page source (`CTRL + U`) and check if the **hidden input field** “ is added.
3. Try submitting a **login form**, **comment**, or **registration**.
4. If reCAPTCHA fails, it should **block submission**.
—
## **Final Thoughts**
This method integrates **Google reCAPTCHA v3 site-wide** **without a plugin** across:
β
Login form
β
Registration form
β
Comment form
β
Custom forms
**If you need further customizations, let me know! π**
—
### **π Steps to Implement Google reCAPTCHA v3 Site-Wide Without Forms**
Instead of applying it on forms, we will:
– **Load reCAPTCHA v3 script globally**
– **Execute reCAPTCHA for every page**
– **Validate requests in the backend**
– **Apply it on actions like login, comment submission, AJAX requests, etc.**
—
### **1οΈβ£ Add reCAPTCHA v3 Script to WordPress Head**
Since reCAPTCHA v3 works based on user behavior, we need to **load it site-wide**.
π **Add this code to `functions.php`**:
function load_recaptcha_v3_sitewide() {
?>
<script src="https://www.google.com/recaptcha/api.js?render='your_site_key'"></script>
<script>
function executeRecaptcha() {
grecaptcha.ready(function() {
grecaptcha.execute('your_site_key', {action: 'sitewide'}).then(function(token) {
localStorage.setItem('recaptcha_token', token); // Store token temporarily
});
});
}
executeRecaptcha();
document.addEventListener("visibilitychange", function() {
if (!document.hidden) {
executeRecaptcha(); // Refresh token on visibility change
}
});
</script>
<?php
}
add_action('wp_head', 'load_recaptcha_v3_sitewide');
β **Replace** `'your_site_key'` with your **Google reCAPTCHA v3 Site Key**.
—
### **2οΈβ£ Validate reCAPTCHA v3 Token in PHP**
Since reCAPTCHA v3 does not rely on form fields, we will **fetch the token dynamically** via AJAX.
π **Add this to `functions.php`**:
function verify_recaptcha_v3_sitewide($token) {
$secret_key = 'your_secret_key'; // Replace with your secret key
$response = wp_remote_post('https://www.google.com/recaptcha/api/siteverify', [
'body' => [
'secret' => $secret_key,
'response' => $token,
'remoteip' => $_SERVER['REMOTE_ADDR']
]
]);
$response_body = wp_remote_retrieve_body($response);
$result = json_decode($response_body);
return ($result->success && $result->score >= 0.5); // Adjust score threshold if needed
}
β **Replace** `'your_secret_key'` with your **Google reCAPTCHA v3 Secret Key**.
—
### **3οΈβ£ Implement reCAPTCHA for Site-Wide Actions**
You can apply **reCAPTCHA validation globally** for different actions.
#### **πΉ Apply reCAPTCHA on WordPress Login**
π **Add this to `functions.php`**:
function validate_recaptcha_on_login($user, $password) {
if ($_SERVER["REQUEST_METHOD"] === "POST") {
$recaptcha_token = isset($_POST['recaptcha_token']) ? sanitize_text_field($_POST['recaptcha_token']) : '';
if (!$recaptcha_token || !verify_recaptcha_v3_sitewide($recaptcha_token)) {
wp_die(__('reCAPTCHA verification failed. Please try again.'));
}
}
return $user;
}
add_filter('wp_authenticate_user', 'validate_recaptcha_on_login', 10, 2);
β This will **protect WordPress login** with reCAPTCHA **without adding a form field**.
—
#### **πΉ Apply reCAPTCHA on Comments**
π **Add this to `functions.php`**:
function validate_recaptcha_on_comment($commentdata) {
if ($_SERVER["REQUEST_METHOD"] === "POST") {
$recaptcha_token = isset($_POST['recaptcha_token']) ? sanitize_text_field($_POST['recaptcha_token']) : '';
if (!$recaptcha_token || !verify_recaptcha_v3_sitewide($recaptcha_token)) {
wp_die(__('reCAPTCHA verification failed. Please try again.'));
}
}
return $commentdata;
}
add_filter('preprocess_comment', 'validate_recaptcha_on_comment');
β This will **protect comments from spam** **without modifying the comment form**.
—
#### **πΉ Apply reCAPTCHA on AJAX Requests**
If your WordPress theme or plugins use AJAX requests, you can add **reCAPTCHA validation before execution**.
π **Add this to `functions.php`**:
function validate_recaptcha_on_ajax() {
check_ajax_referer('wp_ajax_nopriv');
$recaptcha_token = isset($_POST['recaptcha_token']) ? sanitize_text_field($_POST['recaptcha_token']) : '';
if (!$recaptcha_token || !verify_recaptcha_v3_sitewide($recaptcha_token)) {
wp_send_json_error(['message' => 'reCAPTCHA failed'], 400);
}
wp_send_json_success(['message' => 'Success']);
}
add_action('wp_ajax_validate_recaptcha', 'validate_recaptcha_on_ajax');
add_action('wp_ajax_nopriv_validate_recaptcha', 'validate_recaptcha_on_ajax');
β This will **protect AJAX requests**.
—
### **4οΈβ£ Send reCAPTCHA Token via AJAX Automatically**
Since reCAPTCHA tokens are stored in `localStorage`, we need to **send them automatically on actions**.
π **Add this JavaScript inside your theme (`footer.php` or enqueue a separate script file):**
<script>
document.addEventListener("DOMContentLoaded", function() {
var recaptchaToken = localStorage.getItem('recaptcha_token');
if (recaptchaToken) {
var recaptchaInput = document.createElement("input");
recaptchaInput.type = "hidden";
recaptchaInput.name = "recaptcha_token";
recaptchaInput.value = recaptchaToken;
document.body.appendChild(recaptchaInput); // Attach globally to body
}
});
</script>
β This **automatically appends reCAPTCHA token** to **every request** (login, comments, AJAX, etc.).
—
## **π₯ Final Result**
βοΈ **reCAPTCHA v3 applied site-wide without forms**
βοΈ **Protects WordPress login, comments, AJAX requests**
βοΈ **No need to modify each form manually**
βοΈ **Works dynamically with JavaScript**
—
## **β
Summary of Key Changes**
| **Feature** | **How It Works** |
|——————–|—————-|
| **Loads globally** | Injected in `wp_head` for all pages |
| **Dynamic execution** | Runs on every page load & visibility change |
| **No form changes** | Uses AJAX & auto-appends token |
| **Validates actions** | Protects login, comments, AJAX requests |
| **Higher security** | Blocks spam & bot interactions |
—
Now, **Google reCAPTCHA v3 will protect your entire WordPress site** **without modifying forms manually**. ππ―
Let me know if you need any refinements! π
—
## **πΉ Step 1: Load reCAPTCHA v3 Globally**
We need to load the reCAPTCHA script **on all pages** and store the generated token.
π **Add this to `functions.php`**:
function add_recaptcha_v3_script() {
?>
<script src="https://www.google.com/recaptcha/api.js?render='your_site_key'"></script>
<script>
function executeRecaptcha() {
grecaptcha.ready(function() {
grecaptcha.execute('your_site_key', {action: 'sitewide'}).then(function(token) {
document.getElementById('recaptcha-response').value = token;
});
});
}
document.addEventListener("DOMContentLoaded", function() {
executeRecaptcha();
});
document.addEventListener("visibilitychange", function() {
if (!document.hidden) {
executeRecaptcha(); // Refresh token when tab is active
}
});
</script>
<?php
}
add_action('wp_footer', 'add_recaptcha_v3_script');
β **Replace** `'your_site_key'` with your **Google reCAPTCHA v3 Site Key**.
—
## **πΉ Step 2: Add reCAPTCHA Token Field to Footer**
Since we are **not modifying forms**, we will **add a hidden input field globally in the footer**.
π **Add this to your theme's `footer.php` file**, just before “:
<input type="hidden" id="recaptcha-response" name="recaptcha-response">
This ensures **reCAPTCHA v3 token** is available on **every page**.
—
## **πΉ Step 3: Validate reCAPTCHA in WordPress**
Now, we need to verify the **reCAPTCHA token** before processing important actions.
π **Add this to `functions.php`**:
function verify_recaptcha_v3($token) {
$secret_key = 'your_secret_key'; // Replace with your reCAPTCHA secret key
$response = wp_remote_post('https://www.google.com/recaptcha/api/siteverify', [
'body' => [
'secret' => $secret_key,
'response' => $token,
'remoteip' => $_SERVER['REMOTE_ADDR']
]
]);
$response_body = wp_remote_retrieve_body($response);
$result = json_decode($response_body);
return ($result->success && $result->score >= 0.5); // Adjust threshold if needed
}
β **Replace** `'your_secret_key'` with your **Google reCAPTCHA v3 Secret Key**.
—
## **πΉ Step 4: Apply reCAPTCHA Validation to WordPress Actions**
Now, apply **reCAPTCHA validation** before **login, comments, or AJAX requests**.
### **πΉ Validate on WordPress Login**
π **Add this to `functions.php`**:
function validate_recaptcha_on_login($user, $password) {
if ($_SERVER["REQUEST_METHOD"] === "POST") {
$recaptcha_token = isset($_POST['recaptcha-response']) ? sanitize_text_field($_POST['recaptcha-response']) : '';
if (!$recaptcha_token || !verify_recaptcha_v3($recaptcha_token)) {
wp_die(__('reCAPTCHA verification failed. Please try again.'));
}
}
return $user;
}
add_filter('wp_authenticate_user', 'validate_recaptcha_on_login', 10, 2);
β This will **block bot logins** without modifying the login form.
—
### **πΉ Validate on WordPress Comments**
π **Add this to `functions.php`**:
function validate_recaptcha_on_comment($commentdata) {
if ($_SERVER["REQUEST_METHOD"] === "POST") {
$recaptcha_token = isset($_POST['recaptcha-response']) ? sanitize_text_field($_POST['recaptcha-response']) : '';
if (!$recaptcha_token || !verify_recaptcha_v3($recaptcha_token)) {
wp_die(__('reCAPTCHA verification failed. Please try again.'));
}
}
return $commentdata;
}
add_filter('preprocess_comment', 'validate_recaptcha_on_comment');
β This will **block spam comments** automatically.
—
### **πΉ Validate reCAPTCHA on AJAX Requests**
π **Add this to `functions.php`**:
function validate_recaptcha_on_ajax() {
check_ajax_referer('wp_ajax_nopriv');
$recaptcha_token = isset($_POST['recaptcha-response']) ? sanitize_text_field($_POST['recaptcha-response']) : '';
if (!$recaptcha_token || !verify_recaptcha_v3($recaptcha_token)) {
wp_send_json_error(['message' => 'reCAPTCHA failed'], 400);
}
wp_send_json_success(['message' => 'Success']);
}
add_action('wp_ajax_validate_recaptcha', 'validate_recaptcha_on_ajax');
add_action('wp_ajax_nopriv_validate_recaptcha', 'validate_recaptcha_on_ajax');
β This will **secure AJAX-based features** like **contact forms, search, or custom actions**.
—
## **π₯ Final Result**
β **Google reCAPTCHA v3 applied site-wide without modifying forms**
β **Protects login, comments, and AJAX interactions**
β **No changes needed in form fields**
β **Works dynamically with JavaScript**
—
## **β
Summary of Implementation**
| **Feature** | **How It Works** |
|——————–|—————-|
| **Loads globally** | Injected via `wp_footer` for all pages |
| **Dynamic execution** | Runs on every page load & visibility change |
| **No form changes** | Uses hidden input in `footer.php` |
| **Validates actions** | Protects login, comments, AJAX requests |
| **Higher security** | Blocks spam & bot interactions |
—
Now, **Google reCAPTCHA v3 will protect your entire WordPress site** **without modifying form fields manually**. ππ―
Let me know if you need any refinements! π