0

To return comments for a specific user, I use the code below:

$arg = array('user_id' => $userID); 
$coms= get_comments( $arg ); 

How can I modify the arguments of this function so that I get comments for a group of users (get only comments for specific 2 or 3 users)?

The arguemnt 'user_id' should be an integer, I cant find a way to pass an array.

Or should I use PHP or SQL to get my goal?

Your time and consideration of this issue is appreciated.

  • Take a look at this question: wordpress.stackexchange.com/questions/55164/… – Nicolai Jul 2 '13 at 13:06
  • 1
    No, that won't work...read the answers! :) ok, you realized that yourself :D The answers are for post_id's but it shouldn't be that hard to make it work for user_id's. – Nicolai Jul 2 '13 at 13:08
  • I totally agree with you. by analogy to post_id, I should resolve the issue which is not simple as I thought at the beginning. Thank you very much for the link. – whiteletters in blankpapers Jul 2 '13 at 13:13
3

You can try to modify the query using the comments_clauses filter:

$args = array( 'user_id' => 0 );
add_filter( 'comments_clauses', 'custom_comments_clauses');
$comments = get_comments( $args );
remove_filter( 'comments_clauses', 'custom_comments_clauses');

function custom_comments_clauses( $clauses ){
    $clauses['where'] = str_replace( 'user_id = 0', 'user_id IN (1, 2, 3)', $clauses['where'] );
    return $clauses;
}

Update:

You could also add a custom parameter, my_user_ids, to the query like this:

$args = array( 'user_id' => 0, 'my_user_ids' => array(1,2,3) );

add_filter( 'comments_clauses', 'custom_comments_clauses', 99, 2 );
$comments = get_comments( $args );
remove_filter( 'comments_clauses', 'custom_comments_clauses', 99, 2 );

function custom_comments_clauses( $clauses, $query ){
    if( isset( $query->query_vars['user_id'] ) && isset( $query->query_vars['my_user_ids'] ) ){ 
        $user_id = $query->query_vars['user_id'];
        $user_ids = $query->query_vars['my_user_ids'];
        if( count( $user_ids ) > 0 ){
            $from = sprintf( 'user_id = %d', $user_id );
            $to   = sprintf( 'user_id IN (%s)', join( ',', $user_ids ) );
            $clauses['where'] = str_replace( $from, $to, $clauses['where'] );
        }
    }
    return $clauses;
}

where $my_user_ids is an array of user ID's.

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.