Take the 2-minute tour ×
WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. It's 100% free, no registration required.

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.

share|improve this question

2 Answers 2

up vote 1 down vote accepted

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

share|improve this answer
    
Thanks Mridul ! :) –  Poulomi Nag Oct 15 '12 at 10:16
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

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.

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.