0

I would like to filter wordpress comment!!

I've just little knowledge about Php. I write a simple code to filter spam comment. But, I failed. Below my code! Can you please help me?

    add_action('pre_comment_on_post', 'comment_spam_pro');
function comment_spam_pro() {
    $cbox = $_POST["comment_field"];
    $spam = array('href','[url','spamword');    
    if(array_key_exists($spam,$cboc)) {
        wp_die('Spam Comment Detect!!');
    }
}
1
  • You have the option to moderate comments before they are being displayed to the public, make sure you have a appropriate options checked in your setting that are related to comments. Consider installing spam plugins (like akismet), they help reduce spam alot (read the documentation because not all site can use the free version, even if its available). Oct 20, 2021 at 13:23

1 Answer 1

1

As said in this comment, WordPress has some possibilities to moderate comments and some good plugins for spam prevention.

Nevertheless, if I understand you correctly you would like to prevent the post of comments before it gets to the database.

I think I've found a solution for that. Check out the code for your functions.php.

function preprocess_comment_spam( $commentdata ) {

    $spamwords = array( 'href', '[url', 'spamword' );

    foreach( $spamwords as $spam ) {

        if ( \strpos( $commentdata['comment_content'], $spam ) !== false ) {
            wp_die('Sorry, we detected some spam.'); // This is the Error Notice for Wordpress.
            /*return new WP_Error( 'spam_detected', __( 'Sorry, we detected some spam.' ), 403 );*/
        }
    }

    return $commentdata;
}
add_filter( 'preprocess_comment' , 'preprocess_comment_spam' );

I did not test the code, but it should work.

Here you have more informations about this filter: https://developer.wordpress.org/reference/hooks/preprocess_comment/

2
  • This function doesn't works for me! When I enter spam words it show "There has been a critical error on this website." Oct 21, 2021 at 2:50
  • I just tried it and it works. The critical error appears because of the WP_Error function that is called if spam is detected. If it's a normal comment, everything works fine, if not, we get a critical error. You can change that to something else.
    – propz
    Oct 21, 2021 at 13:39

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.