WordPress: Count all comments by user then count meta data on comments

I have set some custom meta against certain comments for users using this function: add_comment_meta( $wp_comment_id, 'accepted', true );

What I want to do is show for each user on their profile /author/username is how many of these special comments they have so for example if a user made 20 comments and 5 had this meta data of accepted equalling true then the value would be 5.

Read More

How could I do this? Thanks.

Related posts

Leave a Reply

2 comments

  1. I’m assuming this is the latest version of wordpress. You can see the database schema diagram here: http://codex.wordpress.org/images/9/9e/WP3.0-ERD.png

    I haven’t tested this, but something LIKE this should do the trick:

    <?php
    getCommentCount('John', 'accepted', 'true');
    
    function getCommentCount($author_name, $meta_key, $meta_value){
        if(empty($author_name)){
            return;
        }
    
        $author_name    = trim($author_name);
        $sql            = 'SELECT count(*) FROM ' . $wpdb->comments . ' comments '
                        . ' INNER JOIN ' . $wpdb->commentmeta . ' meta ON comments.comment_ID = meta.comment_id '
                        . ' WHERE comments.comment_author = %s AND meta.meta_key = %s ANd meta.value = %s ';
    
        $commentCount   = $wpdb->get_var($wpdb->prepare($sql, $author_name, $meta_key, $meta_value));
    
        return $commentCount;
    }
    
  2. i dont understand what do you mean by “count meta data”…
    whice value in meta data.. do you mean the user’s meta data or the comment.

    Anyhow – in order to count comments by a specific user you can…
    Put this code in your functions php

    function countUserComments($userID) {
        $args = array(
            'user_id' => $userID
        );
        $comments = get_comments( $args );
        echo count($comments);
    }
    

    The you can use it anywhere where you got a user id available to you like so

    <?php echo countUserComments($user->ID); ?>
    

    .

    Hope this helps anyone 😉
    Cheers, Sagive