How to Deny Comment Requests with No Referrer in WordPress

Home » Snippets » How to Deny Comment Requests with No Referrer in WordPress
0

Created with:

Visibility: 

public

Creator: WPTurbo Team

Customize with WPTurbo AI
X

Add Snippet To Project

New Project
Add To Existing Project

If you’ve been running a blog or website for any length of time, you’ve undoubtedly encountered spam comments. One of the ways spammers try to get their comments onto your site is by spoofing the referrer header. By doing this, they can make it look like their comment is coming from a legitimate source, when in reality it’s just spam. Fortunately, there’s a simple way to combat this – by denying comment no referrer requests. In this article, we’ll show you how to do just that.

					function wpturbo_deny_comment_no_referrer( $approved, $commentdata ) {
    if ( ! isset( $_SERVER['HTTP_REFERER'] ) ) {
        $approved = 'spam';
    }
    return $approved;
}
add_filter( 'pre_comment_approved', 'wpturbo_deny_comment_no_referrer', 10, 2 );
				

The above code snippet shows an example function for denying comment requests without a referrer. Referrer information is an HTTP header that identifies the address of the webpage where the comment came from. It is a security measure to prevent spam and other malicious activities.

This function is using the WordPress pre_comment_approved filter to intercept comment approval before it is saved to the database. It takes two parameters, $approved and $commentdata, and returns the updated $approved value.

Inside the function, we use an if statement to check if the HTTP_REFERER key is set in the $_SERVER superglobal. This key contains the referrer URL passed by the web browser. If it is not set, we set $approved to ‘spam’, effectively denying the comment.

if ( ! isset( $_SERVER['HTTP_REFERER'] ) ) {
    $approved = 'spam';
}

Finally, we return the updated $approved value to the pre_comment_approved filter.

return $approved;

To use this function, add the code snippet to your WordPress site’s functions.php file or as a new plugin. After that, comments without a referrer will be marked as spam and will not be displayed on your site.

Register an account to save your snippets or go Pro to get more features.