Limit comments per user per post

I use this code to limit the comments to 1 for registers users and works fine. The problem is that when i click to “go back” button in the browser i can comment again. Is there any effective way to limit the comments?

Thank you!

global $current_user, $post;
$args = array( 'user_id' => $current_user->ID, 'post_id' => $post->ID );
$usercomment = get_comments( $args );
if ( 1 <= count( $usercomment ) ) {
    echo 'disabled';
} else {
    comment_form();
}

Related posts

1 comment

  1. I think that hook pre_comment_approved should be perfect in this case.

    Something like this should do the job:

    function my_pre_comment_approved($approved, $commentdata) {
        // you can return 0, 1 or 'spam'
        if ( $commentdata['user_ID'] ) {
            $args = array(
                'user_id' => $commentdata['user_ID'],
                'post_id' => $commentdata['comment_post_ID']
            );
            $usercomment = get_comments( $args );
            if ( 1 <= count( $usercomment ) )
                return 0;
        }
        return $approved;
    }
    add_filter('pre_comment_approved', 'my_pre_comment_approved', 99, 2);
    

    Your filter should return:

    • 0 (i.e. ‘false’) if the comment should be disapproved
    • 1 (i.e. ‘true’) if the comment should be approved
    • 'spam' if the comment should be marked as spam

Comments are closed.