0

I thank you in advance for your help. I am using Wordpress for about 2 years, but always avoiding SQL inside my scripts and looking for built-in functions to perform my goals.

To count the comments submitted by a specific user with $user->ID as id, I didn't find a built-in way, so I am using:

 global $wpdb;

        $count = $wpdb->get_var(
          'SELECT COUNT( comment_id ) FROM '. $wpdb->comments .'
          WHERE user_id = '.$user->ID.'
          AND comment_approved = "1"
          AND comment_type NOT IN ("pingback", "trackback" )'
        );

Actually my goal is to count number of all comments by a user on different posts. In other words, if a user commented 2 or more times on the same post, then only increment the $count variable by one .

Your help is appreciated.

1

If you want to count the number of posts the user commented on, you can try:

global $wpdb;

$sql = 'SELECT COUNT( comment_ID ) FROM ' . $wpdb->comments . '  
        WHERE user_id = %d 
        AND comment_approved = "1"
        AND comment_type NOT IN ("pingback", "trackback" )
        GROUP by comment_post_ID';

$count = $wpdb->get_var( $wpdb->prepare( $sql, $user->ID ) );

where we group by the post ID.

  • Yes it is exactly like counting the number of posts the user commented on. Your fist sentence is simple and adress the issue directly. I feel myself stupid. Thank you. I will test and come back here to give feedback. – whiteletters in blankpapers Jun 7 '13 at 19:42

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.