1

How to Auto-Delete comment if contains certain string?

i tried with this but not work:

add_action( 'transition_comment_status', 'my_approve_comment_callback', 10, 3 );

function my_approve_comment_callback( $new_status, $old_status, $comment ) {
    if (strpos($comment->comment_content, 'dog') !== false) {
            wp_delete_comment( $comment->comment_ID, true );
    }       
}

I have also tried with:

wp_list_comments('callback=better_comment');

function better_comment($comment, $args, $depth) {
    if (strpos($comment->comment_content, 'dog') !== false) {
            wp_delete_comment( $comment->comment_ID, true );
    }   
}

Nothing work =(

1

It is better to use 'comment_post' action for this purpose, it is fired when the comment is saved in database:

add_action('comment_post', 'my_comment_post_callback', 10, 3);

function my_comment_post_callback($comment_id, $comment_approved, $commentdata) {
    if (strpos($commentdata['comment_content'], 'dog') !== false) {
        $post_url = get_permalink($commentdata['comment_post_ID']);
        wp_delete_comment($comment_id, true);
        wp_redirect($post_url);
        exit;
    }       
}
  • It work but when post comment with dog return white page, why? – J. Doe Cd Oct 22 '17 at 18:25
  • White page with this link "wp-comments-post.php#comment-" – J. Doe Cd Oct 22 '17 at 18:27
  • I have updated the example. When you delete the comment while it was processed for the first time, WordPress doesn't know how to return to the post this comment belongs too. If you want to redirect somewhere else, change the redirect URL. – Milan Petrovic Oct 22 '17 at 18:29
  • How could this be updated to accept multiple strings/words? – Pete Aug 24 at 9:29

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.