Akismet Plugin and Custom Forms

Added on November 2nd, 2009

If for some reason you use a custom coded form on your WordPress powered site somewhere and need the submitted content to be checked for spam then you can do it quite easily with the Akismet plugin that comes with WordPress.

Having said that I’d still recommend using one of the contact form plugins if you can as they usually come with spam checking options.

If that however isn’t an option then I’ll show you how to add Akismet spam checking to your forms.

# Akismet
$c['user_ip'] = preg_replace('/[^0-9., ]/', '', $_SERVER['REMOTE_ADDR']);
$c['user_agent'] = $_SERVER['HTTP_USER_AGENT'];
$c['referrer'] = $_SERVER['HTTP_REFERER'];
$c['blog'] = get_option('home');
$c['permalink'] = get_permalink();
$c['comment_type'] = 'contactform';
$c['comment_author'] = $_POST['contact_name'];
$c['comment_content'] = $_POST['contact_comment'];
# $c['comment_content']  = 'viagra-test-123';  # uncomment this to test spam detection

$ignore = array('HTTP_COOKIE');
foreach($_SERVER as $key => $value)
  if(!in_array($key, $ignore))
    $c["$key"] = $value;

$query_string = '';
foreach($c as $key => $data)
  $query_string .= $key . '=' . urlencode(stripslashes($data)) . '&';

# Feed Akismet the data
$response = akismet_http_post($query_string, $akismet_api_host, '/1.1/comment-check', $akismet_api_port);
if($response[1] == 'true')
{
  # Flagged as spam, so put your "You're a bad spammer" code here
}

Double check the $_POST values and see if they match the ones that you use in your form and you’re set. And of course you might want to write the “You’re a bad spammer” code as well, but that I leave up to your imagination.

Personally I just output an error message saying that the user/bot is trying to submit spam and that if that is not the case, that they can always contact me by email as well.

Go back


One reply to “Akismet Plugin and Custom Forms”


Akismet is a must if you are going to allow comments on your blog.