Get all commenters on a post

I’m a little unclear as to exactly the final data you’re looking for. You said “array form”, but that’s not specific enough.

So based on your code snippet, this code will provide you an array of all unique commenter user IDs.

The code is essentially the same as yours, but I’ve combined a few parts together as they don’t need to be their own separate PHP statement – they can be put straight into the Comment Query.

$cq = new \WP_Comment_Query();
$comments = $cq->query(
    array(
        'post_id'    => get_the_ID(),
        'status'     => 'approve',
        'author__in' => get_users(
            array(
                'role__in' => [ 'author', 'subscriber' ],
                'fields'   => 'ID'
            )
        )
    )
);

$all_comment_user_ids = array_map( function ( $comment ) {
    return $comment[ 'user_id' ];
}, $comments );

$total_comments = count( $comments );
$unique_commenters = array_unique( $all_comment_user_ids );
$total_unique_commenters = count( $unique_commenters );

Your query itself was fine… you just had to post-process the results.

  • the array_map goes through each comment result and pulls out the user_id and creates a new array containing only the user IDs.
  • then we use array_unique to reduce the array to only unique values.

Leave a Comment