Fight spam in WordPress’ comments with Google reCaptcha

Fight spam in WordPress’ comments with Google reCaptcha

“There’s nothing in your spam queue at the moment” is a magic phrase when it’s about moderating comments of a WordPress blog.

The plugin Akismet offers some protection against spam, however it’s never been as efficient as I wish it could be. Though I activated the option “Silently discard the worst and most pervasive spam so I never see it.”, there was always ridiculously obvious spams in the moderation queue.

I started looking for ways to add Google reCaptcha to the blog’s comment form after I noticed that there wasn’t spam from the contact form reaching my mailbox, it happened after I started to use Google’s reCaptcha. I know there are plugins to do it, but I decided to take the challenge to find a solution.

The mu-plugin resulting from this challenge is available in this Github repository: WP Google reCaptcha for comments.

This solution works against spam bots, because it checks catpcha’s response after the comment form is submitted, and it relies on the efficiency of Google reCaptcha. Since January 11, when I last cleared the spam queue, my dashboard continues displaying the message I highlighted in the image above that says no spam.

How to install

Upload the files to the folder wp-content/mu-plugins and edit your .htaccess to include the following lines:

<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteRule ^wp-comments-post\.php$ wp-content/mu-plugins/tps-google-recatpcha/wp-comments-post.php [NC,L]

It’s the RewriteRule that redirects the processing of the comment to the mu-plugin’s file tps-google-recatpcha/wp-comments-post.php instead of the default WordPress’ /wp-comments-post.php located in the root directory of WordPress.

How it works

The mu-plugin add the reCaptcha to the comment form on posts, and it validates the response after the comment is submitted. This is why bots are not able to bypass the validation: it happens in the server processing PHP code. Solutions that rely on JavaScript aren’t efficient against bots, because JavaScript can be disabled and bots don’t use browsers.

When a comment is submitted without a valid reCaptcha response, the mu-plugin redirects back to the post URL without allowing WordPress to be aware about the new comment, because it starts processing comments in the function wp_handle_comment_submission(). On the other hand the mu-plugin handles the new comment to WordPress when reCaptcha is solved correctly.

ReCaptcha is not included when a user is logged in the website. And the mu-plugin uses a validation with jQuery Validate to keep people from sending a comment without solving the reCaptcha.

2017-06-23T23:45:54+00:00 Fevereiro 2017|

Deixar Um Comentário