Redirection after submitting duplicate comment

The question:

Sometimes, when posting comments, duplicate comments appear (hosting is very busy ). im use add_filter('comment_flood_filter', '__return_false');

How to not display “Duplicate comment detected” but redirect to post? Without adding a duplicate comment to the database.

In other words – count only one comment, and if the same is found, then redirect to the post.

The Solutions:

Below are the methods you can try. The first solution is probably the best. Try others if the first one doesn’t work. Senior developers aren’t just copying/pasting – they read the methods carefully & apply them wisely to each case.

Method 1

This answer lets you redirect back to the originating post instead of dieing with the flood message. It’s a PHP class, not just a simple function. You can copy-paste this into your functions.php as-is, or set it up in whichever way you like to manage your custom code.

  • assumes PHP 5.3+
  • it also contains code for duplicate comments which your original question mentioned, but then you edited it out. You can remove this bit by deleting the line that contains add_action( 'comment_duplicate_trigger,
class Handle_Comment_Flood {

    private $comment_post_id;

    public function __construct() {
        add_filter( 'preprocess_comment', [ $this, 'capture_post_id' ], 10, 1 );

        add_action( 'comment_flood_trigger', [ $this, 'handle_redirect' ], 0, 0 );
        add_action( 'comment_duplicate_trigger', [ $this, 'handle_redirect' ], 0, 0 );
    }

    public function capture_post_id( $comment ) {
        $this->comment_post_id = isset( $comment[ 'comment_post_ID' ] ) ? $comment[ 'comment_post_ID' ] : 0;
        return $comment;
    }

    public function handle_redirect() {
        if ( !empty( $this->comment_post_id ) ) {
            wp_safe_redirect( get_permalink( get_post( $this->comment_post_id ) ) );
            die();
        }
    }
}

new Handle_Comment_Flood();


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Comment