comments - How to check, if user commented before, on comment_post action?

admin2025-06-05  3

I want check, if user commented post, in comment_post action. So i make this:

function checkUserComment( $comment_ID ) {

    $comment = get_comment( $comment_ID );
    $postID = $comment->comment_post_ID;
    $authorID = $comment->user_id;

    // If user commented this post already, don't update post meta.
    if( get_comments( array( 'post_id' => $postID, 'user_id' => $authorID ) ) )
        return;

    update_post_meta($postID, 'testMeta', 'testValue');

}

add_action( 'comment_post', 'checkUserComment', 10, 2 );

It must doesn't update post_meta if user comments first time. But it updates post_meta anyway.

I want check, if user commented post, in comment_post action. So i make this:

function checkUserComment( $comment_ID ) {

    $comment = get_comment( $comment_ID );
    $postID = $comment->comment_post_ID;
    $authorID = $comment->user_id;

    // If user commented this post already, don't update post meta.
    if( get_comments( array( 'post_id' => $postID, 'user_id' => $authorID ) ) )
        return;

    update_post_meta($postID, 'testMeta', 'testValue');

}

add_action( 'comment_post', 'checkUserComment', 10, 2 );

It must doesn't update post_meta if user comments first time. But it updates post_meta anyway.

Share Improve this question edited Dec 23, 2018 at 12:31 wpdev asked Dec 23, 2018 at 11:05 wpdevwpdev 5492 gold badges13 silver badges28 bronze badges 4
  • To narrow the problem you have to check each variable values, e.g., by echoing it. – Max Yudin Commented Dec 23, 2018 at 11:15
  • I checked all variables and print all them. Also tried is_array() and !empty() but same. I wonder, when action check it? After comment submisson or before? – wpdev Commented Dec 23, 2018 at 11:25
  • And what is the problem exactly? You say it doesn’t work. How? – Krzysiek Dróżdż Commented Dec 23, 2018 at 11:59
  • Updated question. – wpdev Commented Dec 23, 2018 at 12:32
Add a comment  | 

1 Answer 1

Reset to default 1

From the WordPress Codex:

comment_post is an action triggered immediately after a comment is inserted into the database.

Instead, I think what you want to try is to hook into preprocess_comment and not comment_post.

转载请注明原文地址:http://conceptsofalgorithm.com/Algorithm/1749072083a316113.html

最新回复(0)