It is easy to stop most WordPress comment spam instantly with one small change to your theme’s functions.php. This is one of my favourite WordPress functions and I use it on all my setups.

This code snippet works by blocking comments from being added offsite or indirectly and not from the comment box on your webpage. Most spammers try to automate their ‘workload’ and try to exploit WordPress functions that allow you to manage comments or add posts via the WordPress API’s.

Just to prove this works - take a look at your spam comments now and mentally calculate your daily average of new spam comments. Then after adding this code to your functions.php file wait for 24 hours - if your spam comments are not down or close to zero you’ve done something wrong.

The role of WordPress Functions.php

Your functions.php file is the place to add snippets of code just like this. It’s found inside your theme folder and the code here runs before your site starts to load. Remember to keep a copy incase you update or replace your theme, this is because the functions.php file is unique to the active theme.

Stop WordPress Comment Spam

Go to your theme folder and open functions.php and insert this code

//Block Referal URL exploit for Comments
function verify\_comment\_referer() {
if (!wp\_get\_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', 'verify\_comment_referer');

Do you like this? Did this work for you?

Tags: Security

Read more from my blog for an introduction and quick tips on developing in Hugo or UCTD.

Meet the author

Photo for Damien Saunders
Damien Saunders
An experienced management consultant and business leader interested in digital transformation, product centred design and scaled agile. If I'm not writing about living with UCTD (an autoimmune disease), I'm probably listening to music, reading a book or learning more about wine.
Find our more about me.