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 empty (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' );
399 $cache_key = "get_comments:$key:$last_changed";
400 $cache_value = wp_cache_get( $cache_key, 'comment' );
401 if ( false === $cache_value ) {
402 $comment_ids = $this->get_comment_ids();
403 if ( $comment_ids ) {
404 $this->set_found_comments();
407 $cache_value = array(
408 'comment_ids' => $comment_ids,
409 'found_comments' => $this->found_comments,
411 wp_cache_add( $cache_key, $cache_value, 'comment' );
413 $comment_ids = $cache_value['comment_ids'];
414 $this->found_comments = $cache_value['found_comments'];
417 if ( $this->found_comments && $this->query_vars['number'] ) {
418 $this->max_num_pages = ceil( $this->found_comments / $this->query_vars['number'] );
421 // If querying for a count only, there's nothing more to do.
422 if ( $this->query_vars['count'] ) {
423 // $comment_ids is actually a count in this case.
424 return intval( $comment_ids );
427 $comment_ids = array_map( 'intval', $comment_ids );
429 if ( 'ids' == $this->query_vars['fields'] ) {
430 $this->comments = $comment_ids;
431 return $this->comments;
434 _prime_comment_caches( $comment_ids, $this->query_vars['update_comment_meta_cache'] );
436 // Fetch full comment objects from the primed cache.
437 $_comments = array();
438 foreach ( $comment_ids as $comment_id ) {
439 if ( $_comment = get_comment( $comment_id ) ) {
440 $_comments[] = $_comment;
444 // Prime comment post caches.
445 if ( $this->query_vars['update_comment_post_cache'] ) {
446 $comment_post_ids = array();
447 foreach ( $_comments as $_comment ) {
448 $comment_post_ids[] = $_comment->comment_post_ID;
451 _prime_post_caches( $comment_post_ids, false, false );
455 * Filters the comment query results.
459 * @param array $results An array of comments.
460 * @param WP_Comment_Query &$this Current instance of WP_Comment_Query, passed by reference.
462 $_comments = apply_filters_ref_array( 'the_comments', array( $_comments, &$this ) );
464 // Convert to WP_Comment instances
465 $comments = array_map( 'get_comment', $_comments );
467 if ( $this->query_vars['hierarchical'] ) {
468 $comments = $this->fill_descendants( $comments );
471 $this->comments = $comments;
472 return $this->comments;
476 * Used internally to get a list of comment IDs matching the query vars.
481 * @global wpdb $wpdb WordPress database abstraction object.
483 protected function get_comment_ids() {
486 // Assemble clauses related to 'comment_approved'.
487 $approved_clauses = array();
489 // 'status' accepts an array or a comma-separated string.
490 $status_clauses = array();
491 $statuses = $this->query_vars['status'];
492 if ( ! is_array( $statuses ) ) {
493 $statuses = preg_split( '/[\s,]+/', $statuses );
496 // 'any' overrides other statuses.
497 if ( ! in_array( 'any', $statuses ) ) {
498 foreach ( $statuses as $status ) {
501 $status_clauses[] = "comment_approved = '0'";
505 $status_clauses[] = "comment_approved = '1'";
510 $status_clauses[] = "( comment_approved = '0' OR comment_approved = '1' )";
514 $status_clauses[] = $wpdb->prepare( "comment_approved = %s", $status );
519 if ( ! empty( $status_clauses ) ) {
520 $approved_clauses[] = '( ' . implode( ' OR ', $status_clauses ) . ' )';
524 // User IDs or emails whose unapproved comments are included, regardless of $status.
525 if ( ! empty( $this->query_vars['include_unapproved'] ) ) {
526 $include_unapproved = $this->query_vars['include_unapproved'];
528 // Accepts arrays or comma-separated strings.
529 if ( ! is_array( $include_unapproved ) ) {
530 $include_unapproved = preg_split( '/[\s,]+/', $include_unapproved );
533 $unapproved_ids = $unapproved_emails = array();
534 foreach ( $include_unapproved as $unapproved_identifier ) {
535 // Numeric values are assumed to be user ids.
536 if ( is_numeric( $unapproved_identifier ) ) {
537 $approved_clauses[] = $wpdb->prepare( "( user_id = %d AND comment_approved = '0' )", $unapproved_identifier );
539 // Otherwise we match against email addresses.
541 $approved_clauses[] = $wpdb->prepare( "( comment_author_email = %s AND comment_approved = '0' )", $unapproved_identifier );
546 // Collapse comment_approved clauses into a single OR-separated clause.
547 if ( ! empty( $approved_clauses ) ) {
548 if ( 1 === count( $approved_clauses ) ) {
549 $this->sql_clauses['where']['approved'] = $approved_clauses[0];
551 $this->sql_clauses['where']['approved'] = '( ' . implode( ' OR ', $approved_clauses ) . ' )';
555 $order = ( 'ASC' == strtoupper( $this->query_vars['order'] ) ) ? 'ASC' : 'DESC';
557 // Disable ORDER BY with 'none', an empty array, or boolean false.
558 if ( in_array( $this->query_vars['orderby'], array( 'none', array(), false ), true ) ) {
560 } elseif ( ! empty( $this->query_vars['orderby'] ) ) {
561 $ordersby = is_array( $this->query_vars['orderby'] ) ?
562 $this->query_vars['orderby'] :
563 preg_split( '/[,\s]/', $this->query_vars['orderby'] );
565 $orderby_array = array();
566 $found_orderby_comment_ID = false;
567 foreach ( $ordersby as $_key => $_value ) {
572 if ( is_int( $_key ) ) {
580 if ( ! $found_orderby_comment_ID && in_array( $_orderby, array( 'comment_ID', 'comment__in' ) ) ) {
581 $found_orderby_comment_ID = true;
584 $parsed = $this->parse_orderby( $_orderby );
590 if ( 'comment__in' === $_orderby ) {
591 $orderby_array[] = $parsed;
595 $orderby_array[] = $parsed . ' ' . $this->parse_order( $_order );
598 // If no valid clauses were found, order by comment_date_gmt.
599 if ( empty( $orderby_array ) ) {
600 $orderby_array[] = "$wpdb->comments.comment_date_gmt $order";
603 // To ensure determinate sorting, always include a comment_ID clause.
604 if ( ! $found_orderby_comment_ID ) {
605 $comment_ID_order = '';
607 // Inherit order from comment_date or comment_date_gmt, if available.
608 foreach ( $orderby_array as $orderby_clause ) {
609 if ( preg_match( '/comment_date(?:_gmt)*\ (ASC|DESC)/', $orderby_clause, $match ) ) {
610 $comment_ID_order = $match[1];
615 // If no date-related order is available, use the date from the first available clause.
616 if ( ! $comment_ID_order ) {
617 foreach ( $orderby_array as $orderby_clause ) {
618 if ( false !== strpos( 'ASC', $orderby_clause ) ) {
619 $comment_ID_order = 'ASC';
621 $comment_ID_order = 'DESC';
629 if ( ! $comment_ID_order ) {
630 $comment_ID_order = 'DESC';
633 $orderby_array[] = "$wpdb->comments.comment_ID $comment_ID_order";
636 $orderby = implode( ', ', $orderby_array );
638 $orderby = "$wpdb->comments.comment_date_gmt $order";
641 $number = absint( $this->query_vars['number'] );
642 $offset = absint( $this->query_vars['offset'] );
644 if ( ! empty( $number ) ) {
646 $limits = 'LIMIT ' . $offset . ',' . $number;
648 $limits = 'LIMIT ' . $number;
652 if ( $this->query_vars['count'] ) {
653 $fields = 'COUNT(*)';
655 $fields = "$wpdb->comments.comment_ID";
658 $post_id = absint( $this->query_vars['post_id'] );
659 if ( ! empty( $post_id ) ) {
660 $this->sql_clauses['where']['post_id'] = $wpdb->prepare( 'comment_post_ID = %d', $post_id );
663 // Parse comment IDs for an IN clause.
664 if ( ! empty( $this->query_vars['comment__in'] ) ) {
665 $this->sql_clauses['where']['comment__in'] = "$wpdb->comments.comment_ID IN ( " . implode( ',', wp_parse_id_list( $this->query_vars['comment__in'] ) ) . ' )';
668 // Parse comment IDs for a NOT IN clause.
669 if ( ! empty( $this->query_vars['comment__not_in'] ) ) {
670 $this->sql_clauses['where']['comment__not_in'] = "$wpdb->comments.comment_ID NOT IN ( " . implode( ',', wp_parse_id_list( $this->query_vars['comment__not_in'] ) ) . ' )';
673 // Parse comment parent IDs for an IN clause.
674 if ( ! empty( $this->query_vars['parent__in'] ) ) {
675 $this->sql_clauses['where']['parent__in'] = 'comment_parent IN ( ' . implode( ',', wp_parse_id_list( $this->query_vars['parent__in'] ) ) . ' )';
678 // Parse comment parent IDs for a NOT IN clause.
679 if ( ! empty( $this->query_vars['parent__not_in'] ) ) {
680 $this->sql_clauses['where']['parent__not_in'] = 'comment_parent NOT IN ( ' . implode( ',', wp_parse_id_list( $this->query_vars['parent__not_in'] ) ) . ' )';
683 // Parse comment post IDs for an IN clause.
684 if ( ! empty( $this->query_vars['post__in'] ) ) {
685 $this->sql_clauses['where']['post__in'] = 'comment_post_ID IN ( ' . implode( ',', wp_parse_id_list( $this->query_vars['post__in'] ) ) . ' )';
688 // Parse comment post IDs for a NOT IN clause.
689 if ( ! empty( $this->query_vars['post__not_in'] ) ) {
690 $this->sql_clauses['where']['post__not_in'] = 'comment_post_ID NOT IN ( ' . implode( ',', wp_parse_id_list( $this->query_vars['post__not_in'] ) ) . ' )';
693 if ( '' !== $this->query_vars['author_email'] ) {
694 $this->sql_clauses['where']['author_email'] = $wpdb->prepare( 'comment_author_email = %s', $this->query_vars['author_email'] );
697 if ( '' !== $this->query_vars['author_url'] ) {
698 $this->sql_clauses['where']['author_url'] = $wpdb->prepare( 'comment_author_url = %s', $this->query_vars['author_url'] );
701 if ( '' !== $this->query_vars['karma'] ) {
702 $this->sql_clauses['where']['karma'] = $wpdb->prepare( 'comment_karma = %d', $this->query_vars['karma'] );
705 // Filtering by comment_type: 'type', 'type__in', 'type__not_in'.
707 'IN' => array_merge( (array) $this->query_vars['type'], (array) $this->query_vars['type__in'] ),
708 'NOT IN' => (array) $this->query_vars['type__not_in'],
711 $comment_types = array();
712 foreach ( $raw_types as $operator => $_raw_types ) {
713 $_raw_types = array_unique( $_raw_types );
715 foreach ( $_raw_types as $type ) {
717 // An empty translates to 'all', for backward compatibility
724 $comment_types[ $operator ][] = "''";
728 $comment_types[ $operator ][] = "'pingback'";
729 $comment_types[ $operator ][] = "'trackback'";
733 $comment_types[ $operator ][] = $wpdb->prepare( '%s', $type );
738 if ( ! empty( $comment_types[ $operator ] ) ) {
739 $types_sql = implode( ', ', $comment_types[ $operator ] );
740 $this->sql_clauses['where']['comment_type__' . strtolower( str_replace( ' ', '_', $operator ) ) ] = "comment_type $operator ($types_sql)";
744 $parent = $this->query_vars['parent'];
745 if ( $this->query_vars['hierarchical'] && ! $parent ) {
749 if ( '' !== $parent ) {
750 $this->sql_clauses['where']['parent'] = $wpdb->prepare( 'comment_parent = %d', $parent );
753 if ( is_array( $this->query_vars['user_id'] ) ) {
754 $this->sql_clauses['where']['user_id'] = 'user_id IN (' . implode( ',', array_map( 'absint', $this->query_vars['user_id'] ) ) . ')';
755 } elseif ( '' !== $this->query_vars['user_id'] ) {
756 $this->sql_clauses['where']['user_id'] = $wpdb->prepare( 'user_id = %d', $this->query_vars['user_id'] );
759 // Falsy search strings are ignored.
760 if ( strlen( $this->query_vars['search'] ) ) {
761 $search_sql = $this->get_search_sql(
762 $this->query_vars['search'],
763 array( 'comment_author', 'comment_author_email', 'comment_author_url', 'comment_author_IP', 'comment_content' )
766 // Strip leading 'AND'.
767 $this->sql_clauses['where']['search'] = preg_replace( '/^\s*AND\s*/', '', $search_sql );
770 // If any post-related query vars are passed, join the posts table.
771 $join_posts_table = false;
772 $plucked = wp_array_slice_assoc( $this->query_vars, array( 'post_author', 'post_name', 'post_parent' ) );
773 $post_fields = array_filter( $plucked );
775 if ( ! empty( $post_fields ) ) {
776 $join_posts_table = true;
777 foreach ( $post_fields as $field_name => $field_value ) {
778 // $field_value may be an array.
779 $esses = array_fill( 0, count( (array) $field_value ), '%s' );
780 $this->sql_clauses['where'][ $field_name ] = $wpdb->prepare( " {$wpdb->posts}.{$field_name} IN (" . implode( ',', $esses ) . ')', $field_value );
784 // 'post_status' and 'post_type' are handled separately, due to the specialized behavior of 'any'.
785 foreach ( array( 'post_status', 'post_type' ) as $field_name ) {
787 if ( ! empty( $this->query_vars[ $field_name ] ) ) {
788 $q_values = $this->query_vars[ $field_name ];
789 if ( ! is_array( $q_values ) ) {
790 $q_values = explode( ',', $q_values );
793 // 'any' will cause the query var to be ignored.
794 if ( in_array( 'any', $q_values, true ) || empty( $q_values ) ) {
798 $join_posts_table = true;
800 $esses = array_fill( 0, count( $q_values ), '%s' );
801 $this->sql_clauses['where'][ $field_name ] = $wpdb->prepare( " {$wpdb->posts}.{$field_name} IN (" . implode( ',', $esses ) . ")", $q_values );
805 // Comment author IDs for an IN clause.
806 if ( ! empty( $this->query_vars['author__in'] ) ) {
807 $this->sql_clauses['where']['author__in'] = 'user_id IN ( ' . implode( ',', wp_parse_id_list( $this->query_vars['author__in'] ) ) . ' )';
810 // Comment author IDs for a NOT IN clause.
811 if ( ! empty( $this->query_vars['author__not_in'] ) ) {
812 $this->sql_clauses['where']['author__not_in'] = 'user_id NOT IN ( ' . implode( ',', wp_parse_id_list( $this->query_vars['author__not_in'] ) ) . ' )';
815 // Post author IDs for an IN clause.
816 if ( ! empty( $this->query_vars['post_author__in'] ) ) {
817 $join_posts_table = true;
818 $this->sql_clauses['where']['post_author__in'] = 'post_author IN ( ' . implode( ',', wp_parse_id_list( $this->query_vars['post_author__in'] ) ) . ' )';
821 // Post author IDs for a NOT IN clause.
822 if ( ! empty( $this->query_vars['post_author__not_in'] ) ) {
823 $join_posts_table = true;
824 $this->sql_clauses['where']['post_author__not_in'] = 'post_author NOT IN ( ' . implode( ',', wp_parse_id_list( $this->query_vars['post_author__not_in'] ) ) . ' )';
829 if ( $join_posts_table ) {
830 $join .= "JOIN $wpdb->posts ON $wpdb->posts.ID = $wpdb->comments.comment_post_ID";
833 if ( ! empty( $this->meta_query_clauses ) ) {
834 $join .= $this->meta_query_clauses['join'];
836 // Strip leading 'AND'.
837 $this->sql_clauses['where']['meta_query'] = preg_replace( '/^\s*AND\s*/', '', $this->meta_query_clauses['where'] );
839 if ( ! $this->query_vars['count'] ) {
840 $groupby = "{$wpdb->comments}.comment_ID";
844 if ( ! empty( $this->query_vars['date_query'] ) && is_array( $this->query_vars['date_query'] ) ) {
845 $this->date_query = new WP_Date_Query( $this->query_vars['date_query'], 'comment_date' );
846 $this->sql_clauses['where']['date_query'] = preg_replace( '/^\s*AND\s*/', '', $this->date_query->get_sql() );
849 $where = implode( ' AND ', $this->sql_clauses['where'] );
851 $pieces = array( 'fields', 'join', 'where', 'orderby', 'limits', 'groupby' );
853 * Filters the comment query clauses.
857 * @param array $pieces A compacted array of comment query clauses.
858 * @param WP_Comment_Query &$this Current instance of WP_Comment_Query, passed by reference.
860 $clauses = apply_filters_ref_array( 'comments_clauses', array( compact( $pieces ), &$this ) );
862 $fields = isset( $clauses[ 'fields' ] ) ? $clauses[ 'fields' ] : '';
863 $join = isset( $clauses[ 'join' ] ) ? $clauses[ 'join' ] : '';
864 $where = isset( $clauses[ 'where' ] ) ? $clauses[ 'where' ] : '';
865 $orderby = isset( $clauses[ 'orderby' ] ) ? $clauses[ 'orderby' ] : '';
866 $limits = isset( $clauses[ 'limits' ] ) ? $clauses[ 'limits' ] : '';
867 $groupby = isset( $clauses[ 'groupby' ] ) ? $clauses[ 'groupby' ] : '';
869 $this->filtered_where_clause = $where;
872 $where = 'WHERE ' . $where;
876 $groupby = 'GROUP BY ' . $groupby;
880 $orderby = "ORDER BY $orderby";
884 if ( ! $this->query_vars['no_found_rows'] ) {
885 $found_rows = 'SQL_CALC_FOUND_ROWS';
888 $this->sql_clauses['select'] = "SELECT $found_rows $fields";
889 $this->sql_clauses['from'] = "FROM $wpdb->comments $join";
890 $this->sql_clauses['groupby'] = $groupby;
891 $this->sql_clauses['orderby'] = $orderby;
892 $this->sql_clauses['limits'] = $limits;
894 $this->request = "{$this->sql_clauses['select']} {$this->sql_clauses['from']} {$where} {$this->sql_clauses['groupby']} {$this->sql_clauses['orderby']} {$this->sql_clauses['limits']}";
896 if ( $this->query_vars['count'] ) {
897 return intval( $wpdb->get_var( $this->request ) );
899 $comment_ids = $wpdb->get_col( $this->request );
900 return array_map( 'intval', $comment_ids );
905 * Populates found_comments and max_num_pages properties for the current
906 * query if the limit clause was used.
911 * @global wpdb $wpdb WordPress database abstraction object.
913 private function set_found_comments() {
916 if ( $this->query_vars['number'] && ! $this->query_vars['no_found_rows'] ) {
918 * Filters the query used to retrieve found comment count.
922 * @param string $found_comments_query SQL query. Default 'SELECT FOUND_ROWS()'.
923 * @param WP_Comment_Query $comment_query The `WP_Comment_Query` instance.
925 $found_comments_query = apply_filters( 'found_comments_query', 'SELECT FOUND_ROWS()', $this );
927 $this->found_comments = (int) $wpdb->get_var( $found_comments_query );
932 * Fetch descendants for located comments.
934 * Instead of calling `get_children()` separately on each child comment, we do a single set of queries to fetch
935 * the descendant trees for all matched top-level comments.
939 * @param array $comments Array of top-level comments whose descendants should be filled in.
942 protected function fill_descendants( $comments ) {
946 0 => wp_list_pluck( $comments, 'comment_ID' ),
950 * The WHERE clause for the descendant query is the same as for the top-level
951 * query, minus the `parent`, `parent__in`, and `parent__not_in` sub-clauses.
953 $_where = $this->filtered_where_clause;
954 $exclude_keys = array( 'parent', 'parent__in', 'parent__not_in' );
955 foreach ( $exclude_keys as $exclude_key ) {
956 if ( isset( $this->sql_clauses['where'][ $exclude_key ] ) ) {
957 $clause = $this->sql_clauses['where'][ $exclude_key ];
959 // Strip the clause as well as any adjacent ANDs.
960 $pattern = '|(?:AND)?\s*' . $clause . '\s*(?:AND)?|';
961 $_where_parts = preg_split( $pattern, $_where );
964 $_where_parts = array_filter( array_map( 'trim', $_where_parts ) );
966 // Reassemble with an AND.
967 $_where = implode( ' AND ', $_where_parts );
971 $key = md5( serialize( wp_array_slice_assoc( $this->query_vars, array_keys( $this->query_var_defaults ) ) ) );
972 $last_changed = wp_cache_get_last_changed( 'comment' );
974 // Fetch an entire level of the descendant tree at a time.
977 // Parent-child relationships may be cached. Only query for those that are not.
978 $child_ids = $uncached_parent_ids = array();
979 $_parent_ids = $levels[ $level ];
980 foreach ( $_parent_ids as $parent_id ) {
981 $cache_key = "get_comment_child_ids:$parent_id:$key:$last_changed";
982 $parent_child_ids = wp_cache_get( $cache_key, 'comment' );
983 if ( false !== $parent_child_ids ) {
984 $child_ids = array_merge( $child_ids, $parent_child_ids );
986 $uncached_parent_ids[] = $parent_id;
990 if ( $uncached_parent_ids ) {
991 // Fetch this level of comments.
992 $parent_query_args = $this->query_vars;
993 foreach ( $exclude_keys as $exclude_key ) {
994 $parent_query_args[ $exclude_key ] = '';
996 $parent_query_args['parent__in'] = $uncached_parent_ids;
997 $parent_query_args['no_found_rows'] = true;
998 $parent_query_args['hierarchical'] = false;
999 $parent_query_args['offset'] = 0;
1000 $parent_query_args['number'] = 0;
1002 $level_comments = get_comments( $parent_query_args );
1004 // Cache parent-child relationships.
1005 $parent_map = array_fill_keys( $uncached_parent_ids, array() );
1006 foreach ( $level_comments as $level_comment ) {
1007 $parent_map[ $level_comment->comment_parent ][] = $level_comment->comment_ID;
1008 $child_ids[] = $level_comment->comment_ID;
1011 foreach ( $parent_map as $parent_id => $children ) {
1012 $cache_key = "get_comment_child_ids:$parent_id:$key:$last_changed";
1013 wp_cache_set( $cache_key, $children, 'comment' );
1018 $levels[ $level ] = $child_ids;
1019 } while ( $child_ids );
1021 // Prime comment caches for non-top-level comments.
1022 $descendant_ids = array();
1023 for ( $i = 1, $c = count( $levels ); $i < $c; $i++ ) {
1024 $descendant_ids = array_merge( $descendant_ids, $levels[ $i ] );
1027 _prime_comment_caches( $descendant_ids, $this->query_vars['update_comment_meta_cache'] );
1029 // Assemble a flat array of all comments + descendants.
1030 $all_comments = $comments;
1031 foreach ( $descendant_ids as $descendant_id ) {
1032 $all_comments[] = get_comment( $descendant_id );
1035 // If a threaded representation was requested, build the tree.
1036 if ( 'threaded' === $this->query_vars['hierarchical'] ) {
1037 $threaded_comments = $ref = array();
1038 foreach ( $all_comments as $k => $c ) {
1039 $_c = get_comment( $c->comment_ID );
1041 // If the comment isn't in the reference array, it goes in the top level of the thread.
1042 if ( ! isset( $ref[ $c->comment_parent ] ) ) {
1043 $threaded_comments[ $_c->comment_ID ] = $_c;
1044 $ref[ $_c->comment_ID ] = $threaded_comments[ $_c->comment_ID ];
1046 // Otherwise, set it as a child of its parent.
1049 $ref[ $_c->comment_parent ]->add_child( $_c );
1050 $ref[ $_c->comment_ID ] = $ref[ $_c->comment_parent ]->get_child( $_c->comment_ID );
1054 // Set the 'populated_children' flag, to ensure additional database queries aren't run.
1055 foreach ( $ref as $_ref ) {
1056 $_ref->populated_children( true );
1059 $comments = $threaded_comments;
1061 $comments = $all_comments;
1068 * Used internally to generate an SQL string for searching across multiple columns
1073 * @global wpdb $wpdb WordPress database abstraction object.
1075 * @param string $string
1076 * @param array $cols
1079 protected function get_search_sql( $string, $cols ) {
1082 $like = '%' . $wpdb->esc_like( $string ) . '%';
1084 $searches = array();
1085 foreach ( $cols as $col ) {
1086 $searches[] = $wpdb->prepare( "$col LIKE %s", $like );
1089 return ' AND (' . implode(' OR ', $searches) . ')';
1093 * Parse and sanitize 'orderby' keys passed to the comment query.
1098 * @global wpdb $wpdb WordPress database abstraction object.
1100 * @param string $orderby Alias for the field to order by.
1101 * @return string|false Value to used in the ORDER clause. False otherwise.
1103 protected function parse_orderby( $orderby ) {
1106 $allowed_keys = array(
1110 'comment_author_email',
1111 'comment_author_IP',
1112 'comment_author_url',
1124 if ( ! empty( $this->query_vars['meta_key'] ) ) {
1125 $allowed_keys[] = $this->query_vars['meta_key'];
1126 $allowed_keys[] = 'meta_value';
1127 $allowed_keys[] = 'meta_value_num';
1130 $meta_query_clauses = $this->meta_query->get_clauses();
1131 if ( $meta_query_clauses ) {
1132 $allowed_keys = array_merge( $allowed_keys, array_keys( $meta_query_clauses ) );
1136 if ( $orderby == $this->query_vars['meta_key'] || $orderby == 'meta_value' ) {
1137 $parsed = "$wpdb->commentmeta.meta_value";
1138 } elseif ( $orderby == 'meta_value_num' ) {
1139 $parsed = "$wpdb->commentmeta.meta_value+0";
1140 } elseif ( $orderby == 'comment__in' ) {
1141 $comment__in = implode( ',', array_map( 'absint', $this->query_vars['comment__in'] ) );
1142 $parsed = "FIELD( {$wpdb->comments}.comment_ID, $comment__in )";
1143 } elseif ( in_array( $orderby, $allowed_keys ) ) {
1145 if ( isset( $meta_query_clauses[ $orderby ] ) ) {
1146 $meta_clause = $meta_query_clauses[ $orderby ];
1147 $parsed = sprintf( "CAST(%s.meta_value AS %s)", esc_sql( $meta_clause['alias'] ), esc_sql( $meta_clause['cast'] ) );
1149 $parsed = "$wpdb->comments.$orderby";
1157 * Parse an 'order' query variable and cast it to ASC or DESC as necessary.
1162 * @param string $order The 'order' query variable.
1163 * @return string The sanitized 'order' query variable.
1165 protected function parse_order( $order ) {
1166 if ( ! is_string( $order ) || empty( $order ) ) {
1170 if ( 'ASC' === strtoupper( $order ) ) {