Key Takeaways
- Integrating a CAPTCHA with the WordPress comment form can deter bots from submitting spam comments, saving time and resources spent on moderating and deleting these comments.
- The tutorial demonstrates how to use the WordPress HTTP API in a plugin, add additional form fields to the WordPress comment form, and validate and utilize the values added to custom fields.
- The CAPTCHA plugin developed in the tutorial includes an error message if the CAPTCHA form is left empty or if the user fails the challenge. It also deletes any comments submitted that fail the CAPTCHA challenge.
- The tutorial emphasizes the versatility of WordPress comment system, allowing users to add extra form fields to the comment form and implement any desired features thanks to the filters and actions mentioned.
Over the years, WordPress has become a target for spammers due to it increasing popularity.
Unfortunately, automated software exists whose purpose is to crawl the web in search of websites that are built with any popular platform, such as WordPress, and to submit hundreds, even thousands of spam comments. Spam comments are very annoying, they consume our precious time when it comes to moderating and deleting them.
I know you hate spam comments as much as I do and would love to know how to combat them. One way of deterring bots from submitting spam comments is by integrating a CAPTCHA to the comment form.
In previous tutorials, we learned how to integrate CAPTCHAs to the WordPress login and registration form.
In similar fashion, we’ll now run through how to integrate a CAPTCHA with the WordPress comment system.
There are many CAPTCHA plugins available in the WordPress plugin directory such as WP-reCAPTCHA and Securimage-WP-Fixed.
The aim of this tutorial is to not create yet another CAPTCHA plugin but to:
- Demonstrate how the WordPress HTTP API can be used in a plugin.
- How to include additional form fields to the WordPress comment form.
- How to validate and utilise the values added to custom fields.
Without further ado, let’s get started with the plugin development.
Plugin Development
First off, head over to reCAPTCHA, register your domain name and grab your public and private API keys.
Include the plugin header.
<span><span><?php </span></span><span> </span><span><span>/* </span></span><span><span>Plugin Name: Add reCAPTCHA to comment form </span></span><span><span>Plugin URI: https://www.sitepoint.com </span></span><span><span>Description: Add Google's reCAPTCHA to WordPress comment form </span></span><span><span>Version: 1.0 </span></span><span><span>Author: Agbonghama Collins </span></span><span><span>Author URI: http://w3guy.com </span></span><span><span>License: GPL2 </span></span><span><span>*/</span></span>
Create a class with three properties that will store the reCAPTCHA’s private & public key as well as the CAPTCHA error message (errors are generated when the CAPTCHA form is left empty and a user fails the challenge).
<span>class Captcha_Comment_Form { </span> <span>/** <span>@type string private key|public key */</span> </span> <span>private $public_key, $private_key; </span> <span>/** <span>@type string captcha errors */</span> </span> <span>private static $captcha_error;</span>
The class magic constructor method will contain two pairs of action and filter hooks.
<span>/** class constructor */ </span> <span>public function __construct() { </span> <span>$this->public_key = '6Le6d-USAAAAAFuYXiezgJh6rDaQFPKFEi84yfMc'; </span> <span>$this->private_key = '6Le6d-USAAAAAKvV-30YdZbdl4DVmg_geKyUxF6b'; </span> <span>// adds the captcha to the WordPress form </span> <span>add_action( 'comment_form', array( $this, 'captcha_display' ) ); </span> <span>// delete comment that fail the captcha challenge </span> <span>add_action( 'wp_head', array( $this, 'delete_failed_captcha_comment' ) ); </span> <span>// authenticate the captcha answer </span> <span>add_filter( 'preprocess_comment', array( $this, 'validate_captcha_field' ) ); </span> <span>// redirect location for comment </span> <span>add_filter( 'comment_post_redirect', array( $this, 'redirect_fail_captcha_comment' ), 10, 2 ); </span> <span>}</span>
Code explanation: First, my reCAPTCHA public and private keys are saved to their class properties.
The captcha_display() method that will output the reCAPTCHA challenge is added to the comment form by the comment_form Action.
The wp_head Action includes the callback function delete_failed_captcha_comment() that will delete any comment submitted that fail the CAPTCHA challenge.
The filter preprocess_comment calls the validate_captcha_field() method to ensure the CAPTCHA field isn’t left empty and also that the answer is correct.
The filter comment_post_redirect call redirect_fail_captcha_comment() to add some query parameters to the comment redirection URL.
Here is the code for captcha_display() that will output the CAPTCHA challenge.
Additionally, it check if there is a query string attached to the current page URL and display the appropriate error message depending on the value of $_GET['captcha'] set by redirect_fail_captcha_comment()
<span><span><?php </span></span><span> </span><span><span>/* </span></span><span><span>Plugin Name: Add reCAPTCHA to comment form </span></span><span><span>Plugin URI: https://www.sitepoint.com </span></span><span><span>Description: Add Google's reCAPTCHA to WordPress comment form </span></span><span><span>Version: 1.0 </span></span><span><span>Author: Agbonghama Collins </span></span><span><span>Author URI: http://w3guy.com </span></span><span><span>License: GPL2 </span></span><span><span>*/</span></span>
<span>class Captcha_Comment_Form { </span> <span>/** <span>@type string private key|public key */</span> </span> <span>private $public_key, $private_key; </span> <span>/** <span>@type string captcha errors */</span> </span> <span>private static $captcha_error;</span>
The method validate_captcha_field() as its name implies to validate the CAPTCHA answer by making sure the CAPTCHA field isn’t left empty and the supplied answer is correct.
<span>/** class constructor */ </span> <span>public function __construct() { </span> <span>$this->public_key = '6Le6d-USAAAAAFuYXiezgJh6rDaQFPKFEi84yfMc'; </span> <span>$this->private_key = '6Le6d-USAAAAAKvV-30YdZbdl4DVmg_geKyUxF6b'; </span> <span>// adds the captcha to the WordPress form </span> <span>add_action( 'comment_form', array( $this, 'captcha_display' ) ); </span> <span>// delete comment that fail the captcha challenge </span> <span>add_action( 'wp_head', array( $this, 'delete_failed_captcha_comment' ) ); </span> <span>// authenticate the captcha answer </span> <span>add_filter( 'preprocess_comment', array( $this, 'validate_captcha_field' ) ); </span> <span>// redirect location for comment </span> <span>add_filter( 'comment_post_redirect', array( $this, 'redirect_fail_captcha_comment' ), 10, 2 ); </span> <span>}</span>
Let’s take a closer look at validate_captcha_field(), specifically the elseif conditional statement, a call is made to recaptcha_response() to check if the CAPTCHA answer is correct.
Below is the code for the recaptcha_response().
/** Output the reCAPTCHA form field. */ public function captcha_display() { if ( isset( $_GET['captcha'] ) && $_GET['captcha'] == 'empty' ) { echo '<span><span><span><strong</span>></span>ERROR<span><span></strong</span>></span>: CAPTCHA should not be empty'; </span> } elseif ( isset( $_GET['captcha'] ) && $_GET['captcha'] == 'failed' ) { echo '<span><span><span><strong</span>></span>ERROR<span><span></strong</span>></span>: CAPTCHA response was incorrect'; </span> } echo <<<span><span><span><CAPTCHA_FORM</span> </span></span><span> <span><style type<span>='text/css'</span>></span><span><span><span>#submit</span> { </span></span></span><span><span> <span>display: none; </span></span></span><span><span> <span>}</span></span><span><span></style</span>></span> </span> <span><span><span><script</span> type<span>="text/javascript"</span> </span></span><span> <span>src<span>="http://www.google.com/recaptcha/api/challenge?k=<span><?= $this->public_key; ?></span>"</span>></span><span> </span></span><span><span> </span><span><span></script</span>></span> </span> <span><span><span><noscript</span>></span> </span> <span><span><span><iframe</span> src<span>="http://www.google.com/recaptcha/api/noscript?k=<span><?= $this->public_key; ?></span>"</span> </span></span><span> <span>height<span>="300"</span> width<span>="300"</span> frameborder<span>="0"</span>></span><span><span></iframe</span>></span> </span> <span><span><span><br</span>></span> </span> <span><span><span><textarea</span> name<span>="recaptcha_challenge_field"</span> rows<span>="3"</span> cols<span>="40"</span>></span> </span> <span><span><span></textarea</span>></span> </span> <span><span><span><input</span> type<span>="hidden"</span> name<span>="recaptcha_response_field"</span> </span></span><span> <span>value<span>="manual_challenge"</span>></span> </span> <span><span><span></noscript</span>></span> </span> <span><span><span><input</span> name<span>="submit"</span> type<span>="submit"</span> id<span>="submit-alt"</span> tabindex<span>="6"</span> value<span>="Post Comment"</span>/></span> </span>CAPTCHA_FORM; }
Allow me to explain how the recaptcha_response() works.
A POST request is sent to the endpoint http://www.google.com/recaptcha/api/verify with the following parameters.
- privatekey: Your private key
- remoteip The IP address of the user who solved the CAPTCHA.
- challenge The value of recaptcha_challenge_field sent via the form.
- response The value of recaptcha_response_field sent via the form.
The challenge and response POST data sent by the form is captured and saved to $challenge and $response respectively. $_SERVER["REMOTE_ADDR"] capture the user’s IP address and it to $remote_ip.
WordPress HTTP API the POST parameter to be in array form hence the code below.
<span>/** </span><span> * Add query string to the comment redirect location </span><span> * </span><span> * <span>@param $location string location to redirect to after comment </span></span><span> * <span>@param $comment object comment object </span></span><span> * </span><span> * <span>@return <span>string</span> </span></span><span> */ </span> <span>function redirect_fail_captcha_comment( $location, $comment ) { </span> <span>if ( ! empty( <span>self::</span>$captcha_error ) ) { </span> <span>$args = array( 'comment-id' => $comment->comment_ID ); </span> <span>if ( <span>self::</span>$captcha_error == 'captcha_empty' ) { </span> <span>$args['captcha'] = 'empty'; </span> <span>} elseif ( <span>self::</span>$captcha_error == 'challenge_failed' ) { </span> <span>$args['captcha'] = 'failed'; </span> <span>} </span> <span>$location = add_query_arg( $args, $location ); </span> <span>} </span> <span>return $location; </span> <span>}</span>
The recaptcha_post_request() is a wrapper function for the HTTP API which will accept the POST parameter/body, make a request to the reCAPTCHA API and return true if the CAPTCHA test was passed and false otherwise.
<span>/** </span><span> * Verify the captcha answer </span><span> * </span><span> * <span>@param $commentdata object comment object </span></span><span> * </span><span> * <span>@return <span>object</span> </span></span><span> */ </span> <span>public function validate_captcha_field( $commentdata ) { </span> <span>// if captcha is left empty, set the self::$captcha_error property to indicate so. </span> <span>if ( empty( $_POST['recaptcha_response_field'] ) ) { </span> <span><span>self::</span>$captcha_error = 'captcha_empty'; </span> <span>} </span> <span>// if captcha verification fail, set self::$captcha_error to indicate so </span> <span>elseif ( $this->recaptcha_response() == 'false' ) { </span> <span><span>self::</span>$captcha_error = 'challenge_failed'; </span> <span>} </span> <span>return $commentdata; </span> <span>}</span>
Any comment made by a user who failed the captcha challenge or left the field empty get deleted by delete_failed_captcha_comment()
<span>/** </span><span> * Get the reCAPTCHA API response. </span><span> * </span><span> * <span>@return <span>string</span> </span></span><span> */ </span> <span>public function recaptcha_response() { </span> <span>// reCAPTCHA challenge post data </span> <span>$challenge = isset( $_POST['recaptcha_challenge_field'] ) ? esc_attr( $_POST['recaptcha_challenge_field'] ) : ''; </span> <span>// reCAPTCHA response post data </span> <span>$response = isset( $_POST['recaptcha_response_field'] ) ? esc_attr( $_POST['recaptcha_response_field'] ) : ''; </span> <span>$remote_ip = $_SERVER["REMOTE_ADDR"]; </span> <span>$post_body = array( </span> <span>'privatekey' => $this->private_key, </span> <span>'remoteip' => $remote_ip, </span> <span>'challenge' => $challenge, </span> <span>'response' => $response </span> <span>); </span> <span>return $this->recaptcha_post_request( $post_body ); </span> <span>}</span>
Finally, we close the plugin class.
<span>$post_body = array( </span> <span>'privatekey' => $this->private_key, </span> <span>'remoteip' => $remote_ip, </span> <span>'challenge' => $challenge, </span> <span>'response' => $response </span> <span>); </span> <span>return $this->recaptcha_post_request( $post_body );</span>
We are done coding the plugin class. To put the class to work, we need to instantiate it like so:
<span>/** </span><span> * Send HTTP POST request and return the response. </span><span> * </span><span> * <span>@param $post_body array HTTP POST body </span></span><span> * </span><span> * <span>@return <span>bool</span> </span></span><span> */ </span> <span>public function recaptcha_post_request( $post_body ) { </span> <span>$args = array( 'body' => $post_body ); </span> <span>// make a POST request to the Google reCaptcha Server </span> <span>$request = wp_remote_post( 'https://www.google.com/recaptcha/api/verify', $args ); </span> <span>// get the request response body </span> <span>$response_body = wp_remote_retrieve_body( $request ); </span> <span>/** </span><span> * explode the response body and use the request_status </span><span> * <span>@see https://developers.google.com/recaptcha/docs/verify </span></span><span> */ </span> <span>$answers = explode( "\n", $response_body ); </span> <span>$request_status = trim( $answers[0] ); </span> <span>return $request_status; </span> <span>}</span>
On activation of the plugin, a CAPTCHA will be added to the WordPress comment form as show below.

Wrap Up
At the end of this tutorial, you should be able to add extra form fields to the comment form and implement just about any feature you wish to have in the comment system thanks to the filters and actions mentioned.
If you wish to use the plugin on your WordPress site or to study the code in-depth, download the plugin from GitHub.
Until I come your way again, happy coding!
Frequently Asked Questions (FAQs) about Integrating a CAPTCHA with the WordPress Comment Form
What is the Importance of Integrating a CAPTCHA with the WordPress Comment Form?
Integrating a CAPTCHA with the WordPress comment form is crucial for several reasons. Firstly, it helps to prevent spam comments, which can clutter your website and deter genuine users. Secondly, it adds an extra layer of security, protecting your site from bots and automated scripts. Lastly, it saves you time and resources that would otherwise be spent moderating and deleting spam comments.
How Can I Customize the CAPTCHA on My WordPress Comment Form?
Customizing the CAPTCHA on your WordPress comment form can be done through the settings of the CAPTCHA plugin you are using. Most plugins offer options to change the complexity, design, and layout of the CAPTCHA. Some even allow you to create your own custom CAPTCHA.
Are There Any Alternatives to CAPTCHA for WordPress Comment Forms?
Yes, there are several alternatives to CAPTCHA for WordPress comment forms. These include Akismet, a spam filtering service, and Honeypot, a method that tricks bots into revealing themselves by interacting with a hidden form field.
Can I Use CAPTCHA on Other Forms on My WordPress Site?
Absolutely. CAPTCHA can be integrated with any form on your WordPress site, including contact forms, registration forms, and login forms. This provides additional security and spam prevention across your entire site.
What Should I Do If CAPTCHA Is Not Working on My WordPress Comment Form?
If CAPTCHA is not working on your WordPress comment form, first check to ensure that the plugin is properly installed and activated. If the problem persists, try clearing your browser cache or disabling other plugins to see if there is a conflict.
How Can I Make CAPTCHA More Accessible for Users with Disabilities?
To make CAPTCHA more accessible, consider using an audio CAPTCHA or a logic-based CAPTCHA, which asks users to answer a simple question. Also, ensure that your CAPTCHA plugin complies with Web Content Accessibility Guidelines (WCAG).
Is CAPTCHA Effective Against All Types of Spam?
While CAPTCHA is highly effective at preventing bot-generated spam, it may not be as effective against human-generated spam. For this, consider using additional measures such as comment moderation or blacklisting certain words or IP addresses.
Does Integrating CAPTCHA with the WordPress Comment Form Affect Site Performance?
Integrating CAPTCHA with the WordPress comment form should not significantly affect site performance. However, like any plugin, it does use some resources. If you notice a slowdown, consider using a lightweight CAPTCHA plugin or optimizing your site’s performance in other ways.
Can I Integrate CAPTCHA with the WordPress Comment Form Without a Plugin?
While it is technically possible to integrate CAPTCHA with the WordPress comment form without a plugin, it requires advanced coding knowledge and is not recommended for most users. Using a plugin simplifies the process and ensures that the CAPTCHA is correctly implemented.
How Often Should I Update My CAPTCHA Plugin?
It’s recommended to update your CAPTCHA plugin whenever a new version is released. This ensures that you have the latest security features and that the plugin remains compatible with the latest version of WordPress.
The above is the detailed content of Integrating a CAPTCHA with the WordPress Comment Form. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undress AI Tool
Undress images for free

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

The main reasons why WordPress causes the surge in server CPU usage include plug-in problems, inefficient database query, poor quality of theme code, or surge in traffic. 1. First, confirm whether it is a high load caused by WordPress through top, htop or control panel tools; 2. Enter troubleshooting mode to gradually enable plug-ins to troubleshoot performance bottlenecks, use QueryMonitor to analyze the plug-in execution and delete or replace inefficient plug-ins; 3. Install cache plug-ins, clean up redundant data, analyze slow query logs to optimize the database; 4. Check whether the topic has problems such as overloading content, complex queries, or lack of caching mechanisms. It is recommended to use standard topic tests to compare and optimize the code logic. Follow the above steps to check and solve the location and solve the problem one by one.

Miniving JavaScript files can improve WordPress website loading speed by removing blanks, comments, and useless code. 1. Use cache plug-ins that support merge compression, such as W3TotalCache, enable and select compression mode in the "Minify" option; 2. Use a dedicated compression plug-in such as FastVelocityMinify to provide more granular control; 3. Manually compress JS files and upload them through FTP, suitable for users familiar with development tools. Note that some themes or plug-in scripts may conflict with the compression function, and you need to thoroughly test the website functions after activation.

Methods to optimize WordPress sites that do not rely on plug-ins include: 1. Use lightweight themes, such as Astra or GeneratePress, to avoid pile-up themes; 2. Manually compress and merge CSS and JS files to reduce HTTP requests; 3. Optimize images before uploading, use WebP format and control file size; 4. Configure.htaccess to enable browser cache, and connect to CDN to improve static resource loading speed; 5. Limit article revisions and regularly clean database redundant data.

TransientsAPI is a built-in tool in WordPress for temporarily storing automatic expiration data. Its core functions are set_transient, get_transient and delete_transient. Compared with OptionsAPI, transients supports setting time of survival (TTL), which is suitable for scenarios such as cache API request results and complex computing data. When using it, you need to pay attention to the uniqueness of key naming and namespace, cache "lazy deletion" mechanism, and the issue that may not last in the object cache environment. Typical application scenarios include reducing external request frequency, controlling code execution rhythm, and improving page loading performance.

The most effective way to prevent comment spam is to automatically identify and intercept it through programmatic means. 1. Use verification code mechanisms (such as Googler CAPTCHA or hCaptcha) to effectively distinguish between humans and robots, especially suitable for public websites; 2. Set hidden fields (Honeypot technology), and use robots to automatically fill in features to identify spam comments without affecting user experience; 3. Check the blacklist of comment content keywords, filter spam information through sensitive word matching, and pay attention to avoid misjudgment; 4. Judge the frequency and source IP of comments, limit the number of submissions per unit time and establish a blacklist; 5. Use third-party anti-spam services (such as Akismet, Cloudflare) to improve identification accuracy. Can be based on the website

When developing Gutenberg blocks, the correct method of enqueue assets includes: 1. Use register_block_type to specify the paths of editor_script, editor_style and style; 2. Register resources through wp_register_script and wp_register_style in functions.php or plug-in, and set the correct dependencies and versions; 3. Configure the build tool to output the appropriate module format and ensure that the path is consistent; 4. Control the loading logic of the front-end style through add_theme_support or enqueue_block_assets to ensure that the loading logic of the front-end style is ensured.

To add custom user fields, you need to select the extension method according to the platform and pay attention to data verification and permission control. Common practices include: 1. Use additional tables or key-value pairs of the database to store information; 2. Add input boxes to the front end and integrate with the back end; 3. Constrain format checks and access permissions for sensitive data; 4. Update interfaces and templates to support new field display and editing, while taking into account mobile adaptation and user experience.

robots.txt is crucial to the SEO of WordPress websites, and can guide search engines to crawl behavior, avoid duplicate content and improve efficiency. 1. Block system paths such as /wp-admin/ and /wp-includes/, but avoid accidentally blocking the /uploads/ directory; 2. Add Sitemap paths such as Sitemap: https://yourdomain.com/sitemap.xml to help search engines quickly discover site maps; 3. Limit /page/ and URLs with parameters to reduce crawler waste, but be careful not to block important archive pages; 4. Avoid common mistakes such as accidentally blocking the entire site, cache plug-in affecting updates, and ignoring the matching of mobile terminals and subdomains.
