1

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.

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
  • 1
    Aside from taht this isn't really a secure way of doing it sprintf/$wpdb->prepare, in which way is it "more efficient"? Please elaborate. And btw: get_comments() calls WP_Comment_Query internally. – kaiser Oct 15 '12 at 15:45
  • I think the sprintf should be more efficient for this case. $wpdb->prepare does some internal security checks which are only needed if the ID comes from user input(bad code if it does) – Mridul Aggarwal Oct 15 '12 at 16:40
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.

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.