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(
63 * Date query container
67 * @var object WP_Date_Query
69 public $date_query = false;
72 * Query vars set by the user.
81 * Default values for query vars.
87 public $query_var_defaults;
90 * List of comments located by the query.
99 * The amount of found comments for the current query.
105 public $found_comments = 0;
108 * The number of pages.
114 public $max_num_pages = 0;
117 * Make private/protected methods readable for backwards compatibility.
122 * @param callable $name Method to call.
123 * @param array $arguments Arguments to pass when calling.
124 * @return mixed|false Return value of the callback, false otherwise.
126 public function __call( $name, $arguments ) {
127 if ( 'get_search_sql' === $name ) {
128 return call_user_func_array( array( $this, $name ), $arguments );
136 * Sets up the comment query, based on the query vars passed.
139 * @since 4.4.0 `$parent__in` and `$parent__not_in` were added.
140 * @since 4.4.0 Order by `comment__in` was added. `$update_comment_meta_cache`, `$no_found_rows`,
141 * `$hierarchical`, and `$update_comment_post_cache` were added.
144 * @param string|array $query {
145 * Optional. Array or query string of comment query parameters. Default empty.
147 * @type string $author_email Comment author email address. Default empty.
148 * @type array $author__in Array of author IDs to include comments for. Default empty.
149 * @type array $author__not_in Array of author IDs to exclude comments for. Default empty.
150 * @type array $comment__in Array of comment IDs to include. Default empty.
151 * @type array $comment__not_in Array of comment IDs to exclude. Default empty.
152 * @type bool $count Whether to return a comment count (true) or array of
153 * comment objects (false). Default false.
154 * @type array $date_query Date query clauses to limit comments by. See WP_Date_Query.
156 * @type string $fields Comment fields to return. Accepts 'ids' for comment IDs
157 * only or empty for all fields. Default empty.
158 * @type int $ID Currently unused.
159 * @type array $include_unapproved Array of IDs or email addresses of users whose unapproved
160 * comments will be returned by the query regardless of
161 * `$status`. Default empty.
162 * @type int $karma Karma score to retrieve matching comments for.
164 * @type string $meta_key Include comments with a matching comment meta key.
166 * @type string $meta_value Include comments with a matching comment meta value.
167 * Requires `$meta_key` to be set. Default empty.
168 * @type array $meta_query Meta query clauses to limit retrieved comments by.
169 * See WP_Meta_Query. Default empty.
170 * @type int $number Maximum number of comments to retrieve.
171 * Default null (no limit).
172 * @type int $offset Number of comments to offset the query. Used to build
173 * LIMIT clause. Default 0.
174 * @type bool $no_found_rows Whether to disable the `SQL_CALC_FOUND_ROWS` query.
176 * @type string|array $orderby Comment status or array of statuses. To use 'meta_value'
177 * or 'meta_value_num', `$meta_key` must also be defined.
178 * To sort by a specific `$meta_query` clause, use that
179 * clause's array key. Accepts 'comment_agent',
180 * 'comment_approved', 'comment_author',
181 * 'comment_author_email', 'comment_author_IP',
182 * 'comment_author_url', 'comment_content', 'comment_date',
183 * 'comment_date_gmt', 'comment_ID', 'comment_karma',
184 * 'comment_parent', 'comment_post_ID', 'comment_type',
185 * 'user_id', 'comment__in', 'meta_value', 'meta_value_num',
186 * the value of $meta_key, and the array keys of
187 * `$meta_query`. Also accepts false, an empty array, or
188 * 'none' to disable `ORDER BY` clause.
189 * Default: 'comment_date_gmt'.
190 * @type string $order How to order retrieved comments. Accepts 'ASC', 'DESC'.
192 * @type int $parent Parent ID of comment to retrieve children of.
194 * @type array $parent__in Array of parent IDs of comments to retrieve children for.
196 * @type array $parent__not_in Array of parent IDs of comments *not* to retrieve
197 * children for. Default empty.
198 * @type array $post_author__in Array of author IDs to retrieve comments for.
200 * @type array $post_author__not_in Array of author IDs *not* to retrieve comments for.
202 * @type int $post_ID Currently unused.
203 * @type int $post_id Limit results to those affiliated with a given post ID.
205 * @type array $post__in Array of post IDs to include affiliated comments for.
207 * @type array $post__not_in Array of post IDs to exclude affiliated comments for.
209 * @type int $post_author Comment author ID to limit results by. Default empty.
210 * @type string $post_status Post status to retrieve affiliated comments for.
212 * @type string $post_type Post type to retrieve affiliated comments for.
214 * @type string $post_name Post name to retrieve affiliated comments for.
216 * @type int $post_parent Post parent ID to retrieve affiliated comments for.
218 * @type string $search Search term(s) to retrieve matching comments for.
220 * @type string $status Comment status to limit results by. Accepts 'hold'
221 * (`comment_status=0`), 'approve' (`comment_status=1`),
222 * 'all', or a custom comment status. Default 'all'.
223 * @type string|array $type Include comments of a given type, or array of types.
224 * Accepts 'comment', 'pings' (includes 'pingback' and
225 * 'trackback'), or anycustom type string. Default empty.
226 * @type array $type__in Include comments from a given array of comment types.
228 * @type array $type__not_in Exclude comments from a given array of comment types.
230 * @type int $user_id Include comments for a specific user ID. Default empty.
231 * @type bool|string $hierarchical Whether to include comment descendants in the results.
232 * 'threaded' returns a tree, with each comment's children
233 * stored in a `children` property on the `WP_Comment`
234 * object. 'flat' returns a flat array of found comments plus
235 * their children. Pass `false` to leave out descendants.
236 * The parameter is ignored (forced to `false`) when
237 * `$fields` is 'ids' or 'counts'. Accepts 'threaded',
238 * 'flat', or false. Default: false.
239 * @type bool $update_comment_meta_cache Whether to prime the metadata cache for found comments.
241 * @type bool $update_comment_post_cache Whether to prime the cache for comment posts.
245 public function __construct( $query = '' ) {
246 $this->query_var_defaults = array(
247 'author_email' => '',
249 'author__not_in' => '',
250 'include_unapproved' => '',
254 'comment__not_in' => '',
258 'no_found_rows' => true,
262 'post_author__in' => '',
263 'post_author__not_in' => '',
267 'post__not_in' => '',
276 'type__not_in' => '',
283 'date_query' => null, // See WP_Date_Query
284 'hierarchical' => false,
285 'update_comment_meta_cache' => true,
286 'update_comment_post_cache' => false,
289 if ( ! empty( $query ) ) {
290 $this->query( $query );
295 * Parse arguments passed to the comment query with default query parameters.
297 * @since 4.2.0 Extracted from WP_Comment_Query::query().
301 * @param string|array $query WP_Comment_Query arguments. See WP_Comment_Query::__construct()
303 public function parse_query( $query = '' ) {
304 if ( empty( $query ) ) {
305 $query = $this->query_vars;
308 $this->query_vars = wp_parse_args( $query, $this->query_var_defaults );
309 do_action_ref_array( 'parse_comment_query', array( &$this ) );
313 * Sets up the WordPress query for retrieving comments.
316 * @since 4.1.0 Introduced 'comment__in', 'comment__not_in', 'post_author__in',
317 * 'post_author__not_in', 'author__in', 'author__not_in', 'post__in',
318 * 'post__not_in', 'include_unapproved', 'type__in', and 'type__not_in'
319 * arguments to $query_vars.
320 * @since 4.2.0 Moved parsing to WP_Comment_Query::parse_query().
323 * @param string|array $query Array or URL query string of parameters.
324 * @return array|int List of comments, or number of comments when 'count' is passed as a query var.
326 public function query( $query ) {
327 $this->query_vars = wp_parse_args( $query );
328 return $this->get_comments();
332 * Get a list of comments matching the query vars.
337 * @global wpdb $wpdb WordPress database abstraction object.
339 * @return int|array The list of comments.
341 public function get_comments() {
344 $this->parse_query();
347 $this->meta_query = new WP_Meta_Query();
348 $this->meta_query->parse_query_vars( $this->query_vars );
351 * Fires before comments are retrieved.
355 * @param WP_Comment_Query &$this Current instance of WP_Comment_Query, passed by reference.
357 do_action_ref_array( 'pre_get_comments', array( &$this ) );
359 // Reparse query vars, in case they were modified in a 'pre_get_comments' callback.
360 $this->meta_query->parse_query_vars( $this->query_vars );
361 if ( ! empty( $this->meta_query->queries ) ) {
362 $this->meta_query_clauses = $this->meta_query->get_sql( 'comment', $wpdb->comments, 'comment_ID', $this );
365 // $args can include anything. Only use the args defined in the query_var_defaults to compute the key.
366 $key = md5( serialize( wp_array_slice_assoc( $this->query_vars, array_keys( $this->query_var_defaults ) ) ) );
367 $last_changed = wp_cache_get( 'last_changed', 'comment' );
368 if ( ! $last_changed ) {
369 $last_changed = microtime();
370 wp_cache_set( 'last_changed', $last_changed, 'comment' );
372 $cache_key = "get_comment_ids:$key:$last_changed";
374 $comment_ids = wp_cache_get( $cache_key, 'comment' );
375 if ( false === $comment_ids ) {
376 $comment_ids = $this->get_comment_ids();
377 wp_cache_add( $cache_key, $comment_ids, 'comment' );
380 // If querying for a count only, there's nothing more to do.
381 if ( $this->query_vars['count'] ) {
382 // $comment_ids is actually a count in this case.
383 return intval( $comment_ids );
386 $comment_ids = array_map( 'intval', $comment_ids );
388 $this->comment_count = count( $this->comments );
390 if ( $comment_ids && $this->query_vars['number'] && ! $this->query_vars['no_found_rows'] ) {
392 * Filter the query used to retrieve found comment count.
396 * @param string $found_comments_query SQL query. Default 'SELECT FOUND_ROWS()'.
397 * @param WP_Comment_Query $comment_query The `WP_Comment_Query` instance.
399 $found_comments_query = apply_filters( 'found_comments_query', 'SELECT FOUND_ROWS()', $this );
400 $this->found_comments = (int) $wpdb->get_var( $found_comments_query );
402 $this->max_num_pages = ceil( $this->found_comments / $this->query_vars['number'] );
405 if ( 'ids' == $this->query_vars['fields'] ) {
406 $this->comments = $comment_ids;
407 return $this->comments;
410 _prime_comment_caches( $comment_ids, $this->query_vars['update_comment_meta_cache'] );
412 // Fetch full comment objects from the primed cache.
413 $_comments = array();
414 foreach ( $comment_ids as $comment_id ) {
415 if ( $_comment = get_comment( $comment_id ) ) {
416 $_comments[] = $_comment;
420 // Prime comment post caches.
421 if ( $this->query_vars['update_comment_post_cache'] ) {
422 $comment_post_ids = array();
423 foreach ( $_comments as $_comment ) {
424 $comment_post_ids[] = $_comment->comment_post_ID;
427 _prime_post_caches( $comment_post_ids, false, false );
431 * Filter the comment query results.
435 * @param array $results An array of comments.
436 * @param WP_Comment_Query &$this Current instance of WP_Comment_Query, passed by reference.
438 $_comments = apply_filters_ref_array( 'the_comments', array( $_comments, &$this ) );
440 // Convert to WP_Comment instances
441 $comments = array_map( 'get_comment', $_comments );
443 if ( $this->query_vars['hierarchical'] ) {
444 $comments = $this->fill_descendants( $comments );
447 $this->comments = $comments;
448 return $this->comments;
452 * Used internally to get a list of comment IDs matching the query vars.
457 * @global wpdb $wpdb WordPress database abstraction object.
459 protected function get_comment_ids() {
462 // Assemble clauses related to 'comment_approved'.
463 $approved_clauses = array();
465 // 'status' accepts an array or a comma-separated string.
466 $status_clauses = array();
467 $statuses = $this->query_vars['status'];
468 if ( ! is_array( $statuses ) ) {
469 $statuses = preg_split( '/[\s,]+/', $statuses );
472 // 'any' overrides other statuses.
473 if ( ! in_array( 'any', $statuses ) ) {
474 foreach ( $statuses as $status ) {
477 $status_clauses[] = "comment_approved = '0'";
481 $status_clauses[] = "comment_approved = '1'";
486 $status_clauses[] = "( comment_approved = '0' OR comment_approved = '1' )";
490 $status_clauses[] = $wpdb->prepare( "comment_approved = %s", $status );
495 if ( ! empty( $status_clauses ) ) {
496 $approved_clauses[] = '( ' . implode( ' OR ', $status_clauses ) . ' )';
500 // User IDs or emails whose unapproved comments are included, regardless of $status.
501 if ( ! empty( $this->query_vars['include_unapproved'] ) ) {
502 $include_unapproved = $this->query_vars['include_unapproved'];
504 // Accepts arrays or comma-separated strings.
505 if ( ! is_array( $include_unapproved ) ) {
506 $include_unapproved = preg_split( '/[\s,]+/', $include_unapproved );
509 $unapproved_ids = $unapproved_emails = array();
510 foreach ( $include_unapproved as $unapproved_identifier ) {
511 // Numeric values are assumed to be user ids.
512 if ( is_numeric( $unapproved_identifier ) ) {
513 $approved_clauses[] = $wpdb->prepare( "( user_id = %d AND comment_approved = '0' )", $unapproved_identifier );
515 // Otherwise we match against email addresses.
517 $approved_clauses[] = $wpdb->prepare( "( comment_author_email = %s AND comment_approved = '0' )", $unapproved_identifier );
522 // Collapse comment_approved clauses into a single OR-separated clause.
523 if ( ! empty( $approved_clauses ) ) {
524 if ( 1 === count( $approved_clauses ) ) {
525 $this->sql_clauses['where']['approved'] = $approved_clauses[0];
527 $this->sql_clauses['where']['approved'] = '( ' . implode( ' OR ', $approved_clauses ) . ' )';
531 $order = ( 'ASC' == strtoupper( $this->query_vars['order'] ) ) ? 'ASC' : 'DESC';
533 // Disable ORDER BY with 'none', an empty array, or boolean false.
534 if ( in_array( $this->query_vars['orderby'], array( 'none', array(), false ), true ) ) {
536 } elseif ( ! empty( $this->query_vars['orderby'] ) ) {
537 $ordersby = is_array( $this->query_vars['orderby'] ) ?
538 $this->query_vars['orderby'] :
539 preg_split( '/[,\s]/', $this->query_vars['orderby'] );
541 $orderby_array = array();
542 $found_orderby_comment_ID = false;
543 foreach ( $ordersby as $_key => $_value ) {
548 if ( is_int( $_key ) ) {
556 if ( ! $found_orderby_comment_ID && in_array( $_orderby, array( 'comment_ID', 'comment__in' ) ) ) {
557 $found_orderby_comment_ID = true;
560 $parsed = $this->parse_orderby( $_orderby );
566 if ( 'comment__in' === $_orderby ) {
567 $orderby_array[] = $parsed;
571 $orderby_array[] = $parsed . ' ' . $this->parse_order( $_order );
574 // If no valid clauses were found, order by comment_date_gmt.
575 if ( empty( $orderby_array ) ) {
576 $orderby_array[] = "$wpdb->comments.comment_date_gmt $order";
579 // To ensure determinate sorting, always include a comment_ID clause.
580 if ( ! $found_orderby_comment_ID ) {
581 $comment_ID_order = '';
583 // Inherit order from comment_date or comment_date_gmt, if available.
584 foreach ( $orderby_array as $orderby_clause ) {
585 if ( preg_match( '/comment_date(?:_gmt)*\ (ASC|DESC)/', $orderby_clause, $match ) ) {
586 $comment_ID_order = $match[1];
591 // If no date-related order is available, use the date from the first available clause.
592 if ( ! $comment_ID_order ) {
593 foreach ( $orderby_array as $orderby_clause ) {
594 if ( false !== strpos( 'ASC', $orderby_clause ) ) {
595 $comment_ID_order = 'ASC';
597 $comment_ID_order = 'DESC';
605 if ( ! $comment_ID_order ) {
606 $comment_ID_order = 'DESC';
609 $orderby_array[] = "$wpdb->comments.comment_ID $comment_ID_order";
612 $orderby = implode( ', ', $orderby_array );
614 $orderby = "$wpdb->comments.comment_date_gmt $order";
617 $number = absint( $this->query_vars['number'] );
618 $offset = absint( $this->query_vars['offset'] );
620 if ( ! empty( $number ) ) {
622 $limits = 'LIMIT ' . $offset . ',' . $number;
624 $limits = 'LIMIT ' . $number;
628 if ( $this->query_vars['count'] ) {
629 $fields = 'COUNT(*)';
631 $fields = "$wpdb->comments.comment_ID";
634 $post_id = absint( $this->query_vars['post_id'] );
635 if ( ! empty( $post_id ) ) {
636 $this->sql_clauses['where']['post_id'] = $wpdb->prepare( 'comment_post_ID = %d', $post_id );
639 // Parse comment IDs for an IN clause.
640 if ( ! empty( $this->query_vars['comment__in'] ) ) {
641 $this->sql_clauses['where']['comment__in'] = "$wpdb->comments.comment_ID IN ( " . implode( ',', wp_parse_id_list( $this->query_vars['comment__in'] ) ) . ' )';
644 // Parse comment IDs for a NOT IN clause.
645 if ( ! empty( $this->query_vars['comment__not_in'] ) ) {
646 $this->sql_clauses['where']['comment__not_in'] = "$wpdb->comments.comment_ID NOT IN ( " . implode( ',', wp_parse_id_list( $this->query_vars['comment__not_in'] ) ) . ' )';
649 // Parse comment parent IDs for an IN clause.
650 if ( ! empty( $this->query_vars['parent__in'] ) ) {
651 $this->sql_clauses['where']['parent__in'] = 'comment_parent IN ( ' . implode( ',', wp_parse_id_list( $this->query_vars['parent__in'] ) ) . ' )';
654 // Parse comment parent IDs for a NOT IN clause.
655 if ( ! empty( $this->query_vars['parent__not_in'] ) ) {
656 $this->sql_clauses['where']['parent__not_in'] = 'comment_parent NOT IN ( ' . implode( ',', wp_parse_id_list( $this->query_vars['parent__not_in'] ) ) . ' )';
659 // Parse comment post IDs for an IN clause.
660 if ( ! empty( $this->query_vars['post__in'] ) ) {
661 $this->sql_clauses['where']['post__in'] = 'comment_post_ID IN ( ' . implode( ',', wp_parse_id_list( $this->query_vars['post__in'] ) ) . ' )';
664 // Parse comment post IDs for a NOT IN clause.
665 if ( ! empty( $this->query_vars['post__not_in'] ) ) {
666 $this->sql_clauses['where']['post__not_in'] = 'comment_post_ID NOT IN ( ' . implode( ',', wp_parse_id_list( $this->query_vars['post__not_in'] ) ) . ' )';
669 if ( '' !== $this->query_vars['author_email'] ) {
670 $this->sql_clauses['where']['author_email'] = $wpdb->prepare( 'comment_author_email = %s', $this->query_vars['author_email'] );
673 if ( '' !== $this->query_vars['karma'] ) {
674 $this->sql_clauses['where']['karma'] = $wpdb->prepare( 'comment_karma = %d', $this->query_vars['karma'] );
677 // Filtering by comment_type: 'type', 'type__in', 'type__not_in'.
679 'IN' => array_merge( (array) $this->query_vars['type'], (array) $this->query_vars['type__in'] ),
680 'NOT IN' => (array) $this->query_vars['type__not_in'],
683 $comment_types = array();
684 foreach ( $raw_types as $operator => $_raw_types ) {
685 $_raw_types = array_unique( $_raw_types );
687 foreach ( $_raw_types as $type ) {
689 // An empty translates to 'all', for backward compatibility
696 $comment_types[ $operator ][] = "''";
700 $comment_types[ $operator ][] = "'pingback'";
701 $comment_types[ $operator ][] = "'trackback'";
705 $comment_types[ $operator ][] = $wpdb->prepare( '%s', $type );
710 if ( ! empty( $comment_types[ $operator ] ) ) {
711 $types_sql = implode( ', ', $comment_types[ $operator ] );
712 $this->sql_clauses['where']['comment_type__' . strtolower( str_replace( ' ', '_', $operator ) ) ] = "comment_type $operator ($types_sql)";
716 if ( $this->query_vars['hierarchical'] && ! $this->query_vars['parent'] ) {
717 $this->query_vars['parent'] = 0;
720 if ( '' !== $this->query_vars['parent'] ) {
721 $this->sql_clauses['where']['parent'] = $wpdb->prepare( 'comment_parent = %d', $this->query_vars['parent'] );
724 if ( is_array( $this->query_vars['user_id'] ) ) {
725 $this->sql_clauses['where']['user_id'] = 'user_id IN (' . implode( ',', array_map( 'absint', $this->query_vars['user_id'] ) ) . ')';
726 } elseif ( '' !== $this->query_vars['user_id'] ) {
727 $this->sql_clauses['where']['user_id'] = $wpdb->prepare( 'user_id = %d', $this->query_vars['user_id'] );
730 if ( '' !== $this->query_vars['search'] ) {
731 $search_sql = $this->get_search_sql(
732 $this->query_vars['search'],
733 array( 'comment_author', 'comment_author_email', 'comment_author_url', 'comment_author_IP', 'comment_content' )
736 // Strip leading 'AND'.
737 $this->sql_clauses['where']['search'] = preg_replace( '/^\s*AND\s*/', '', $search_sql );
740 // If any post-related query vars are passed, join the posts table.
741 $join_posts_table = false;
742 $plucked = wp_array_slice_assoc( $this->query_vars, array( 'post_author', 'post_name', 'post_parent', 'post_status', 'post_type' ) );
743 $post_fields = array_filter( $plucked );
745 if ( ! empty( $post_fields ) ) {
746 $join_posts_table = true;
747 foreach ( $post_fields as $field_name => $field_value ) {
748 // $field_value may be an array.
749 $esses = array_fill( 0, count( (array) $field_value ), '%s' );
750 $this->sql_clauses['where']['post_fields'] = $wpdb->prepare( " {$wpdb->posts}.{$field_name} IN (" . implode( ',', $esses ) . ')', $field_value );
754 // Comment author IDs for an IN clause.
755 if ( ! empty( $this->query_vars['author__in'] ) ) {
756 $this->sql_clauses['where']['author__in'] = 'user_id IN ( ' . implode( ',', wp_parse_id_list( $this->query_vars['author__in'] ) ) . ' )';
759 // Comment author IDs for a NOT IN clause.
760 if ( ! empty( $this->query_vars['author__not_in'] ) ) {
761 $this->sql_clauses['where']['author__not_in'] = 'user_id NOT IN ( ' . implode( ',', wp_parse_id_list( $this->query_vars['author__not_in'] ) ) . ' )';
764 // Post author IDs for an IN clause.
765 if ( ! empty( $this->query_vars['post_author__in'] ) ) {
766 $join_posts_table = true;
767 $this->sql_clauses['where']['post_author__in'] = 'post_author IN ( ' . implode( ',', wp_parse_id_list( $this->query_vars['post_author__in'] ) ) . ' )';
770 // Post author IDs for a NOT IN clause.
771 if ( ! empty( $this->query_vars['post_author__not_in'] ) ) {
772 $join_posts_table = true;
773 $this->sql_clauses['where']['post_author__not_in'] = 'post_author NOT IN ( ' . implode( ',', wp_parse_id_list( $this->query_vars['post_author__not_in'] ) ) . ' )';
778 if ( $join_posts_table ) {
779 $join .= "JOIN $wpdb->posts ON $wpdb->posts.ID = $wpdb->comments.comment_post_ID";
782 if ( ! empty( $this->meta_query_clauses ) ) {
783 $join .= $this->meta_query_clauses['join'];
785 // Strip leading 'AND'.
786 $this->sql_clauses['where']['meta_query'] = preg_replace( '/^\s*AND\s*/', '', $this->meta_query_clauses['where'] );
788 if ( ! $this->query_vars['count'] ) {
789 $groupby = "{$wpdb->comments}.comment_ID";
793 $date_query = $this->query_vars['date_query'];
794 if ( ! empty( $date_query ) && is_array( $date_query ) ) {
795 $date_query_object = new WP_Date_Query( $date_query, 'comment_date' );
796 $this->sql_clauses['where']['date_query'] = preg_replace( '/^\s*AND\s*/', '', $date_query_object->get_sql() );
799 $where = implode( ' AND ', $this->sql_clauses['where'] );
801 $pieces = array( 'fields', 'join', 'where', 'orderby', 'limits', 'groupby' );
803 * Filter the comment query clauses.
807 * @param array $pieces A compacted array of comment query clauses.
808 * @param WP_Comment_Query &$this Current instance of WP_Comment_Query, passed by reference.
810 $clauses = apply_filters_ref_array( 'comments_clauses', array( compact( $pieces ), &$this ) );
812 $fields = isset( $clauses[ 'fields' ] ) ? $clauses[ 'fields' ] : '';
813 $join = isset( $clauses[ 'join' ] ) ? $clauses[ 'join' ] : '';
814 $where = isset( $clauses[ 'where' ] ) ? $clauses[ 'where' ] : '';
815 $orderby = isset( $clauses[ 'orderby' ] ) ? $clauses[ 'orderby' ] : '';
816 $limits = isset( $clauses[ 'limits' ] ) ? $clauses[ 'limits' ] : '';
817 $groupby = isset( $clauses[ 'groupby' ] ) ? $clauses[ 'groupby' ] : '';
820 $where = 'WHERE ' . $where;
824 $groupby = 'GROUP BY ' . $groupby;
828 $orderby = "ORDER BY $orderby";
832 if ( ! $this->query_vars['no_found_rows'] ) {
833 $found_rows = 'SQL_CALC_FOUND_ROWS';
836 $this->sql_clauses['select'] = "SELECT $found_rows $fields";
837 $this->sql_clauses['from'] = "FROM $wpdb->comments $join";
838 $this->sql_clauses['groupby'] = $groupby;
839 $this->sql_clauses['orderby'] = $orderby;
840 $this->sql_clauses['limits'] = $limits;
842 $this->request = "{$this->sql_clauses['select']} {$this->sql_clauses['from']} {$where} {$this->sql_clauses['groupby']} {$this->sql_clauses['orderby']} {$this->sql_clauses['limits']}";
844 if ( $this->query_vars['count'] ) {
845 return intval( $wpdb->get_var( $this->request ) );
847 $comment_ids = $wpdb->get_col( $this->request );
848 return array_map( 'intval', $comment_ids );
853 * Fetch descendants for located comments.
855 * Instead of calling `get_children()` separately on each child comment, we do a single set of queries to fetch
856 * the descendant trees for all matched top-level comments.
860 * @param array $comments Array of top-level comments whose descendants should be filled in.
863 protected function fill_descendants( $comments ) {
867 0 => wp_list_pluck( $comments, 'comment_ID' ),
870 $where_clauses = $this->sql_clauses['where'];
872 $where_clauses['parent'],
873 $where_clauses['parent__in'],
874 $where_clauses['parent__not_in']
877 // Fetch an entire level of the descendant tree at a time.
880 $parent_ids = $levels[ $level ];
881 if ( ! $parent_ids ) {
885 $where = 'WHERE ' . implode( ' AND ', $where_clauses ) . ' AND comment_parent IN (' . implode( ',', array_map( 'intval', $parent_ids ) ) . ')';
886 $comment_ids = $wpdb->get_col( "{$this->sql_clauses['select']} {$this->sql_clauses['from']} {$where} {$this->sql_clauses['groupby']} ORDER BY comment_date_gmt ASC, comment_ID ASC" );
889 $levels[ $level ] = $comment_ids;
890 } while ( $comment_ids );
892 // Prime comment caches for non-top-level comments.
893 $descendant_ids = array();
894 for ( $i = 1; $i < count( $levels ); $i++ ) {
895 $descendant_ids = array_merge( $descendant_ids, $levels[ $i ] );
898 _prime_comment_caches( $descendant_ids, $this->query_vars['update_comment_meta_cache'] );
900 // Assemble a flat array of all comments + descendants.
901 $all_comments = $comments;
902 foreach ( $descendant_ids as $descendant_id ) {
903 $all_comments[] = get_comment( $descendant_id );
906 // If a threaded representation was requested, build the tree.
907 if ( 'threaded' === $this->query_vars['hierarchical'] ) {
908 $threaded_comments = $ref = array();
909 foreach ( $all_comments as $k => $c ) {
910 $_c = get_comment( $c->comment_ID );
912 // If the comment isn't in the reference array, it goes in the top level of the thread.
913 if ( ! isset( $ref[ $c->comment_parent ] ) ) {
914 $threaded_comments[ $_c->comment_ID ] = $_c;
915 $ref[ $_c->comment_ID ] = $threaded_comments[ $_c->comment_ID ];
917 // Otherwise, set it as a child of its parent.
920 $ref[ $_c->comment_parent ]->add_child( $_c );
921 $ref[ $_c->comment_ID ] = $ref[ $_c->comment_parent ]->get_child( $_c->comment_ID );
925 // Set the 'populated_children' flag, to ensure additional database queries aren't run.
926 foreach ( $ref as $_ref ) {
927 $_ref->populated_children( true );
930 $comments = $threaded_comments;
932 $comments = $all_comments;
939 * Used internally to generate an SQL string for searching across multiple columns
944 * @global wpdb $wpdb WordPress database abstraction object.
946 * @param string $string
950 protected function get_search_sql( $string, $cols ) {
953 $like = '%' . $wpdb->esc_like( $string ) . '%';
956 foreach ( $cols as $col ) {
957 $searches[] = $wpdb->prepare( "$col LIKE %s", $like );
960 return ' AND (' . implode(' OR ', $searches) . ')';
964 * Parse and sanitize 'orderby' keys passed to the comment query.
969 * @global wpdb $wpdb WordPress database abstraction object.
971 * @param string $orderby Alias for the field to order by.
972 * @return string|false Value to used in the ORDER clause. False otherwise.
974 protected function parse_orderby( $orderby ) {
977 $allowed_keys = array(
981 'comment_author_email',
983 'comment_author_url',
995 if ( ! empty( $this->query_vars['meta_key'] ) ) {
996 $allowed_keys[] = $this->query_vars['meta_key'];
997 $allowed_keys[] = 'meta_value';
998 $allowed_keys[] = 'meta_value_num';
1001 $meta_query_clauses = $this->meta_query->get_clauses();
1002 if ( $meta_query_clauses ) {
1003 $allowed_keys = array_merge( $allowed_keys, array_keys( $meta_query_clauses ) );
1007 if ( $orderby == $this->query_vars['meta_key'] || $orderby == 'meta_value' ) {
1008 $parsed = "$wpdb->commentmeta.meta_value";
1009 } elseif ( $orderby == 'meta_value_num' ) {
1010 $parsed = "$wpdb->commentmeta.meta_value+0";
1011 } elseif ( $orderby == 'comment__in' ) {
1012 $comment__in = implode( ',', array_map( 'absint', $this->query_vars['comment__in'] ) );
1013 $parsed = "FIELD( {$wpdb->comments}.comment_ID, $comment__in )";
1014 } elseif ( in_array( $orderby, $allowed_keys ) ) {
1016 if ( isset( $meta_query_clauses[ $orderby ] ) ) {
1017 $meta_clause = $meta_query_clauses[ $orderby ];
1018 $parsed = sprintf( "CAST(%s.meta_value AS %s)", esc_sql( $meta_clause['alias'] ), esc_sql( $meta_clause['cast'] ) );
1020 $parsed = "$wpdb->comments.$orderby";
1028 * Parse an 'order' query variable and cast it to ASC or DESC as necessary.
1033 * @param string $order The 'order' query variable.
1034 * @return string The sanitized 'order' query variable.
1036 protected function parse_order( $order ) {
1037 if ( ! is_string( $order ) || empty( $order ) ) {
1041 if ( 'ASC' === strtoupper( $order ) ) {