3 * Comment API: WP_Comment_Query class
11 * Core class used for querying comments.
15 * @see WP_Comment_Query::__construct() for accepted arguments.
17 class WP_Comment_Query {
20 * SQL for database query.
29 * Metadata query container
33 * @var object WP_Meta_Query
35 public $meta_query = false;
38 * Metadata query clauses.
44 protected $meta_query_clauses;
53 protected $sql_clauses = array(
65 * Stored after the {@see 'comments_clauses'} filter is run on the compiled WHERE sub-clauses.
71 protected $filtered_where_clause;
74 * Date query container
78 * @var object WP_Date_Query
80 public $date_query = false;
83 * Query vars set by the user.
92 * Default values for query vars.
98 public $query_var_defaults;
101 * List of comments located by the query.
110 * The amount of found comments for the current query.
116 public $found_comments = 0;
119 * The number of pages.
125 public $max_num_pages = 0;
128 * Make private/protected methods readable for backward compatibility.
133 * @param callable $name Method to call.
134 * @param array $arguments Arguments to pass when calling.
135 * @return mixed|false Return value of the callback, false otherwise.
137 public function __call( $name, $arguments ) {
138 if ( 'get_search_sql' === $name ) {
139 return call_user_func_array( array( $this, $name ), $arguments );
147 * Sets up the comment query, based on the query vars passed.
150 * @since 4.4.0 `$parent__in` and `$parent__not_in` were added.
151 * @since 4.4.0 Order by `comment__in` was added. `$update_comment_meta_cache`, `$no_found_rows`,
152 * `$hierarchical`, and `$update_comment_post_cache` were added.
153 * @since 4.5.0 Introduced the `$author_url` argument.
154 * @since 4.6.0 Introduced the `$cache_domain` argument.
157 * @param string|array $query {
158 * Optional. Array or query string of comment query parameters. Default empty.
160 * @type string $author_email Comment author email address. Default empty.
161 * @type string $author_url Comment author URL. Default empty.
162 * @type array $author__in Array of author IDs to include comments for. Default empty.
163 * @type array $author__not_in Array of author IDs to exclude comments for. Default empty.
164 * @type array $comment__in Array of comment IDs to include. Default empty.
165 * @type array $comment__not_in Array of comment IDs to exclude. Default empty.
166 * @type bool $count Whether to return a comment count (true) or array of
167 * comment objects (false). Default false.
168 * @type array $date_query Date query clauses to limit comments by. See WP_Date_Query.
170 * @type string $fields Comment fields to return. Accepts 'ids' for comment IDs
171 * only or empty for all fields. Default empty.
172 * @type int $ID Currently unused.
173 * @type array $include_unapproved Array of IDs or email addresses of users whose unapproved
174 * comments will be returned by the query regardless of
175 * `$status`. Default empty.
176 * @type int $karma Karma score to retrieve matching comments for.
178 * @type string $meta_key Include comments with a matching comment meta key.
180 * @type string $meta_value Include comments with a matching comment meta value.
181 * Requires `$meta_key` to be set. Default empty.
182 * @type array $meta_query Meta query clauses to limit retrieved comments by.
183 * See WP_Meta_Query. Default empty.
184 * @type int $number Maximum number of comments to retrieve.
185 * Default null (no limit).
186 * @type int $offset Number of comments to offset the query. Used to build
187 * LIMIT clause. Default 0.
188 * @type bool $no_found_rows Whether to disable the `SQL_CALC_FOUND_ROWS` query.
190 * @type string|array $orderby Comment status or array of statuses. To use 'meta_value'
191 * or 'meta_value_num', `$meta_key` must also be defined.
192 * To sort by a specific `$meta_query` clause, use that
193 * clause's array key. Accepts 'comment_agent',
194 * 'comment_approved', 'comment_author',
195 * 'comment_author_email', 'comment_author_IP',
196 * 'comment_author_url', 'comment_content', 'comment_date',
197 * 'comment_date_gmt', 'comment_ID', 'comment_karma',
198 * 'comment_parent', 'comment_post_ID', 'comment_type',
199 * 'user_id', 'comment__in', 'meta_value', 'meta_value_num',
200 * the value of $meta_key, and the array keys of
201 * `$meta_query`. Also accepts false, an empty array, or
202 * 'none' to disable `ORDER BY` clause.
203 * Default: 'comment_date_gmt'.
204 * @type string $order How to order retrieved comments. Accepts 'ASC', 'DESC'.
206 * @type int $parent Parent ID of comment to retrieve children of.
208 * @type array $parent__in Array of parent IDs of comments to retrieve children for.
210 * @type array $parent__not_in Array of parent IDs of comments *not* to retrieve
211 * children for. Default empty.
212 * @type array $post_author__in Array of author IDs to retrieve comments for.
214 * @type array $post_author__not_in Array of author IDs *not* to retrieve comments for.
216 * @type int $post_ID Currently unused.
217 * @type int $post_id Limit results to those affiliated with a given post ID.
219 * @type array $post__in Array of post IDs to include affiliated comments for.
221 * @type array $post__not_in Array of post IDs to exclude affiliated comments for.
223 * @type int $post_author Post author ID to limit results by. Default empty.
224 * @type string|array $post_status Post status or array of post statuses to retrieve
225 * affiliated comments for. Pass 'any' to match any value.
227 * @type string $post_type Post type or array of post types to retrieve affiliated
228 * comments for. Pass 'any' to match any value. Default empty.
229 * @type string $post_name Post name to retrieve affiliated comments for.
231 * @type int $post_parent Post parent ID to retrieve affiliated comments for.
233 * @type string $search Search term(s) to retrieve matching comments for.
235 * @type string $status Comment status to limit results by. Accepts 'hold'
236 * (`comment_status=0`), 'approve' (`comment_status=1`),
237 * 'all', or a custom comment status. Default 'all'.
238 * @type string|array $type Include comments of a given type, or array of types.
239 * Accepts 'comment', 'pings' (includes 'pingback' and
240 * 'trackback'), or anycustom type string. Default empty.
241 * @type array $type__in Include comments from a given array of comment types.
243 * @type array $type__not_in Exclude comments from a given array of comment types.
245 * @type int $user_id Include comments for a specific user ID. Default empty.
246 * @type bool|string $hierarchical Whether to include comment descendants in the results.
247 * 'threaded' returns a tree, with each comment's children
248 * stored in a `children` property on the `WP_Comment`
249 * object. 'flat' returns a flat array of found comments plus
250 * their children. Pass `false` to leave out descendants.
251 * The parameter is ignored (forced to `false`) when
252 * `$fields` is 'ids' or 'counts'. Accepts 'threaded',
253 * 'flat', or false. Default: false.
254 * @type string $cache_domain Unique cache key to be produced when this query is stored in
255 * an object cache. Default is 'core'.
256 * @type bool $update_comment_meta_cache Whether to prime the metadata cache for found comments.
258 * @type bool $update_comment_post_cache Whether to prime the cache for comment posts.
262 public function __construct( $query = '' ) {
263 $this->query_var_defaults = array(
264 'author_email' => '',
267 'author__not_in' => '',
268 'include_unapproved' => '',
272 'comment__not_in' => '',
276 'no_found_rows' => true,
281 'parent__not_in' => '',
282 'post_author__in' => '',
283 'post_author__not_in' => '',
287 'post__not_in' => '',
296 'type__not_in' => '',
303 'date_query' => null, // See WP_Date_Query
304 'hierarchical' => false,
305 'cache_domain' => 'core',
306 'update_comment_meta_cache' => true,
307 'update_comment_post_cache' => false,
310 if ( ! empty( $query ) ) {
311 $this->query( $query );
316 * Parse arguments passed to the comment query with default query parameters.
318 * @since 4.2.0 Extracted from WP_Comment_Query::query().
322 * @param string|array $query WP_Comment_Query arguments. See WP_Comment_Query::__construct()
324 public function parse_query( $query = '' ) {
325 if ( empty( $query ) ) {
326 $query = $this->query_vars;
329 $this->query_vars = wp_parse_args( $query, $this->query_var_defaults );
332 * Fires after the comment query vars have been parsed.
336 * @param WP_Comment_Query &$this The WP_Comment_Query instance (passed by reference).
338 do_action_ref_array( 'parse_comment_query', array( &$this ) );
342 * Sets up the WordPress query for retrieving comments.
345 * @since 4.1.0 Introduced 'comment__in', 'comment__not_in', 'post_author__in',
346 * 'post_author__not_in', 'author__in', 'author__not_in', 'post__in',
347 * 'post__not_in', 'include_unapproved', 'type__in', and 'type__not_in'
348 * arguments to $query_vars.
349 * @since 4.2.0 Moved parsing to WP_Comment_Query::parse_query().
352 * @param string|array $query Array or URL query string of parameters.
353 * @return array|int List of comments, or number of comments when 'count' is passed as a query var.
355 public function query( $query ) {
356 $this->query_vars = wp_parse_args( $query );
357 return $this->get_comments();
361 * Get a list of comments matching the query vars.
366 * @global wpdb $wpdb WordPress database abstraction object.
368 * @return int|array List of comments or number of found comments if `$count` argument is true.
370 public function get_comments() {
373 $this->parse_query();
376 $this->meta_query = new WP_Meta_Query();
377 $this->meta_query->parse_query_vars( $this->query_vars );
380 * Fires before comments are retrieved.
384 * @param WP_Comment_Query &$this Current instance of WP_Comment_Query, passed by reference.
386 do_action_ref_array( 'pre_get_comments', array( &$this ) );
388 // Reparse query vars, in case they were modified in a 'pre_get_comments' callback.
389 $this->meta_query->parse_query_vars( $this->query_vars );
390 if ( ! empty( $this->meta_query->queries ) ) {
391 $this->meta_query_clauses = $this->meta_query->get_sql( 'comment', $wpdb->comments, 'comment_ID', $this );
394 // $args can include anything. Only use the args defined in the query_var_defaults to compute the key.
395 $key = md5( serialize( wp_array_slice_assoc( $this->query_vars, array_keys( $this->query_var_defaults ) ) ) );
396 $last_changed = wp_cache_get( 'last_changed', 'comment' );
397 if ( ! $last_changed ) {
398 $last_changed = microtime();
399 wp_cache_set( 'last_changed', $last_changed, 'comment' );
402 $cache_key = "get_comments:$key:$last_changed";
403 $cache_value = wp_cache_get( $cache_key, 'comment' );
404 if ( false === $cache_value ) {
405 $comment_ids = $this->get_comment_ids();
406 if ( $comment_ids ) {
407 $this->set_found_comments();
410 $cache_value = array(
411 'comment_ids' => $comment_ids,
412 'found_comments' => $this->found_comments,
414 wp_cache_add( $cache_key, $cache_value, 'comment' );
416 $comment_ids = $cache_value['comment_ids'];
417 $this->found_comments = $cache_value['found_comments'];
420 if ( $this->found_comments && $this->query_vars['number'] ) {
421 $this->max_num_pages = ceil( $this->found_comments / $this->query_vars['number'] );
424 // If querying for a count only, there's nothing more to do.
425 if ( $this->query_vars['count'] ) {
426 // $comment_ids is actually a count in this case.
427 return intval( $comment_ids );
430 $comment_ids = array_map( 'intval', $comment_ids );
432 if ( 'ids' == $this->query_vars['fields'] ) {
433 $this->comments = $comment_ids;
434 return $this->comments;
437 _prime_comment_caches( $comment_ids, $this->query_vars['update_comment_meta_cache'] );
439 // Fetch full comment objects from the primed cache.
440 $_comments = array();
441 foreach ( $comment_ids as $comment_id ) {
442 if ( $_comment = get_comment( $comment_id ) ) {
443 $_comments[] = $_comment;
447 // Prime comment post caches.
448 if ( $this->query_vars['update_comment_post_cache'] ) {
449 $comment_post_ids = array();
450 foreach ( $_comments as $_comment ) {
451 $comment_post_ids[] = $_comment->comment_post_ID;
454 _prime_post_caches( $comment_post_ids, false, false );
458 * Filters the comment query results.
462 * @param array $results An array of comments.
463 * @param WP_Comment_Query &$this Current instance of WP_Comment_Query, passed by reference.
465 $_comments = apply_filters_ref_array( 'the_comments', array( $_comments, &$this ) );
467 // Convert to WP_Comment instances
468 $comments = array_map( 'get_comment', $_comments );
470 if ( $this->query_vars['hierarchical'] ) {
471 $comments = $this->fill_descendants( $comments );
474 $this->comments = $comments;
475 return $this->comments;
479 * Used internally to get a list of comment IDs matching the query vars.
484 * @global wpdb $wpdb WordPress database abstraction object.
486 protected function get_comment_ids() {
489 // Assemble clauses related to 'comment_approved'.
490 $approved_clauses = array();
492 // 'status' accepts an array or a comma-separated string.
493 $status_clauses = array();
494 $statuses = $this->query_vars['status'];
495 if ( ! is_array( $statuses ) ) {
496 $statuses = preg_split( '/[\s,]+/', $statuses );
499 // 'any' overrides other statuses.
500 if ( ! in_array( 'any', $statuses ) ) {
501 foreach ( $statuses as $status ) {
504 $status_clauses[] = "comment_approved = '0'";
508 $status_clauses[] = "comment_approved = '1'";
513 $status_clauses[] = "( comment_approved = '0' OR comment_approved = '1' )";
517 $status_clauses[] = $wpdb->prepare( "comment_approved = %s", $status );
522 if ( ! empty( $status_clauses ) ) {
523 $approved_clauses[] = '( ' . implode( ' OR ', $status_clauses ) . ' )';
527 // User IDs or emails whose unapproved comments are included, regardless of $status.
528 if ( ! empty( $this->query_vars['include_unapproved'] ) ) {
529 $include_unapproved = $this->query_vars['include_unapproved'];
531 // Accepts arrays or comma-separated strings.
532 if ( ! is_array( $include_unapproved ) ) {
533 $include_unapproved = preg_split( '/[\s,]+/', $include_unapproved );
536 $unapproved_ids = $unapproved_emails = array();
537 foreach ( $include_unapproved as $unapproved_identifier ) {
538 // Numeric values are assumed to be user ids.
539 if ( is_numeric( $unapproved_identifier ) ) {
540 $approved_clauses[] = $wpdb->prepare( "( user_id = %d AND comment_approved = '0' )", $unapproved_identifier );
542 // Otherwise we match against email addresses.
544 $approved_clauses[] = $wpdb->prepare( "( comment_author_email = %s AND comment_approved = '0' )", $unapproved_identifier );
549 // Collapse comment_approved clauses into a single OR-separated clause.
550 if ( ! empty( $approved_clauses ) ) {
551 if ( 1 === count( $approved_clauses ) ) {
552 $this->sql_clauses['where']['approved'] = $approved_clauses[0];
554 $this->sql_clauses['where']['approved'] = '( ' . implode( ' OR ', $approved_clauses ) . ' )';
558 $order = ( 'ASC' == strtoupper( $this->query_vars['order'] ) ) ? 'ASC' : 'DESC';
560 // Disable ORDER BY with 'none', an empty array, or boolean false.
561 if ( in_array( $this->query_vars['orderby'], array( 'none', array(), false ), true ) ) {
563 } elseif ( ! empty( $this->query_vars['orderby'] ) ) {
564 $ordersby = is_array( $this->query_vars['orderby'] ) ?
565 $this->query_vars['orderby'] :
566 preg_split( '/[,\s]/', $this->query_vars['orderby'] );
568 $orderby_array = array();
569 $found_orderby_comment_ID = false;
570 foreach ( $ordersby as $_key => $_value ) {
575 if ( is_int( $_key ) ) {
583 if ( ! $found_orderby_comment_ID && in_array( $_orderby, array( 'comment_ID', 'comment__in' ) ) ) {
584 $found_orderby_comment_ID = true;
587 $parsed = $this->parse_orderby( $_orderby );
593 if ( 'comment__in' === $_orderby ) {
594 $orderby_array[] = $parsed;
598 $orderby_array[] = $parsed . ' ' . $this->parse_order( $_order );
601 // If no valid clauses were found, order by comment_date_gmt.
602 if ( empty( $orderby_array ) ) {
603 $orderby_array[] = "$wpdb->comments.comment_date_gmt $order";
606 // To ensure determinate sorting, always include a comment_ID clause.
607 if ( ! $found_orderby_comment_ID ) {
608 $comment_ID_order = '';
610 // Inherit order from comment_date or comment_date_gmt, if available.
611 foreach ( $orderby_array as $orderby_clause ) {
612 if ( preg_match( '/comment_date(?:_gmt)*\ (ASC|DESC)/', $orderby_clause, $match ) ) {
613 $comment_ID_order = $match[1];
618 // If no date-related order is available, use the date from the first available clause.
619 if ( ! $comment_ID_order ) {
620 foreach ( $orderby_array as $orderby_clause ) {
621 if ( false !== strpos( 'ASC', $orderby_clause ) ) {
622 $comment_ID_order = 'ASC';
624 $comment_ID_order = 'DESC';
632 if ( ! $comment_ID_order ) {
633 $comment_ID_order = 'DESC';
636 $orderby_array[] = "$wpdb->comments.comment_ID $comment_ID_order";
639 $orderby = implode( ', ', $orderby_array );
641 $orderby = "$wpdb->comments.comment_date_gmt $order";
644 $number = absint( $this->query_vars['number'] );
645 $offset = absint( $this->query_vars['offset'] );
647 if ( ! empty( $number ) ) {
649 $limits = 'LIMIT ' . $offset . ',' . $number;
651 $limits = 'LIMIT ' . $number;
655 if ( $this->query_vars['count'] ) {
656 $fields = 'COUNT(*)';
658 $fields = "$wpdb->comments.comment_ID";
661 $post_id = absint( $this->query_vars['post_id'] );
662 if ( ! empty( $post_id ) ) {
663 $this->sql_clauses['where']['post_id'] = $wpdb->prepare( 'comment_post_ID = %d', $post_id );
666 // Parse comment IDs for an IN clause.
667 if ( ! empty( $this->query_vars['comment__in'] ) ) {
668 $this->sql_clauses['where']['comment__in'] = "$wpdb->comments.comment_ID IN ( " . implode( ',', wp_parse_id_list( $this->query_vars['comment__in'] ) ) . ' )';
671 // Parse comment IDs for a NOT IN clause.
672 if ( ! empty( $this->query_vars['comment__not_in'] ) ) {
673 $this->sql_clauses['where']['comment__not_in'] = "$wpdb->comments.comment_ID NOT IN ( " . implode( ',', wp_parse_id_list( $this->query_vars['comment__not_in'] ) ) . ' )';
676 // Parse comment parent IDs for an IN clause.
677 if ( ! empty( $this->query_vars['parent__in'] ) ) {
678 $this->sql_clauses['where']['parent__in'] = 'comment_parent IN ( ' . implode( ',', wp_parse_id_list( $this->query_vars['parent__in'] ) ) . ' )';
681 // Parse comment parent IDs for a NOT IN clause.
682 if ( ! empty( $this->query_vars['parent__not_in'] ) ) {
683 $this->sql_clauses['where']['parent__not_in'] = 'comment_parent NOT IN ( ' . implode( ',', wp_parse_id_list( $this->query_vars['parent__not_in'] ) ) . ' )';
686 // Parse comment post IDs for an IN clause.
687 if ( ! empty( $this->query_vars['post__in'] ) ) {
688 $this->sql_clauses['where']['post__in'] = 'comment_post_ID IN ( ' . implode( ',', wp_parse_id_list( $this->query_vars['post__in'] ) ) . ' )';
691 // Parse comment post IDs for a NOT IN clause.
692 if ( ! empty( $this->query_vars['post__not_in'] ) ) {
693 $this->sql_clauses['where']['post__not_in'] = 'comment_post_ID NOT IN ( ' . implode( ',', wp_parse_id_list( $this->query_vars['post__not_in'] ) ) . ' )';
696 if ( '' !== $this->query_vars['author_email'] ) {
697 $this->sql_clauses['where']['author_email'] = $wpdb->prepare( 'comment_author_email = %s', $this->query_vars['author_email'] );
700 if ( '' !== $this->query_vars['author_url'] ) {
701 $this->sql_clauses['where']['author_url'] = $wpdb->prepare( 'comment_author_url = %s', $this->query_vars['author_url'] );
704 if ( '' !== $this->query_vars['karma'] ) {
705 $this->sql_clauses['where']['karma'] = $wpdb->prepare( 'comment_karma = %d', $this->query_vars['karma'] );
708 // Filtering by comment_type: 'type', 'type__in', 'type__not_in'.
710 'IN' => array_merge( (array) $this->query_vars['type'], (array) $this->query_vars['type__in'] ),
711 'NOT IN' => (array) $this->query_vars['type__not_in'],
714 $comment_types = array();
715 foreach ( $raw_types as $operator => $_raw_types ) {
716 $_raw_types = array_unique( $_raw_types );
718 foreach ( $_raw_types as $type ) {
720 // An empty translates to 'all', for backward compatibility
727 $comment_types[ $operator ][] = "''";
731 $comment_types[ $operator ][] = "'pingback'";
732 $comment_types[ $operator ][] = "'trackback'";
736 $comment_types[ $operator ][] = $wpdb->prepare( '%s', $type );
741 if ( ! empty( $comment_types[ $operator ] ) ) {
742 $types_sql = implode( ', ', $comment_types[ $operator ] );
743 $this->sql_clauses['where']['comment_type__' . strtolower( str_replace( ' ', '_', $operator ) ) ] = "comment_type $operator ($types_sql)";
747 $parent = $this->query_vars['parent'];
748 if ( $this->query_vars['hierarchical'] && ! $parent ) {
752 if ( '' !== $parent ) {
753 $this->sql_clauses['where']['parent'] = $wpdb->prepare( 'comment_parent = %d', $parent );
756 if ( is_array( $this->query_vars['user_id'] ) ) {
757 $this->sql_clauses['where']['user_id'] = 'user_id IN (' . implode( ',', array_map( 'absint', $this->query_vars['user_id'] ) ) . ')';
758 } elseif ( '' !== $this->query_vars['user_id'] ) {
759 $this->sql_clauses['where']['user_id'] = $wpdb->prepare( 'user_id = %d', $this->query_vars['user_id'] );
762 // Falsy search strings are ignored.
763 if ( strlen( $this->query_vars['search'] ) ) {
764 $search_sql = $this->get_search_sql(
765 $this->query_vars['search'],
766 array( 'comment_author', 'comment_author_email', 'comment_author_url', 'comment_author_IP', 'comment_content' )
769 // Strip leading 'AND'.
770 $this->sql_clauses['where']['search'] = preg_replace( '/^\s*AND\s*/', '', $search_sql );
773 // If any post-related query vars are passed, join the posts table.
774 $join_posts_table = false;
775 $plucked = wp_array_slice_assoc( $this->query_vars, array( 'post_author', 'post_name', 'post_parent' ) );
776 $post_fields = array_filter( $plucked );
778 if ( ! empty( $post_fields ) ) {
779 $join_posts_table = true;
780 foreach ( $post_fields as $field_name => $field_value ) {
781 // $field_value may be an array.
782 $esses = array_fill( 0, count( (array) $field_value ), '%s' );
783 $this->sql_clauses['where'][ $field_name ] = $wpdb->prepare( " {$wpdb->posts}.{$field_name} IN (" . implode( ',', $esses ) . ')', $field_value );
787 // 'post_status' and 'post_type' are handled separately, due to the specialized behavior of 'any'.
788 foreach ( array( 'post_status', 'post_type' ) as $field_name ) {
790 if ( ! empty( $this->query_vars[ $field_name ] ) ) {
791 $q_values = $this->query_vars[ $field_name ];
792 if ( ! is_array( $q_values ) ) {
793 $q_values = explode( ',', $q_values );
796 // 'any' will cause the query var to be ignored.
797 if ( in_array( 'any', $q_values, true ) || empty( $q_values ) ) {
801 $join_posts_table = true;
803 $esses = array_fill( 0, count( $q_values ), '%s' );
804 $this->sql_clauses['where'][ $field_name ] = $wpdb->prepare( " {$wpdb->posts}.{$field_name} IN (" . implode( ',', $esses ) . ")", $q_values );
808 // Comment author IDs for an IN clause.
809 if ( ! empty( $this->query_vars['author__in'] ) ) {
810 $this->sql_clauses['where']['author__in'] = 'user_id IN ( ' . implode( ',', wp_parse_id_list( $this->query_vars['author__in'] ) ) . ' )';
813 // Comment author IDs for a NOT IN clause.
814 if ( ! empty( $this->query_vars['author__not_in'] ) ) {
815 $this->sql_clauses['where']['author__not_in'] = 'user_id NOT IN ( ' . implode( ',', wp_parse_id_list( $this->query_vars['author__not_in'] ) ) . ' )';
818 // Post author IDs for an IN clause.
819 if ( ! empty( $this->query_vars['post_author__in'] ) ) {
820 $join_posts_table = true;
821 $this->sql_clauses['where']['post_author__in'] = 'post_author IN ( ' . implode( ',', wp_parse_id_list( $this->query_vars['post_author__in'] ) ) . ' )';
824 // Post author IDs for a NOT IN clause.
825 if ( ! empty( $this->query_vars['post_author__not_in'] ) ) {
826 $join_posts_table = true;
827 $this->sql_clauses['where']['post_author__not_in'] = 'post_author NOT IN ( ' . implode( ',', wp_parse_id_list( $this->query_vars['post_author__not_in'] ) ) . ' )';
832 if ( $join_posts_table ) {
833 $join .= "JOIN $wpdb->posts ON $wpdb->posts.ID = $wpdb->comments.comment_post_ID";
836 if ( ! empty( $this->meta_query_clauses ) ) {
837 $join .= $this->meta_query_clauses['join'];
839 // Strip leading 'AND'.
840 $this->sql_clauses['where']['meta_query'] = preg_replace( '/^\s*AND\s*/', '', $this->meta_query_clauses['where'] );
842 if ( ! $this->query_vars['count'] ) {
843 $groupby = "{$wpdb->comments}.comment_ID";
847 if ( ! empty( $this->query_vars['date_query'] ) && is_array( $this->query_vars['date_query'] ) ) {
848 $this->date_query = new WP_Date_Query( $this->query_vars['date_query'], 'comment_date' );
849 $this->sql_clauses['where']['date_query'] = preg_replace( '/^\s*AND\s*/', '', $this->date_query->get_sql() );
852 $where = implode( ' AND ', $this->sql_clauses['where'] );
854 $pieces = array( 'fields', 'join', 'where', 'orderby', 'limits', 'groupby' );
856 * Filters the comment query clauses.
860 * @param array $pieces A compacted array of comment query clauses.
861 * @param WP_Comment_Query &$this Current instance of WP_Comment_Query, passed by reference.
863 $clauses = apply_filters_ref_array( 'comments_clauses', array( compact( $pieces ), &$this ) );
865 $fields = isset( $clauses[ 'fields' ] ) ? $clauses[ 'fields' ] : '';
866 $join = isset( $clauses[ 'join' ] ) ? $clauses[ 'join' ] : '';
867 $where = isset( $clauses[ 'where' ] ) ? $clauses[ 'where' ] : '';
868 $orderby = isset( $clauses[ 'orderby' ] ) ? $clauses[ 'orderby' ] : '';
869 $limits = isset( $clauses[ 'limits' ] ) ? $clauses[ 'limits' ] : '';
870 $groupby = isset( $clauses[ 'groupby' ] ) ? $clauses[ 'groupby' ] : '';
872 $this->filtered_where_clause = $where;
875 $where = 'WHERE ' . $where;
879 $groupby = 'GROUP BY ' . $groupby;
883 $orderby = "ORDER BY $orderby";
887 if ( ! $this->query_vars['no_found_rows'] ) {
888 $found_rows = 'SQL_CALC_FOUND_ROWS';
891 $this->sql_clauses['select'] = "SELECT $found_rows $fields";
892 $this->sql_clauses['from'] = "FROM $wpdb->comments $join";
893 $this->sql_clauses['groupby'] = $groupby;
894 $this->sql_clauses['orderby'] = $orderby;
895 $this->sql_clauses['limits'] = $limits;
897 $this->request = "{$this->sql_clauses['select']} {$this->sql_clauses['from']} {$where} {$this->sql_clauses['groupby']} {$this->sql_clauses['orderby']} {$this->sql_clauses['limits']}";
899 if ( $this->query_vars['count'] ) {
900 return intval( $wpdb->get_var( $this->request ) );
902 $comment_ids = $wpdb->get_col( $this->request );
903 return array_map( 'intval', $comment_ids );
908 * Populates found_comments and max_num_pages properties for the current
909 * query if the limit clause was used.
914 * @global wpdb $wpdb WordPress database abstraction object.
916 private function set_found_comments() {
919 if ( $this->query_vars['number'] && ! $this->query_vars['no_found_rows'] ) {
921 * Filters the query used to retrieve found comment count.
925 * @param string $found_comments_query SQL query. Default 'SELECT FOUND_ROWS()'.
926 * @param WP_Comment_Query $comment_query The `WP_Comment_Query` instance.
928 $found_comments_query = apply_filters( 'found_comments_query', 'SELECT FOUND_ROWS()', $this );
930 $this->found_comments = (int) $wpdb->get_var( $found_comments_query );
935 * Fetch descendants for located comments.
937 * Instead of calling `get_children()` separately on each child comment, we do a single set of queries to fetch
938 * the descendant trees for all matched top-level comments.
942 * @param array $comments Array of top-level comments whose descendants should be filled in.
945 protected function fill_descendants( $comments ) {
949 0 => wp_list_pluck( $comments, 'comment_ID' ),
953 * The WHERE clause for the descendant query is the same as for the top-level
954 * query, minus the `parent`, `parent__in`, and `parent__not_in` sub-clauses.
956 $_where = $this->filtered_where_clause;
957 $exclude_keys = array( 'parent', 'parent__in', 'parent__not_in' );
958 foreach ( $exclude_keys as $exclude_key ) {
959 if ( isset( $this->sql_clauses['where'][ $exclude_key ] ) ) {
960 $clause = $this->sql_clauses['where'][ $exclude_key ];
962 // Strip the clause as well as any adjacent ANDs.
963 $pattern = '|(?:AND)?\s*' . $clause . '\s*(?:AND)?|';
964 $_where_parts = preg_split( $pattern, $_where );
967 $_where_parts = array_filter( array_map( 'trim', $_where_parts ) );
969 // Reassemble with an AND.
970 $_where = implode( ' AND ', $_where_parts );
974 $key = md5( serialize( wp_array_slice_assoc( $this->query_vars, array_keys( $this->query_var_defaults ) ) ) );
975 $last_changed = wp_cache_get( 'last_changed', 'comment' );
976 if ( ! $last_changed ) {
977 $last_changed = microtime();
978 wp_cache_set( 'last_changed', $last_changed, 'comment' );
981 // Fetch an entire level of the descendant tree at a time.
984 // Parent-child relationships may be cached. Only query for those that are not.
985 $child_ids = $uncached_parent_ids = array();
986 $_parent_ids = $levels[ $level ];
987 foreach ( $_parent_ids as $parent_id ) {
988 $cache_key = "get_comment_child_ids:$parent_id:$key:$last_changed";
989 $parent_child_ids = wp_cache_get( $cache_key, 'comment' );
990 if ( false !== $parent_child_ids ) {
991 $child_ids = array_merge( $child_ids, $parent_child_ids );
993 $uncached_parent_ids[] = $parent_id;
997 if ( $uncached_parent_ids ) {
998 $where = 'WHERE ' . $_where . ' AND comment_parent IN (' . implode( ',', array_map( 'intval', $uncached_parent_ids ) ) . ')';
999 $level_comments = $wpdb->get_results( "SELECT $wpdb->comments.comment_ID, $wpdb->comments.comment_parent {$this->sql_clauses['from']} {$where} {$this->sql_clauses['groupby']} ORDER BY comment_date_gmt ASC, comment_ID ASC" );
1001 // Cache parent-child relationships.
1002 $parent_map = array_fill_keys( $uncached_parent_ids, array() );
1003 foreach ( $level_comments as $level_comment ) {
1004 $parent_map[ $level_comment->comment_parent ][] = $level_comment->comment_ID;
1005 $child_ids[] = $level_comment->comment_ID;
1008 foreach ( $parent_map as $parent_id => $children ) {
1009 $cache_key = "get_comment_child_ids:$parent_id:$key:$last_changed";
1010 wp_cache_set( $cache_key, $children, 'comment' );
1015 $levels[ $level ] = $child_ids;
1016 } while ( $child_ids );
1018 // Prime comment caches for non-top-level comments.
1019 $descendant_ids = array();
1020 for ( $i = 1; $i < count( $levels ); $i++ ) {
1021 $descendant_ids = array_merge( $descendant_ids, $levels[ $i ] );
1024 _prime_comment_caches( $descendant_ids, $this->query_vars['update_comment_meta_cache'] );
1026 // Assemble a flat array of all comments + descendants.
1027 $all_comments = $comments;
1028 foreach ( $descendant_ids as $descendant_id ) {
1029 $all_comments[] = get_comment( $descendant_id );
1032 // If a threaded representation was requested, build the tree.
1033 if ( 'threaded' === $this->query_vars['hierarchical'] ) {
1034 $threaded_comments = $ref = array();
1035 foreach ( $all_comments as $k => $c ) {
1036 $_c = get_comment( $c->comment_ID );
1038 // If the comment isn't in the reference array, it goes in the top level of the thread.
1039 if ( ! isset( $ref[ $c->comment_parent ] ) ) {
1040 $threaded_comments[ $_c->comment_ID ] = $_c;
1041 $ref[ $_c->comment_ID ] = $threaded_comments[ $_c->comment_ID ];
1043 // Otherwise, set it as a child of its parent.
1046 $ref[ $_c->comment_parent ]->add_child( $_c );
1047 $ref[ $_c->comment_ID ] = $ref[ $_c->comment_parent ]->get_child( $_c->comment_ID );
1051 // Set the 'populated_children' flag, to ensure additional database queries aren't run.
1052 foreach ( $ref as $_ref ) {
1053 $_ref->populated_children( true );
1056 $comments = $threaded_comments;
1058 $comments = $all_comments;
1065 * Used internally to generate an SQL string for searching across multiple columns
1070 * @global wpdb $wpdb WordPress database abstraction object.
1072 * @param string $string
1073 * @param array $cols
1076 protected function get_search_sql( $string, $cols ) {
1079 $like = '%' . $wpdb->esc_like( $string ) . '%';
1081 $searches = array();
1082 foreach ( $cols as $col ) {
1083 $searches[] = $wpdb->prepare( "$col LIKE %s", $like );
1086 return ' AND (' . implode(' OR ', $searches) . ')';
1090 * Parse and sanitize 'orderby' keys passed to the comment query.
1095 * @global wpdb $wpdb WordPress database abstraction object.
1097 * @param string $orderby Alias for the field to order by.
1098 * @return string|false Value to used in the ORDER clause. False otherwise.
1100 protected function parse_orderby( $orderby ) {
1103 $allowed_keys = array(
1107 'comment_author_email',
1108 'comment_author_IP',
1109 'comment_author_url',
1121 if ( ! empty( $this->query_vars['meta_key'] ) ) {
1122 $allowed_keys[] = $this->query_vars['meta_key'];
1123 $allowed_keys[] = 'meta_value';
1124 $allowed_keys[] = 'meta_value_num';
1127 $meta_query_clauses = $this->meta_query->get_clauses();
1128 if ( $meta_query_clauses ) {
1129 $allowed_keys = array_merge( $allowed_keys, array_keys( $meta_query_clauses ) );
1133 if ( $orderby == $this->query_vars['meta_key'] || $orderby == 'meta_value' ) {
1134 $parsed = "$wpdb->commentmeta.meta_value";
1135 } elseif ( $orderby == 'meta_value_num' ) {
1136 $parsed = "$wpdb->commentmeta.meta_value+0";
1137 } elseif ( $orderby == 'comment__in' ) {
1138 $comment__in = implode( ',', array_map( 'absint', $this->query_vars['comment__in'] ) );
1139 $parsed = "FIELD( {$wpdb->comments}.comment_ID, $comment__in )";
1140 } elseif ( in_array( $orderby, $allowed_keys ) ) {
1142 if ( isset( $meta_query_clauses[ $orderby ] ) ) {
1143 $meta_clause = $meta_query_clauses[ $orderby ];
1144 $parsed = sprintf( "CAST(%s.meta_value AS %s)", esc_sql( $meta_clause['alias'] ), esc_sql( $meta_clause['cast'] ) );
1146 $parsed = "$wpdb->comments.$orderby";
1154 * Parse an 'order' query variable and cast it to ASC or DESC as necessary.
1159 * @param string $order The 'order' query variable.
1160 * @return string The sanitized 'order' query variable.
1162 protected function parse_order( $order ) {
1163 if ( ! is_string( $order ) || empty( $order ) ) {
1167 if ( 'ASC' === strtoupper( $order ) ) {