0

Hello I have multiauthor website and I need to create a condition to check if defined user ( no current user ) has comment on current post. Here is my code but I can not complete this

$userid = "444"; //this is the user that I need to Check if has comments on current post

$commenters = array("444", "544", "245", "453", "773", "990"); //here I need to get array of users ids who have comment in current post and check if user with the id 444 exist in this array
if(in_array($userid, $commenters)){ 
    echo " user with the id 444 have comment in current article";
}
else {
    echo "user with the id 444 have no comment in current article";
}

my problem is that how can I get array of users ids who have comment in current post or do you have any better alternative to code. Thanks for your attention

1 Answer 1

1

I need to create a condition to check if defined user ( no current user ) has comment on current post

For that purpose, you can just use get_comments() like so:

$post_id = get_the_ID(); // or just set a specific post ID
$user_id = 444;

// Get the total number of comments by the above user on the above post only.
$comment_count = get_comments( array(
    'post_id' => $post_id,
    'user_id' => $user_id,
    'count'   => true,
) );

if ( $comment_count ) {
    echo "user $user_id has <b>$comment_count comments</b> on post $post_id";
} else {
    echo "user $user_id has not commented on post $post_id";
}

how can I get array of users ids who have comment in current post

Just like the above example, you can also use get_comments() like so:

$comments = get_comments( array(
    'post_id' => $post_id,
) );

// Get the users who have commented on the above post and store their ID, if any,
// in $commenters.
$commenters = array();
foreach ( $comments as $comm ) {
    if ( $comm->user_id && ! in_array( $comm->user_id, $commenters ) ) {
        $commenters[] = $comm->user_id;
    }
}

if ( in_array( $user_id, $commenters ) ) {
    .. your code here.
} else ...
1

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.