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 '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 backwards 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.
155 * @param string|array $query {
156 * Optional. Array or query string of comment query parameters. Default empty.
158 * @type string $author_email Comment author email address. Default empty.
159 * @type array $author__in Array of author IDs to include comments for. Default empty.
160 * @type array $author__not_in Array of author IDs to exclude comments for. Default empty.
161 * @type array $comment__in Array of comment IDs to include. Default empty.
162 * @type array $comment__not_in Array of comment IDs to exclude. Default empty.
163 * @type bool $count Whether to return a comment count (true) or array of
164 * comment objects (false). Default false.
165 * @type array $date_query Date query clauses to limit comments by. See WP_Date_Query.
167 * @type string $fields Comment fields to return. Accepts 'ids' for comment IDs
168 * only or empty for all fields. Default empty.
169 * @type int $ID Currently unused.
170 * @type array $include_unapproved Array of IDs or email addresses of users whose unapproved
171 * comments will be returned by the query regardless of
172 * `$status`. Default empty.
173 * @type int $karma Karma score to retrieve matching comments for.
175 * @type string $meta_key Include comments with a matching comment meta key.
177 * @type string $meta_value Include comments with a matching comment meta value.
178 * Requires `$meta_key` to be set. Default empty.
179 * @type array $meta_query Meta query clauses to limit retrieved comments by.
180 * See WP_Meta_Query. Default empty.
181 * @type int $number Maximum number of comments to retrieve.
182 * Default null (no limit).
183 * @type int $offset Number of comments to offset the query. Used to build
184 * LIMIT clause. Default 0.
185 * @type bool $no_found_rows Whether to disable the `SQL_CALC_FOUND_ROWS` query.
187 * @type string|array $orderby Comment status or array of statuses. To use 'meta_value'
188 * or 'meta_value_num', `$meta_key` must also be defined.
189 * To sort by a specific `$meta_query` clause, use that
190 * clause's array key. Accepts 'comment_agent',
191 * 'comment_approved', 'comment_author',
192 * 'comment_author_email', 'comment_author_IP',
193 * 'comment_author_url', 'comment_content', 'comment_date',
194 * 'comment_date_gmt', 'comment_ID', 'comment_karma',
195 * 'comment_parent', 'comment_post_ID', 'comment_type',
196 * 'user_id', 'comment__in', 'meta_value', 'meta_value_num',
197 * the value of $meta_key, and the array keys of
198 * `$meta_query`. Also accepts false, an empty array, or
199 * 'none' to disable `ORDER BY` clause.
200 * Default: 'comment_date_gmt'.
201 * @type string $order How to order retrieved comments. Accepts 'ASC', 'DESC'.
203 * @type int $parent Parent ID of comment to retrieve children of.
205 * @type array $parent__in Array of parent IDs of comments to retrieve children for.
207 * @type array $parent__not_in Array of parent IDs of comments *not* to retrieve
208 * children for. Default empty.
209 * @type array $post_author__in Array of author IDs to retrieve comments for.
211 * @type array $post_author__not_in Array of author IDs *not* to retrieve comments for.
213 * @type int $post_ID Currently unused.
214 * @type int $post_id Limit results to those affiliated with a given post ID.
216 * @type array $post__in Array of post IDs to include affiliated comments for.
218 * @type array $post__not_in Array of post IDs to exclude affiliated comments for.
220 * @type int $post_author Comment author ID to limit results by. Default empty.
221 * @type string $post_status Post status to retrieve affiliated comments for.
223 * @type string $post_type Post type to retrieve affiliated comments for.
225 * @type string $post_name Post name to retrieve affiliated comments for.
227 * @type int $post_parent Post parent ID to retrieve affiliated comments for.
229 * @type string $search Search term(s) to retrieve matching comments for.
231 * @type string $status Comment status to limit results by. Accepts 'hold'
232 * (`comment_status=0`), 'approve' (`comment_status=1`),
233 * 'all', or a custom comment status. Default 'all'.
234 * @type string|array $type Include comments of a given type, or array of types.
235 * Accepts 'comment', 'pings' (includes 'pingback' and
236 * 'trackback'), or anycustom type string. Default empty.
237 * @type array $type__in Include comments from a given array of comment types.
239 * @type array $type__not_in Exclude comments from a given array of comment types.
241 * @type int $user_id Include comments for a specific user ID. Default empty.
242 * @type bool|string $hierarchical Whether to include comment descendants in the results.
243 * 'threaded' returns a tree, with each comment's children
244 * stored in a `children` property on the `WP_Comment`
245 * object. 'flat' returns a flat array of found comments plus
246 * their children. Pass `false` to leave out descendants.
247 * The parameter is ignored (forced to `false`) when
248 * `$fields` is 'ids' or 'counts'. Accepts 'threaded',
249 * 'flat', or false. Default: false.
250 * @type bool $update_comment_meta_cache Whether to prime the metadata cache for found comments.
252 * @type bool $update_comment_post_cache Whether to prime the cache for comment posts.
256 public function __construct( $query = '' ) {
257 $this->query_var_defaults = array(
258 'author_email' => '',
260 'author__not_in' => '',
261 'include_unapproved' => '',
265 'comment__not_in' => '',
269 'no_found_rows' => true,
273 'post_author__in' => '',
274 'post_author__not_in' => '',
278 'post__not_in' => '',
287 'type__not_in' => '',
294 'date_query' => null, // See WP_Date_Query
295 'hierarchical' => false,
296 'update_comment_meta_cache' => true,
297 'update_comment_post_cache' => false,
300 if ( ! empty( $query ) ) {
301 $this->query( $query );
306 * Parse arguments passed to the comment query with default query parameters.
308 * @since 4.2.0 Extracted from WP_Comment_Query::query().
312 * @param string|array $query WP_Comment_Query arguments. See WP_Comment_Query::__construct()
314 public function parse_query( $query = '' ) {
315 if ( empty( $query ) ) {
316 $query = $this->query_vars;
319 $this->query_vars = wp_parse_args( $query, $this->query_var_defaults );
320 do_action_ref_array( 'parse_comment_query', array( &$this ) );
324 * Sets up the WordPress query for retrieving comments.
327 * @since 4.1.0 Introduced 'comment__in', 'comment__not_in', 'post_author__in',
328 * 'post_author__not_in', 'author__in', 'author__not_in', 'post__in',
329 * 'post__not_in', 'include_unapproved', 'type__in', and 'type__not_in'
330 * arguments to $query_vars.
331 * @since 4.2.0 Moved parsing to WP_Comment_Query::parse_query().
334 * @param string|array $query Array or URL query string of parameters.
335 * @return array|int List of comments, or number of comments when 'count' is passed as a query var.
337 public function query( $query ) {
338 $this->query_vars = wp_parse_args( $query );
339 return $this->get_comments();
343 * Get a list of comments matching the query vars.
348 * @global wpdb $wpdb WordPress database abstraction object.
350 * @return int|array The list of comments.
352 public function get_comments() {
355 $this->parse_query();
358 $this->meta_query = new WP_Meta_Query();
359 $this->meta_query->parse_query_vars( $this->query_vars );
362 * Fires before comments are retrieved.
366 * @param WP_Comment_Query &$this Current instance of WP_Comment_Query, passed by reference.
368 do_action_ref_array( 'pre_get_comments', array( &$this ) );
370 // Reparse query vars, in case they were modified in a 'pre_get_comments' callback.
371 $this->meta_query->parse_query_vars( $this->query_vars );
372 if ( ! empty( $this->meta_query->queries ) ) {
373 $this->meta_query_clauses = $this->meta_query->get_sql( 'comment', $wpdb->comments, 'comment_ID', $this );
376 // $args can include anything. Only use the args defined in the query_var_defaults to compute the key.
377 $key = md5( serialize( wp_array_slice_assoc( $this->query_vars, array_keys( $this->query_var_defaults ) ) ) );
378 $last_changed = wp_cache_get( 'last_changed', 'comment' );
379 if ( ! $last_changed ) {
380 $last_changed = microtime();
381 wp_cache_set( 'last_changed', $last_changed, 'comment' );
383 $cache_key = "get_comment_ids:$key:$last_changed";
385 $comment_ids = wp_cache_get( $cache_key, 'comment' );
386 if ( false === $comment_ids ) {
387 $comment_ids = $this->get_comment_ids();
388 wp_cache_add( $cache_key, $comment_ids, 'comment' );
391 // If querying for a count only, there's nothing more to do.
392 if ( $this->query_vars['count'] ) {
393 // $comment_ids is actually a count in this case.
394 return intval( $comment_ids );
397 $comment_ids = array_map( 'intval', $comment_ids );
399 $this->comment_count = count( $this->comments );
401 if ( $comment_ids && $this->query_vars['number'] && ! $this->query_vars['no_found_rows'] ) {
403 * Filter the query used to retrieve found comment count.
407 * @param string $found_comments_query SQL query. Default 'SELECT FOUND_ROWS()'.
408 * @param WP_Comment_Query $comment_query The `WP_Comment_Query` instance.
410 $found_comments_query = apply_filters( 'found_comments_query', 'SELECT FOUND_ROWS()', $this );
411 $this->found_comments = (int) $wpdb->get_var( $found_comments_query );
413 $this->max_num_pages = ceil( $this->found_comments / $this->query_vars['number'] );
416 if ( 'ids' == $this->query_vars['fields'] ) {
417 $this->comments = $comment_ids;
418 return $this->comments;
421 _prime_comment_caches( $comment_ids, $this->query_vars['update_comment_meta_cache'] );
423 // Fetch full comment objects from the primed cache.
424 $_comments = array();
425 foreach ( $comment_ids as $comment_id ) {
426 if ( $_comment = get_comment( $comment_id ) ) {
427 $_comments[] = $_comment;
431 // Prime comment post caches.
432 if ( $this->query_vars['update_comment_post_cache'] ) {
433 $comment_post_ids = array();
434 foreach ( $_comments as $_comment ) {
435 $comment_post_ids[] = $_comment->comment_post_ID;
438 _prime_post_caches( $comment_post_ids, false, false );
442 * Filter the comment query results.
446 * @param array $results An array of comments.
447 * @param WP_Comment_Query &$this Current instance of WP_Comment_Query, passed by reference.
449 $_comments = apply_filters_ref_array( 'the_comments', array( $_comments, &$this ) );
451 // Convert to WP_Comment instances
452 $comments = array_map( 'get_comment', $_comments );
454 if ( $this->query_vars['hierarchical'] ) {
455 $comments = $this->fill_descendants( $comments );
458 $this->comments = $comments;
459 return $this->comments;
463 * Used internally to get a list of comment IDs matching the query vars.
468 * @global wpdb $wpdb WordPress database abstraction object.
470 protected function get_comment_ids() {
473 // Assemble clauses related to 'comment_approved'.
474 $approved_clauses = array();
476 // 'status' accepts an array or a comma-separated string.
477 $status_clauses = array();
478 $statuses = $this->query_vars['status'];
479 if ( ! is_array( $statuses ) ) {
480 $statuses = preg_split( '/[\s,]+/', $statuses );
483 // 'any' overrides other statuses.
484 if ( ! in_array( 'any', $statuses ) ) {
485 foreach ( $statuses as $status ) {
488 $status_clauses[] = "comment_approved = '0'";
492 $status_clauses[] = "comment_approved = '1'";
497 $status_clauses[] = "( comment_approved = '0' OR comment_approved = '1' )";
501 $status_clauses[] = $wpdb->prepare( "comment_approved = %s", $status );
506 if ( ! empty( $status_clauses ) ) {
507 $approved_clauses[] = '( ' . implode( ' OR ', $status_clauses ) . ' )';
511 // User IDs or emails whose unapproved comments are included, regardless of $status.
512 if ( ! empty( $this->query_vars['include_unapproved'] ) ) {
513 $include_unapproved = $this->query_vars['include_unapproved'];
515 // Accepts arrays or comma-separated strings.
516 if ( ! is_array( $include_unapproved ) ) {
517 $include_unapproved = preg_split( '/[\s,]+/', $include_unapproved );
520 $unapproved_ids = $unapproved_emails = array();
521 foreach ( $include_unapproved as $unapproved_identifier ) {
522 // Numeric values are assumed to be user ids.
523 if ( is_numeric( $unapproved_identifier ) ) {
524 $approved_clauses[] = $wpdb->prepare( "( user_id = %d AND comment_approved = '0' )", $unapproved_identifier );
526 // Otherwise we match against email addresses.
528 $approved_clauses[] = $wpdb->prepare( "( comment_author_email = %s AND comment_approved = '0' )", $unapproved_identifier );
533 // Collapse comment_approved clauses into a single OR-separated clause.
534 if ( ! empty( $approved_clauses ) ) {
535 if ( 1 === count( $approved_clauses ) ) {
536 $this->sql_clauses['where']['approved'] = $approved_clauses[0];
538 $this->sql_clauses['where']['approved'] = '( ' . implode( ' OR ', $approved_clauses ) . ' )';
542 $order = ( 'ASC' == strtoupper( $this->query_vars['order'] ) ) ? 'ASC' : 'DESC';
544 // Disable ORDER BY with 'none', an empty array, or boolean false.
545 if ( in_array( $this->query_vars['orderby'], array( 'none', array(), false ), true ) ) {
547 } elseif ( ! empty( $this->query_vars['orderby'] ) ) {
548 $ordersby = is_array( $this->query_vars['orderby'] ) ?
549 $this->query_vars['orderby'] :
550 preg_split( '/[,\s]/', $this->query_vars['orderby'] );
552 $orderby_array = array();
553 $found_orderby_comment_ID = false;
554 foreach ( $ordersby as $_key => $_value ) {
559 if ( is_int( $_key ) ) {
567 if ( ! $found_orderby_comment_ID && in_array( $_orderby, array( 'comment_ID', 'comment__in' ) ) ) {
568 $found_orderby_comment_ID = true;
571 $parsed = $this->parse_orderby( $_orderby );
577 if ( 'comment__in' === $_orderby ) {
578 $orderby_array[] = $parsed;
582 $orderby_array[] = $parsed . ' ' . $this->parse_order( $_order );
585 // If no valid clauses were found, order by comment_date_gmt.
586 if ( empty( $orderby_array ) ) {
587 $orderby_array[] = "$wpdb->comments.comment_date_gmt $order";
590 // To ensure determinate sorting, always include a comment_ID clause.
591 if ( ! $found_orderby_comment_ID ) {
592 $comment_ID_order = '';
594 // Inherit order from comment_date or comment_date_gmt, if available.
595 foreach ( $orderby_array as $orderby_clause ) {
596 if ( preg_match( '/comment_date(?:_gmt)*\ (ASC|DESC)/', $orderby_clause, $match ) ) {
597 $comment_ID_order = $match[1];
602 // If no date-related order is available, use the date from the first available clause.
603 if ( ! $comment_ID_order ) {
604 foreach ( $orderby_array as $orderby_clause ) {
605 if ( false !== strpos( 'ASC', $orderby_clause ) ) {
606 $comment_ID_order = 'ASC';
608 $comment_ID_order = 'DESC';
616 if ( ! $comment_ID_order ) {
617 $comment_ID_order = 'DESC';
620 $orderby_array[] = "$wpdb->comments.comment_ID $comment_ID_order";
623 $orderby = implode( ', ', $orderby_array );
625 $orderby = "$wpdb->comments.comment_date_gmt $order";
628 $number = absint( $this->query_vars['number'] );
629 $offset = absint( $this->query_vars['offset'] );
631 if ( ! empty( $number ) ) {
633 $limits = 'LIMIT ' . $offset . ',' . $number;
635 $limits = 'LIMIT ' . $number;
639 if ( $this->query_vars['count'] ) {
640 $fields = 'COUNT(*)';
642 $fields = "$wpdb->comments.comment_ID";
645 $post_id = absint( $this->query_vars['post_id'] );
646 if ( ! empty( $post_id ) ) {
647 $this->sql_clauses['where']['post_id'] = $wpdb->prepare( 'comment_post_ID = %d', $post_id );
650 // Parse comment IDs for an IN clause.
651 if ( ! empty( $this->query_vars['comment__in'] ) ) {
652 $this->sql_clauses['where']['comment__in'] = "$wpdb->comments.comment_ID IN ( " . implode( ',', wp_parse_id_list( $this->query_vars['comment__in'] ) ) . ' )';
655 // Parse comment IDs for a NOT IN clause.
656 if ( ! empty( $this->query_vars['comment__not_in'] ) ) {
657 $this->sql_clauses['where']['comment__not_in'] = "$wpdb->comments.comment_ID NOT IN ( " . implode( ',', wp_parse_id_list( $this->query_vars['comment__not_in'] ) ) . ' )';
660 // Parse comment parent IDs for an IN clause.
661 if ( ! empty( $this->query_vars['parent__in'] ) ) {
662 $this->sql_clauses['where']['parent__in'] = 'comment_parent IN ( ' . implode( ',', wp_parse_id_list( $this->query_vars['parent__in'] ) ) . ' )';
665 // Parse comment parent IDs for a NOT IN clause.
666 if ( ! empty( $this->query_vars['parent__not_in'] ) ) {
667 $this->sql_clauses['where']['parent__not_in'] = 'comment_parent NOT IN ( ' . implode( ',', wp_parse_id_list( $this->query_vars['parent__not_in'] ) ) . ' )';
670 // Parse comment post IDs for an IN clause.
671 if ( ! empty( $this->query_vars['post__in'] ) ) {
672 $this->sql_clauses['where']['post__in'] = 'comment_post_ID IN ( ' . implode( ',', wp_parse_id_list( $this->query_vars['post__in'] ) ) . ' )';
675 // Parse comment post IDs for a NOT IN clause.
676 if ( ! empty( $this->query_vars['post__not_in'] ) ) {
677 $this->sql_clauses['where']['post__not_in'] = 'comment_post_ID NOT IN ( ' . implode( ',', wp_parse_id_list( $this->query_vars['post__not_in'] ) ) . ' )';
680 if ( '' !== $this->query_vars['author_email'] ) {
681 $this->sql_clauses['where']['author_email'] = $wpdb->prepare( 'comment_author_email = %s', $this->query_vars['author_email'] );
684 if ( '' !== $this->query_vars['karma'] ) {
685 $this->sql_clauses['where']['karma'] = $wpdb->prepare( 'comment_karma = %d', $this->query_vars['karma'] );
688 // Filtering by comment_type: 'type', 'type__in', 'type__not_in'.
690 'IN' => array_merge( (array) $this->query_vars['type'], (array) $this->query_vars['type__in'] ),
691 'NOT IN' => (array) $this->query_vars['type__not_in'],
694 $comment_types = array();
695 foreach ( $raw_types as $operator => $_raw_types ) {
696 $_raw_types = array_unique( $_raw_types );
698 foreach ( $_raw_types as $type ) {
700 // An empty translates to 'all', for backward compatibility
707 $comment_types[ $operator ][] = "''";
711 $comment_types[ $operator ][] = "'pingback'";
712 $comment_types[ $operator ][] = "'trackback'";
716 $comment_types[ $operator ][] = $wpdb->prepare( '%s', $type );
721 if ( ! empty( $comment_types[ $operator ] ) ) {
722 $types_sql = implode( ', ', $comment_types[ $operator ] );
723 $this->sql_clauses['where']['comment_type__' . strtolower( str_replace( ' ', '_', $operator ) ) ] = "comment_type $operator ($types_sql)";
727 if ( $this->query_vars['hierarchical'] && ! $this->query_vars['parent'] ) {
728 $this->query_vars['parent'] = 0;
731 if ( '' !== $this->query_vars['parent'] ) {
732 $this->sql_clauses['where']['parent'] = $wpdb->prepare( 'comment_parent = %d', $this->query_vars['parent'] );
735 if ( is_array( $this->query_vars['user_id'] ) ) {
736 $this->sql_clauses['where']['user_id'] = 'user_id IN (' . implode( ',', array_map( 'absint', $this->query_vars['user_id'] ) ) . ')';
737 } elseif ( '' !== $this->query_vars['user_id'] ) {
738 $this->sql_clauses['where']['user_id'] = $wpdb->prepare( 'user_id = %d', $this->query_vars['user_id'] );
741 if ( '' !== $this->query_vars['search'] ) {
742 $search_sql = $this->get_search_sql(
743 $this->query_vars['search'],
744 array( 'comment_author', 'comment_author_email', 'comment_author_url', 'comment_author_IP', 'comment_content' )
747 // Strip leading 'AND'.
748 $this->sql_clauses['where']['search'] = preg_replace( '/^\s*AND\s*/', '', $search_sql );
751 // If any post-related query vars are passed, join the posts table.
752 $join_posts_table = false;
753 $plucked = wp_array_slice_assoc( $this->query_vars, array( 'post_author', 'post_name', 'post_parent', 'post_status', 'post_type' ) );
754 $post_fields = array_filter( $plucked );
756 if ( ! empty( $post_fields ) ) {
757 $join_posts_table = true;
758 foreach ( $post_fields as $field_name => $field_value ) {
759 // $field_value may be an array.
760 $esses = array_fill( 0, count( (array) $field_value ), '%s' );
761 $this->sql_clauses['where'][ $field_name ] = $wpdb->prepare( " {$wpdb->posts}.{$field_name} IN (" . implode( ',', $esses ) . ')', $field_value );
765 // Comment author IDs for an IN clause.
766 if ( ! empty( $this->query_vars['author__in'] ) ) {
767 $this->sql_clauses['where']['author__in'] = 'user_id IN ( ' . implode( ',', wp_parse_id_list( $this->query_vars['author__in'] ) ) . ' )';
770 // Comment author IDs for a NOT IN clause.
771 if ( ! empty( $this->query_vars['author__not_in'] ) ) {
772 $this->sql_clauses['where']['author__not_in'] = 'user_id NOT IN ( ' . implode( ',', wp_parse_id_list( $this->query_vars['author__not_in'] ) ) . ' )';
775 // Post author IDs for an IN clause.
776 if ( ! empty( $this->query_vars['post_author__in'] ) ) {
777 $join_posts_table = true;
778 $this->sql_clauses['where']['post_author__in'] = 'post_author IN ( ' . implode( ',', wp_parse_id_list( $this->query_vars['post_author__in'] ) ) . ' )';
781 // Post author IDs for a NOT IN clause.
782 if ( ! empty( $this->query_vars['post_author__not_in'] ) ) {
783 $join_posts_table = true;
784 $this->sql_clauses['where']['post_author__not_in'] = 'post_author NOT IN ( ' . implode( ',', wp_parse_id_list( $this->query_vars['post_author__not_in'] ) ) . ' )';
789 if ( $join_posts_table ) {
790 $join .= "JOIN $wpdb->posts ON $wpdb->posts.ID = $wpdb->comments.comment_post_ID";
793 if ( ! empty( $this->meta_query_clauses ) ) {
794 $join .= $this->meta_query_clauses['join'];
796 // Strip leading 'AND'.
797 $this->sql_clauses['where']['meta_query'] = preg_replace( '/^\s*AND\s*/', '', $this->meta_query_clauses['where'] );
799 if ( ! $this->query_vars['count'] ) {
800 $groupby = "{$wpdb->comments}.comment_ID";
804 $date_query = $this->query_vars['date_query'];
805 if ( ! empty( $date_query ) && is_array( $date_query ) ) {
806 $date_query_object = new WP_Date_Query( $date_query, 'comment_date' );
807 $this->sql_clauses['where']['date_query'] = preg_replace( '/^\s*AND\s*/', '', $date_query_object->get_sql() );
810 $where = implode( ' AND ', $this->sql_clauses['where'] );
812 $pieces = array( 'fields', 'join', 'where', 'orderby', 'limits', 'groupby' );
814 * Filter the comment query clauses.
818 * @param array $pieces A compacted array of comment query clauses.
819 * @param WP_Comment_Query &$this Current instance of WP_Comment_Query, passed by reference.
821 $clauses = apply_filters_ref_array( 'comments_clauses', array( compact( $pieces ), &$this ) );
823 $fields = isset( $clauses[ 'fields' ] ) ? $clauses[ 'fields' ] : '';
824 $join = isset( $clauses[ 'join' ] ) ? $clauses[ 'join' ] : '';
825 $where = isset( $clauses[ 'where' ] ) ? $clauses[ 'where' ] : '';
826 $orderby = isset( $clauses[ 'orderby' ] ) ? $clauses[ 'orderby' ] : '';
827 $limits = isset( $clauses[ 'limits' ] ) ? $clauses[ 'limits' ] : '';
828 $groupby = isset( $clauses[ 'groupby' ] ) ? $clauses[ 'groupby' ] : '';
830 $this->filtered_where_clause = $where;
833 $where = 'WHERE ' . $where;
837 $groupby = 'GROUP BY ' . $groupby;
841 $orderby = "ORDER BY $orderby";
845 if ( ! $this->query_vars['no_found_rows'] ) {
846 $found_rows = 'SQL_CALC_FOUND_ROWS';
849 $this->sql_clauses['select'] = "SELECT $found_rows $fields";
850 $this->sql_clauses['from'] = "FROM $wpdb->comments $join";
851 $this->sql_clauses['groupby'] = $groupby;
852 $this->sql_clauses['orderby'] = $orderby;
853 $this->sql_clauses['limits'] = $limits;
855 $this->request = "{$this->sql_clauses['select']} {$this->sql_clauses['from']} {$where} {$this->sql_clauses['groupby']} {$this->sql_clauses['orderby']} {$this->sql_clauses['limits']}";
857 if ( $this->query_vars['count'] ) {
858 return intval( $wpdb->get_var( $this->request ) );
860 $comment_ids = $wpdb->get_col( $this->request );
861 return array_map( 'intval', $comment_ids );
866 * Fetch descendants for located comments.
868 * Instead of calling `get_children()` separately on each child comment, we do a single set of queries to fetch
869 * the descendant trees for all matched top-level comments.
873 * @param array $comments Array of top-level comments whose descendants should be filled in.
876 protected function fill_descendants( $comments ) {
880 0 => wp_list_pluck( $comments, 'comment_ID' ),
884 * The WHERE clause for the descendant query is the same as for the top-level
885 * query, minus the `parent`, `parent__in`, and `parent__not_in` sub-clauses.
887 $_where = $this->filtered_where_clause;
888 $exclude_keys = array( 'parent', 'parent__in', 'parent__not_in' );
889 foreach ( $exclude_keys as $exclude_key ) {
890 if ( isset( $this->sql_clauses['where'][ $exclude_key ] ) ) {
891 $clause = $this->sql_clauses['where'][ $exclude_key ];
893 // Strip the clause as well as any adjacent ANDs.
894 $pattern = '|(?:AND)?\s*' . $clause . '\s*(?:AND)?|';
895 $_where_parts = preg_split( $pattern, $_where );
898 $_where_parts = array_filter( array_map( 'trim', $_where_parts ) );
900 // Reassemble with an AND.
901 $_where = implode( ' AND ', $_where_parts );
905 // Fetch an entire level of the descendant tree at a time.
908 $parent_ids = $levels[ $level ];
909 if ( ! $parent_ids ) {
913 $where = 'WHERE ' . $_where . ' AND comment_parent IN (' . implode( ',', array_map( 'intval', $parent_ids ) ) . ')';
914 $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" );
917 $levels[ $level ] = $comment_ids;
918 } while ( $comment_ids );
920 // Prime comment caches for non-top-level comments.
921 $descendant_ids = array();
922 for ( $i = 1; $i < count( $levels ); $i++ ) {
923 $descendant_ids = array_merge( $descendant_ids, $levels[ $i ] );
926 _prime_comment_caches( $descendant_ids, $this->query_vars['update_comment_meta_cache'] );
928 // Assemble a flat array of all comments + descendants.
929 $all_comments = $comments;
930 foreach ( $descendant_ids as $descendant_id ) {
931 $all_comments[] = get_comment( $descendant_id );
934 // If a threaded representation was requested, build the tree.
935 if ( 'threaded' === $this->query_vars['hierarchical'] ) {
936 $threaded_comments = $ref = array();
937 foreach ( $all_comments as $k => $c ) {
938 $_c = get_comment( $c->comment_ID );
940 // If the comment isn't in the reference array, it goes in the top level of the thread.
941 if ( ! isset( $ref[ $c->comment_parent ] ) ) {
942 $threaded_comments[ $_c->comment_ID ] = $_c;
943 $ref[ $_c->comment_ID ] = $threaded_comments[ $_c->comment_ID ];
945 // Otherwise, set it as a child of its parent.
948 $ref[ $_c->comment_parent ]->add_child( $_c );
949 $ref[ $_c->comment_ID ] = $ref[ $_c->comment_parent ]->get_child( $_c->comment_ID );
953 // Set the 'populated_children' flag, to ensure additional database queries aren't run.
954 foreach ( $ref as $_ref ) {
955 $_ref->populated_children( true );
958 $comments = $threaded_comments;
960 $comments = $all_comments;
967 * Used internally to generate an SQL string for searching across multiple columns
972 * @global wpdb $wpdb WordPress database abstraction object.
974 * @param string $string
978 protected function get_search_sql( $string, $cols ) {
981 $like = '%' . $wpdb->esc_like( $string ) . '%';
984 foreach ( $cols as $col ) {
985 $searches[] = $wpdb->prepare( "$col LIKE %s", $like );
988 return ' AND (' . implode(' OR ', $searches) . ')';
992 * Parse and sanitize 'orderby' keys passed to the comment query.
997 * @global wpdb $wpdb WordPress database abstraction object.
999 * @param string $orderby Alias for the field to order by.
1000 * @return string|false Value to used in the ORDER clause. False otherwise.
1002 protected function parse_orderby( $orderby ) {
1005 $allowed_keys = array(
1009 'comment_author_email',
1010 'comment_author_IP',
1011 'comment_author_url',
1023 if ( ! empty( $this->query_vars['meta_key'] ) ) {
1024 $allowed_keys[] = $this->query_vars['meta_key'];
1025 $allowed_keys[] = 'meta_value';
1026 $allowed_keys[] = 'meta_value_num';
1029 $meta_query_clauses = $this->meta_query->get_clauses();
1030 if ( $meta_query_clauses ) {
1031 $allowed_keys = array_merge( $allowed_keys, array_keys( $meta_query_clauses ) );
1035 if ( $orderby == $this->query_vars['meta_key'] || $orderby == 'meta_value' ) {
1036 $parsed = "$wpdb->commentmeta.meta_value";
1037 } elseif ( $orderby == 'meta_value_num' ) {
1038 $parsed = "$wpdb->commentmeta.meta_value+0";
1039 } elseif ( $orderby == 'comment__in' ) {
1040 $comment__in = implode( ',', array_map( 'absint', $this->query_vars['comment__in'] ) );
1041 $parsed = "FIELD( {$wpdb->comments}.comment_ID, $comment__in )";
1042 } elseif ( in_array( $orderby, $allowed_keys ) ) {
1044 if ( isset( $meta_query_clauses[ $orderby ] ) ) {
1045 $meta_clause = $meta_query_clauses[ $orderby ];
1046 $parsed = sprintf( "CAST(%s.meta_value AS %s)", esc_sql( $meta_clause['alias'] ), esc_sql( $meta_clause['cast'] ) );
1048 $parsed = "$wpdb->comments.$orderby";
1056 * Parse an 'order' query variable and cast it to ASC or DESC as necessary.
1061 * @param string $order The 'order' query variable.
1062 * @return string The sanitized 'order' query variable.
1064 protected function parse_order( $order ) {
1065 if ( ! is_string( $order ) || empty( $order ) ) {
1069 if ( 'ASC' === strtoupper( $order ) ) {