·

photo credit: Susan NYC via photopin cc

Prevent WordPress spam with a nonce and Akismet

You might struggle something when preventing spam on your WordPress blog. Sure, the built-in post-types of WordPress might already have some spam-protection (like nonces and/or Akismet), but what if you are creating your own post-types? Or you have some exotic submission-form that is not using any post-type at all? Well, in those cases you can fairly simple add some of that juicy spam-protection without all too much trouble.

Nonce

The first line of defence is a nonce. You might already have seen these before. A nonce in WordPress is a ‘number used once’. It prevents form from being misused by checking for things like the referrer and time for example. Adding a nonce to your field is very simple, it just requires one function you must embed in your form:

This function generates something like the following HTML:

Now in the piece of code where you are about to save all submitted data in the database you can add the following check:

That’s just how easy you can use nonces in your site.

Akismet

Another nice approach that might not be familiar with some of you is to use what’s already there: Akismet. If you are currently using the Akismet WordPress plugin to prevent spam comments, you can already make use of this plugin to check any kind of content or form submission for spam. I first read about this method in this article. The approach is fairly simple: just use the static Akismet::http_post() -method to check with the Akismet server if your form submission contains spam. A simple method for this could look something like this:

In conclusion

You see that it’s very easy to add two lines of defence in the battle against spam. Without too much hassle you can protect your own forms and custom post-types from being clogged up with spam. If you have any suggestions, tips, comments or more approaches on how to prevent spam on your blog, please let share the knowledge in the comments below.

Special thanks go out to Birgir Erlendsson for pointing out the Akismet-method.

Visitors give this article an average rating of 5.0 out of 5.

How would you rate this article?

Leave a Reply