How to Prevent Spam from WordPress Contact Forms: Tips and Tricks

Home » Snippets » How to Prevent Spam from WordPress Contact Forms: Tips and Tricks

Created with:



Creator: WPTurbo Team

Customize with WPTurbo AI

Add Snippet To Project

New Project
Add To Existing Project

As a website owner, it’s always a good idea to have a contact form on your site to make it easy for visitors to get in touch with you. But you might have noticed that sometimes those contact forms attract spam messages – and nobody wants to waste time sorting through those. In this article, we’ll show you some methods to help you stop spam from your WordPress contact form and keep your inbox manageable. Let’s dive in.

					function wpturbo_prevent_form_spam() {
    if( !empty( $_POST ) ) {
        $spam_keywords = array( 'viagra', 'cialis', 'insurance', 'gambling', 'free money' );
        foreach( $spam_keywords as $keyword ) {
            if ( stripos( $_POST['message'], $keyword ) !== false ) {
                wp_die( 'Your message has been flagged as spam.' );
add_action( 'wp_footer', 'wpturbo_prevent_form_spam' );

The above code snippet provides a solution for preventing spam messages from the WordPress contact form. The function wpturbo_prevent_form_spam() checks if any POST data is submitted and then searches for specific spam keywords. If any of the keywords are found in the message field, the function terminates the processing of the form and outputs a custom spam message.

The $spam_keywords array contains the keywords to search for in the message. You can add or remove keywords from this array as needed to prevent the specific types of spam that you are receiving. These keywords are checked against the message submitted by the user using the stripos() function, which checks if a given string contains a specific substring. The stripos() function is used instead of strpos() because it is case-insensitive, making it more effective in detecting variations of the keywords, such as "VIAGRA" or "ViAgRA", for example.

If any of the spam keywords are found in the message, the function uses the wp_die() function to immediately stop the processing of the form and display a custom spam message. The wp_die() function outputs an error message and terminates the current request, preventing any further execution of the code. This provides an effective means of preventing spam messages from being submitted through the WordPress contact form.

Finally, the add_action() function is used to hook the wpturbo_prevent_form_spam() function into the wp_footer action. This ensures that the spam check is performed on every page of the website, regardless of whether or not a contact form is present. This helps to prevent spam bots from finding and submitting spam messages through the contact form from different pages on your website.

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