Using WordPress Akismet Plugin to Check Spam

Whether you’re developing a custom contact form, comment or testimonial section in your WordPress site, you will need a strong anti-spam solution to protect yourself from bombardment of Spam content. Who else can give you better protection than inbuilt Akismet plugin in WordPress.

The PHP function uses Akismet plugin to check for spam content, just drop this PHP code in your functions.php in your active WordPress theme directory, and call it whenever you will need to check user submitted content for spam. Just make sure Akismet plugin is active.

PHP
1234567891011121314151617181920212223242526272829

function is_spam_akismet($args){
	global $akismet_api_host, $akismet_api_port;
	$query['user_ip'] 		= preg_replace( '/[^0-9., ]/', '', $_SERVER['REMOTE_ADDR'] );
	$query['user_agent'] 	= (isset( $_SERVER['HTTP_USER_AGENT'] )) ? $_SERVER['HTTP_USER_AGENT'] : '';
	$query['referrer'] 		= (isset( $_SERVER['HTTP_REFERER'] )) ? $_SERVER['HTTP_REFERER'] : '';
	$query['blog'] 			= get_option( 'home' );
	$query['blog_lang'] 	= get_locale(); // default 'en_US'
	$query['blog_charset'] 	= get_option( 'blog_charset' );
	$query['comment_type'] 	= 'forum-post'; //For more info http://bit.ly/2bVOMay
	$query['comment_content'] = $args["post_content"];
	$query['permalink'] 	= $args['referrer'];
	$query['comment_author'] = $args["user_name"];
	$query['comment_author_email'] = $args["user_email"];
	//$query['is_test']  = "1";  // uncomment this when testing spam detection
	//$query['comment_author']  = "viagra-test-123";  // uncomment this to test spam detection
	$query_string = http_build_query($query);
	$spam = false;
	if ( is_callable( array( 'Akismet', 'http_post' ) ) ) { //Akismet v3.0+
		$response = Akismet::http_post( $query_string, 'comment-check' );
	} else {
		$response = akismet_http_post( $query_string, $akismet_api_host,
			'/1.1/comment-check', $akismet_api_port );
	}
	if ( 'true' == $response[1] ) {
		$spam = true;
	}
	return $spam;
}

Usage

Let’s say you want to check for spam in content submitted by a user :

PHP
123456
$args["post_content"] = $_POST["content"];
$args["user_name"] = $_POST["sender_name"];
$args["user_email"] = $_POST["sender_email"];
if(is_spam_akismet($args)){
	//do something with spam
}

This should return true if the submitted content is found to be spam by Akismet server.