Get comments for more than one post

The 'post_id' is converted to a positive integer in WP_Comment_Query, so you cannot successful pass anything else to get_comments().

You have to filter 'comments_clauses'. Here you can change the WHERE clause to use comment_post_ID IN ( $ids ) instead of comment_post_ID = $id.

I would use a static class as a wrapper for get_comments().

Sample code

/**
 * Query comments for multiple post IDs.
 */
class T5_Multipost_Comments
{
    /**
     * Post IDs, eg. array ( 1, 2, 40 )
     * @var array
     */
    protected static $post_ids = array ();

    /**
     * Called like get_comments.
     *
     * @param  array $args
     * @param  array $post_ids
     * @return array
     */
    public static function get( $args = array (), $post_ids = array () )
    {
        if ( array () !== $post_ids )
        {
            self::$post_ids = $post_ids;
            add_filter( 'comments_clauses', array ( __CLASS__, 'filter_where_clause' ) );
        }
        return get_comments( $args );
    }

    /**
     * Filter the comment query
     *
     * @param array $q Query parts, see WP_Comment_Query::query()
     *
     * @return array
     */
    public static function filter_where_clause( $q )
    {
        $ids       = implode( ', ', self::$post_ids );
        $_where_in = " AND comment_post_ID IN ( $ids )";

        if ( FALSE !== strpos( $q['where'], ' AND comment_post_ID =' ) )
        {
            $q['where'] = preg_replace(
                '~ AND comment_post_ID = \d+~',
                $_where_in,
                $q['where']
            );
        }
        else
        {
            $q['where'] .= $_where_in;
        }

        remove_filter( 'comments_clauses', array ( __CLASS__, 'filter_where_clause' ) );
        return $q;
    }
}

Usage example

$multi_comments = T5_Multipost_Comments::get(
    array ( 'number' => '14' ), // comment args
    array ( 149, 564, 151 )     // post IDs
);
print '<pre>' . htmlspecialchars( print_r( $multi_comments, TRUE ) ) . '</pre>';

Leave a Comment