WordPress: Stop spam posts programmatically

I have an image sharing site built on WordPress and recently I’ve had a lot of bots registering a user and creating a spam post with links to various sites.

After installing WP-reCAPTCHA the numbers have reduced but there are still ‘attacks’ every hour or so.

Read More

I’m trying to handle this programmatically now, by hooking into wp_insert_post_data (which is called whenever a post/revision is saved). I inspect the post data and if it contains a link I remove the post’s content and set the status to draft so that it isn’t published.

But it’s still a nuisance to delete spam users and posts from the back end.

Is there a better hook I can use to stop the saving of the post even happening? i.e. can I reject the call to save the post?

Here is the code I’m currently using:

function block_spam_posts($data, $postarr) {

    // if the post contains a link, set it to draft status
    $post_content = $data['post_content'];
    if (strpos($post_content,'http') !== false) {
        $data['post_content'] = 'Post data removed by anti-spam measures.';
        $data['post_status'] = 'draft';
    }
}
add_filter('wp_insert_post_data', 'block_spam_posts',1,2);

Thanks for your help.

Related posts

Leave a Reply

1 comment