Nobody like spam! Unless, of course, It’s Fried :). In this tutorial, I’m going to show you two WordPress hacks using .htaccess file and function.php file to stop spammy comments. If you have a WordPress blog, then you’re probably irritated with the amount of daily spam comments. Yes, you must be already using akismet, but this is another trick to stop comment spam.
Most of the spammers don’t even go to your blog to post spammy comments. They use a dedicated software or script to do this work. So in this post, we’re going to look at denying comment posting to no referrer requests, if the comment isn’t actually coming from your site, then it gets blocked.
How to Stop Comment Spam
Here’s the code snippets you need to work with:
For security purpose, please backup your .htaccess and function.php files before doing these hacks.
Hack using .htaccess file
Simply paste the following code on your .htaccess file, located at the root of your WordPress install.
RewriteEngine On RewriteCond %{REQUEST_METHOD} POST RewriteCond %{REQUEST_URI} .wp-comments-post\.php* RewriteCond %{HTTP_REFERER} !.*yourdomain.com.* [OR] RewriteCond %{HTTP_USER_AGENT} ^$ RewriteRule (.*) ^http://%{REMOTE_ADDR}/$ [R=301,L]
NOTE: Don’t forget to specify your domain url on line 4.
Hack using PHP file
Simply add the following code on your theme’s function.php file.
function check_referrer() { if (!isset($_SERVER['HTTP_REFERER']) || $_SERVER['HTTP_REFERER'] == "") { wp_die( __('You cannot post comment at this time, may be you need to enable referrers in your browser.') ); } } add_action('check_comment_flood', 'check_referrer');
Both the hacks work exactly the same. It checks the referrer’s request. If the request doesn’t come directly from your blog, then it gets redirected (.htaccess code) or show a blank page (PHP code) and the comment will not be posted.