how to find user ids of all commenters in a post

Is there a function in wordpress that grabs all the users(user ids) who have commented on a post? I have the post id available.

Related posts

Leave a Reply

2 comments

  1. The get_comments() answer by Poulomi Nag is correct. This will be somewhat more efficient.

    global $wpdb, $post;
    $query = sprintf("SELECT user_id
                        FROM {$wpdb->comments}
                        JOIN {$wpdb->posts} ON {$wpdb->posts}.ID = {$wpdb->comments}.comment_post_ID
                        WHERE comment_post_ID = %d
                        AND comment_approved = '1'",
                      $post->ID);
    $authors = $wpdb->get_col($query);
    $authors = array_unique($authors);
    $authors = array_diff($authors,array('0')); // Remove those where users are not registered
    

    Another alternative is to use WP_Comment_Query
    http://core.trac.wordpress.org/browser/branches/3.2/wp-includes/comment.php#L186

  2. The following snippet is one way of doing it:

    $args = array(
    'status' => 'approve',
    'post_id' => get_the_ID()
    );
    $comments = get_comments( $args );
    foreach( $comments as $comment )
        echo $comment->user_id;
    

    The user IDs of course should be used for better use than just echoing.