Halloween Sale 15% off Ends in See the plans
PHP

Check Your Own Form Submissions With Akismet

Adds a wpide_akismet_is_spam() helper that sends a name, email and message from any custom form to Akismet and tells you whether it looks like spam, so your hand-built forms get the same protection as comments.

Don’t have WPIDE yet? Install it on your site

Code

if ( ! function_exists( 'wpide_akismet_is_spam' ) ) {
    function wpide_akismet_is_spam( array $fields ) {
        if ( ! class_exists( 'Akismet' ) || ! Akismet::get_api_key() ) {
            return false;
        }

        $request = array(
            'blog'                 => home_url(),
            'blog_lang'            => get_locale(),
            'blog_charset'         => get_option( 'blog_charset' ),
            'user_ip'              => isset( $_SERVER['REMOTE_ADDR'] ) ? sanitize_text_field( wp_unslash( $_SERVER['REMOTE_ADDR'] ) ) : '',
            'user_agent'           => isset( $_SERVER['HTTP_USER_AGENT'] ) ? sanitize_text_field( wp_unslash( $_SERVER['HTTP_USER_AGENT'] ) ) : '',
            'referrer'             => wp_get_raw_referer() ? wp_get_raw_referer() : '',
            'permalink'            => wp_get_referer() ? wp_get_referer() : home_url( '/' ),
            'comment_type'         => 'contact-form',
            'comment_author'       => isset( $fields['name'] ) ? (string) $fields['name'] : '',
            'comment_author_email' => isset( $fields['email'] ) ? (string) $fields['email'] : '',
            'comment_content'      => isset( $fields['message'] ) ? (string) $fields['message'] : '',
        );

        $response = Akismet::http_post( Akismet::build_query( $request ), 'comment-check' );

        return is_array( $response ) && isset( $response[1] ) && 'true' === trim( $response[1] );
    }
}

Notes

Call wpide_akismet_is_spam( array( 'name' => ..., 'email' => ..., 'message' => ... ) ) in your form handler; it returns false when Akismet is missing or unreachable, so submissions are never lost.

How to add this snippet

  1. Install WPIDE on your WordPress site (it is free) and open Code Snippets.
  2. Use snippet above adds it from the library in one click. Or copy the code into a new snippet with the same code type.
  3. It is added inactive: review the code and settings, then switch it on.

Have a snippet worth sharing?

Publish it to the library from WPIDE or right here. Sign in with any WordPress site that runs WPIDE, free or Pro. Public snippets are reviewed by the WPIDE team before they appear.

Which site should get this snippet?

Enter the address of your WordPress site. WPIDE opens there in a new tab with the snippet ready to review and save.

Remembered in this browser only, so you are asked once.

Report this snippet

Tell the WPIDE team what is wrong: broken code, something harmful, spam or copied work.