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.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
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 :

1
2
3
4
5
6
7
$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.

  1. Akismet plugin is very powerful to overcome comment spam..terimakasih for a tutorial how to use the Akismet plugin

     Reply
  2. Awesome plugin, nice har work

     Reply
  3. قالب وردپرس

    thank you for introducing this awesome plugin :)

     Reply
Message Type : Question Comment ?
  • Question : Can include code, jsFiddle, codePen etc using Markdown Syntax.
  • Comment : Short comments and questions.