Search code examples
phpwordpresscomments

Get all comments on a post by an array of users


I'm trying to get all the comments from a post by an array of users.

This is what I'd like to be able to do:

$user_ids = array(10, 22, 41, 80);
$post_id = 57;

$args = array (
    'number'   => -1,
    'user_id'  => $user_ids,
    'post_id'  => $post_id,
    'status'   => 'approve',
    'order'    => 'DESC'
);
$comments = get_comments( $args );

Now obviously this doesn't work, but that's what I'd like to do. Is there any other way to achieve this? Maybe using a custom select?


Solution

  • I've built a WPDB query based on the query method of WP_Comment_Query class. And doing the sanitization based on this forum post.

    global $wpdb;
    
    // Sanitize
    $post = '1148';
    $post = absint($post);
    
    // Sanitize
    $a = '2'; // User One
    $b = '3'; // User Two
    $user_ids = array_map( 'absint', array( $a, $b ) );
    $user_ids = implode( ', ', $user_ids );
    
    $query = "SELECT * FROM $wpdb->comments 
            WHERE comment_post_ID = $post 
            AND user_id IN ($user_ids) 
            AND comment_approved = 1
            ORDER BY comment_date DESC";
    $comments = $wpdb->get_results( $query );