[ Index ]

PHP Cross Reference of WordPress Trunk (Updated Daily)

Search

title

Body

[close]

/wp-includes/ -> class-wp-comment-query.php (source)

   1  <?php
   2  /**
   3   * Comment API: WP_Comment_Query class
   4   *
   5   * @package WordPress
   6   * @subpackage Comments
   7   * @since 4.4.0
   8   */
   9  
  10  /**
  11   * Core class used for querying comments.
  12   *
  13   * @since 3.1.0
  14   *
  15   * @see WP_Comment_Query::__construct() for accepted arguments.
  16   */
  17  #[AllowDynamicProperties]
  18  class WP_Comment_Query {
  19  
  20      /**
  21       * SQL for database query.
  22       *
  23       * @since 4.0.1
  24       * @var string
  25       */
  26      public $request;
  27  
  28      /**
  29       * Metadata query container
  30       *
  31       * @since 3.5.0
  32       * @var WP_Meta_Query A meta query instance.
  33       */
  34      public $meta_query = false;
  35  
  36      /**
  37       * Metadata query clauses.
  38       *
  39       * @since 4.4.0
  40       * @var array
  41       */
  42      protected $meta_query_clauses;
  43  
  44      /**
  45       * SQL query clauses.
  46       *
  47       * @since 4.4.0
  48       * @var array
  49       */
  50      protected $sql_clauses = array(
  51          'select'  => '',
  52          'from'    => '',
  53          'where'   => array(),
  54          'groupby' => '',
  55          'orderby' => '',
  56          'limits'  => '',
  57      );
  58  
  59      /**
  60       * SQL WHERE clause.
  61       *
  62       * Stored after the {@see 'comments_clauses'} filter is run on the compiled WHERE sub-clauses.
  63       *
  64       * @since 4.4.2
  65       * @var string
  66       */
  67      protected $filtered_where_clause;
  68  
  69      /**
  70       * Date query container
  71       *
  72       * @since 3.7.0
  73       * @var WP_Date_Query A date query instance.
  74       */
  75      public $date_query = false;
  76  
  77      /**
  78       * Query vars set by the user.
  79       *
  80       * @since 3.1.0
  81       * @var array
  82       */
  83      public $query_vars;
  84  
  85      /**
  86       * Default values for query vars.
  87       *
  88       * @since 4.2.0
  89       * @var array
  90       */
  91      public $query_var_defaults;
  92  
  93      /**
  94       * List of comments located by the query.
  95       *
  96       * Null until a query has been run.
  97       *
  98       * @since 4.0.0
  99       * @var int[]|WP_Comment[]|null
 100       * @phpstan-var non-negative-int[]|array<int, WP_Comment>|null
 101       */
 102      public $comments;
 103  
 104      /**
 105       * The amount of found comments for the current query.
 106       *
 107       * @since 4.4.0
 108       * @var int
 109       * @phpstan-var non-negative-int
 110       */
 111      public $found_comments = 0;
 112  
 113      /**
 114       * The number of pages.
 115       *
 116       * @since 4.4.0
 117       * @var int
 118       * @phpstan-var non-negative-int
 119       */
 120      public $max_num_pages = 0;
 121  
 122      /**
 123       * Make private/protected methods readable for backward compatibility.
 124       *
 125       * @since 4.0.0
 126       *
 127       * @param string $name      Method to call.
 128       * @param array  $arguments Arguments to pass when calling.
 129       * @return mixed|false Return value of the callback, false otherwise.
 130       */
 131  	public function __call( $name, $arguments ) {
 132          if ( 'get_search_sql' === $name ) {
 133              return $this->get_search_sql( ...$arguments );
 134          }
 135          return false;
 136      }
 137  
 138      /**
 139       * Constructor.
 140       *
 141       * Sets up the comment query, based on the query vars passed.
 142       *
 143       * @since 4.2.0
 144       * @since 4.4.0 `$parent__in` and `$parent__not_in` were added.
 145       * @since 4.4.0 Order by `comment__in` was added. `$update_comment_meta_cache`, `$no_found_rows`,
 146       *              `$hierarchical`, and `$update_comment_post_cache` were added.
 147       * @since 4.5.0 Introduced the `$author_url` argument.
 148       * @since 4.6.0 Introduced the `$cache_domain` argument.
 149       * @since 4.9.0 Introduced the `$paged` argument.
 150       * @since 5.1.0 Introduced the `$meta_compare_key` argument.
 151       * @since 5.3.0 Introduced the `$meta_type_key` argument.
 152       *
 153       * @param string|array $query {
 154       *     Optional. Array or query string of comment query parameters. Default empty.
 155       *
 156       *     @type string          $author_email              Comment author email address. Default empty.
 157       *     @type string          $author_url                Comment author URL. Default empty.
 158       *     @type int[]           $author__in                Array of author IDs to include comments for. Default empty.
 159       *     @type int[]           $author__not_in            Array of author IDs to exclude comments for. Default empty.
 160       *     @type int[]           $comment__in               Array of comment IDs to include. Default empty.
 161       *     @type int[]           $comment__not_in           Array of comment IDs to exclude. Default empty.
 162       *     @type bool            $count                     Whether to return a comment count (true) or array of
 163       *                                                      comment objects (false). Default false.
 164       *     @type array           $date_query                Date query clauses to limit comments by. See WP_Date_Query.
 165       *                                                      Default null.
 166       *     @type string          $fields                    Comment fields to return. Accepts 'ids' for comment IDs
 167       *                                                      only or empty for all fields. Default empty.
 168       *     @type array           $include_unapproved        Array of IDs or email addresses of users whose unapproved
 169       *                                                      comments will be returned by the query regardless of
 170       *                                                      `$status`. Default empty.
 171       *     @type int             $karma                     Karma score to retrieve matching comments for.
 172       *                                                      Default empty.
 173       *     @type string|string[] $meta_key                  Meta key or keys to filter by.
 174       *     @type string|string[] $meta_value                Meta value or values to filter by.
 175       *     @type string          $meta_compare              MySQL operator used for comparing the meta value.
 176       *                                                      See WP_Meta_Query::__construct() for accepted values and default value.
 177       *     @type string          $meta_compare_key          MySQL operator used for comparing the meta key.
 178       *                                                      See WP_Meta_Query::__construct() for accepted values and default value.
 179       *     @type string          $meta_type                 MySQL data type that the meta_value column will be CAST to for comparisons.
 180       *                                                      See WP_Meta_Query::__construct() for accepted values and default value.
 181       *     @type string          $meta_type_key             MySQL data type that the meta_key column will be CAST to for comparisons.
 182       *                                                      See WP_Meta_Query::__construct() for accepted values and default value.
 183       *     @type array           $meta_query                An associative array of WP_Meta_Query arguments.
 184       *                                                      See WP_Meta_Query::__construct() for accepted values.
 185       *     @type int             $number                    Maximum number of comments to retrieve.
 186       *                                                      Default empty (no limit).
 187       *     @type int             $paged                     When used with `$number`, defines the page of results to return.
 188       *                                                      When used with `$offset`, `$offset` takes precedence. Default 1.
 189       *     @type int             $offset                    Number of comments to offset the query. Used to build
 190       *                                                      LIMIT clause. Default 0.
 191       *     @type bool            $no_found_rows             Whether to disable the `SQL_CALC_FOUND_ROWS` query.
 192       *                                                      Default: true.
 193       *     @type string|array    $orderby                   Comment status or array of statuses. To use 'meta_value'
 194       *                                                      or 'meta_value_num', `$meta_key` must also be defined.
 195       *                                                      To sort by a specific `$meta_query` clause, use that
 196       *                                                      clause's array key. Accepts:
 197       *                                                      - 'comment_agent'
 198       *                                                      - 'comment_approved'
 199       *                                                      - 'comment_author'
 200       *                                                      - 'comment_author_email'
 201       *                                                      - 'comment_author_IP'
 202       *                                                      - 'comment_author_url'
 203       *                                                      - 'comment_content'
 204       *                                                      - 'comment_date'
 205       *                                                      - 'comment_date_gmt'
 206       *                                                      - 'comment_ID'
 207       *                                                      - 'comment_karma'
 208       *                                                      - 'comment_parent'
 209       *                                                      - 'comment_post_ID'
 210       *                                                      - 'comment_type'
 211       *                                                      - 'user_id'
 212       *                                                      - 'comment__in'
 213       *                                                      - 'meta_value'
 214       *                                                      - 'meta_value_num'
 215       *                                                      - The value of `$meta_key`
 216       *                                                      - The array keys of `$meta_query`
 217       *                                                      - false, an empty array, or 'none' to disable `ORDER BY` clause.
 218       *                                                      Default: 'comment_date_gmt'.
 219       *     @type string          $order                     How to order retrieved comments. Accepts 'ASC', 'DESC'.
 220       *                                                      Default: 'DESC'.
 221       *     @type int             $parent                    Parent ID of comment to retrieve children of.
 222       *                                                      Default empty.
 223       *     @type int[]           $parent__in                Array of parent IDs of comments to retrieve children for.
 224       *                                                      Default empty.
 225       *     @type int[]           $parent__not_in            Array of parent IDs of comments *not* to retrieve
 226       *                                                      children for. Default empty.
 227       *     @type int[]           $post_author__in           Array of author IDs to retrieve comments for.
 228       *                                                      Default empty.
 229       *     @type int[]           $post_author__not_in       Array of author IDs *not* to retrieve comments for.
 230       *                                                      Default empty.
 231       *     @type int             $post_id                   Limit results to those affiliated with a given post ID.
 232       *                                                      Default 0.
 233       *     @type int[]           $post__in                  Array of post IDs to include affiliated comments for.
 234       *                                                      Default empty.
 235       *     @type int[]           $post__not_in              Array of post IDs to exclude affiliated comments for.
 236       *                                                      Default empty.
 237       *     @type int             $post_author               Post author ID to limit results by. Default empty.
 238       *     @type string|string[] $post_status               Post status or array of post statuses to retrieve
 239       *                                                      affiliated comments for. Pass 'any' to match any value.
 240       *                                                      Default empty.
 241       *     @type string|string[] $post_type                 Post type or array of post types to retrieve affiliated
 242       *                                                      comments for. Pass 'any' to match any value. Default empty.
 243       *     @type string          $post_name                 Post name to retrieve affiliated comments for.
 244       *                                                      Default empty.
 245       *     @type int             $post_parent               Post parent ID to retrieve affiliated comments for.
 246       *                                                      Default empty.
 247       *     @type string          $search                    Search term(s) to retrieve matching comments for.
 248       *                                                      Default empty.
 249       *     @type string|array    $status                    Comment statuses to limit results by. Accepts an array
 250       *                                                      or space/comma-separated list of 'hold' (`comment_status=0`),
 251       *                                                      'approve' (`comment_status=1`), 'all', or a custom
 252       *                                                      comment status. Default 'all'.
 253       *     @type string|string[] $type                      Include comments of a given type, or array of types.
 254       *                                                      Accepts 'comment', 'pings' (includes 'pingback' and
 255       *                                                      'trackback'), or any custom type string. Default empty.
 256       *     @type string[]        $type__in                  Include comments from a given array of comment types.
 257       *                                                      Default empty.
 258       *     @type string[]        $type__not_in              Exclude comments from a given array of comment types.
 259       *                                                      Default empty.
 260       *     @type int             $user_id                   Include comments for a specific user ID. Default empty.
 261       *     @type bool|string     $hierarchical              Whether to include comment descendants in the results.
 262       *                                                      - 'threaded' returns a tree, with each comment's children
 263       *                                                        stored in a `children` property on the `WP_Comment` object.
 264       *                                                      - 'flat' returns a flat array of found comments plus
 265       *                                                        their children.
 266       *                                                      - Boolean `false` leaves out descendants.
 267       *                                                      The parameter is ignored (forced to `false`) when
 268       *                                                      `$fields` is 'ids' or 'counts'. Accepts 'threaded',
 269       *                                                      'flat', or false. Default: false.
 270       *     @type string          $cache_domain              Unique cache key to be produced when this query is stored in
 271       *                                                      an object cache. Default is 'core'.
 272       *     @type bool            $update_comment_meta_cache Whether to prime the metadata cache for found comments.
 273       *                                                      Default true.
 274       *     @type bool            $update_comment_post_cache Whether to prime the cache for comment posts.
 275       *                                                      Default false.
 276       * }
 277       */
 278  	public function __construct( $query = '' ) {
 279          $this->query_var_defaults = array(
 280              'author_email'              => '',
 281              'author_url'                => '',
 282              'author__in'                => '',
 283              'author__not_in'            => '',
 284              'include_unapproved'        => '',
 285              'fields'                    => '',
 286              'ID'                        => '',
 287              'comment__in'               => '',
 288              'comment__not_in'           => '',
 289              'karma'                     => '',
 290              'number'                    => '',
 291              'offset'                    => '',
 292              'no_found_rows'             => true,
 293              'orderby'                   => '',
 294              'order'                     => 'DESC',
 295              'paged'                     => 1,
 296              'parent'                    => '',
 297              'parent__in'                => '',
 298              'parent__not_in'            => '',
 299              'post_author__in'           => '',
 300              'post_author__not_in'       => '',
 301              'post_ID'                   => '',
 302              'post_id'                   => 0,
 303              'post__in'                  => '',
 304              'post__not_in'              => '',
 305              'post_author'               => '',
 306              'post_name'                 => '',
 307              'post_parent'               => '',
 308              'post_status'               => '',
 309              'post_type'                 => '',
 310              'status'                    => 'all',
 311              'type'                      => '',
 312              'type__in'                  => '',
 313              'type__not_in'              => '',
 314              'user_id'                   => '',
 315              'search'                    => '',
 316              'count'                     => false,
 317              'meta_key'                  => '',
 318              'meta_value'                => '',
 319              'meta_query'                => '',
 320              'date_query'                => null, // See WP_Date_Query.
 321              'hierarchical'              => false,
 322              'cache_domain'              => 'core',
 323              'update_comment_meta_cache' => true,
 324              'update_comment_post_cache' => false,
 325          );
 326  
 327          if ( ! empty( $query ) ) {
 328              $this->query( $query );
 329          }
 330      }
 331  
 332      /**
 333       * Parse arguments passed to the comment query with default query parameters.
 334       *
 335       * @since 4.2.0 Extracted from WP_Comment_Query::query().
 336       *
 337       * @param string|array $query WP_Comment_Query arguments. See WP_Comment_Query::__construct() for accepted arguments.
 338       */
 339  	public function parse_query( $query = '' ) {
 340          if ( empty( $query ) ) {
 341              $query = $this->query_vars;
 342          }
 343  
 344          $this->query_vars = wp_parse_args( $query, $this->query_var_defaults );
 345  
 346          /**
 347           * Fires after the comment query vars have been parsed.
 348           *
 349           * @since 4.2.0
 350           *
 351           * @param WP_Comment_Query $query The WP_Comment_Query instance (passed by reference).
 352           */
 353          do_action_ref_array( 'parse_comment_query', array( &$this ) );
 354      }
 355  
 356      /**
 357       * Sets up the WordPress query for retrieving comments.
 358       *
 359       * @since 3.1.0
 360       * @since 4.1.0 Introduced 'comment__in', 'comment__not_in', 'post_author__in',
 361       *              'post_author__not_in', 'author__in', 'author__not_in', 'post__in',
 362       *              'post__not_in', 'include_unapproved', 'type__in', and 'type__not_in'
 363       *              arguments to $query_vars.
 364       * @since 4.2.0 Moved parsing to WP_Comment_Query::parse_query().
 365       *
 366       * @param string|array $query Array or URL query string of parameters.
 367       * @return WP_Comment[]|int[]|int List of comments, or number of comments when 'count' is passed as a query var.
 368       *
 369       * @phpstan-return (
 370       *     $query is array{ count: true, ... } ? non-negative-int : (
 371       *         $query is array{ fields: 'ids', ... } ? non-negative-int[] : array<int, WP_Comment>
 372       *     )
 373       * )
 374       */
 375  	public function query( $query ) {
 376          $this->query_vars = wp_parse_args( $query );
 377          return $this->get_comments();
 378      }
 379  
 380      /**
 381       * Get a list of comments matching the query vars.
 382       *
 383       * @since 4.2.0
 384       *
 385       * @global wpdb $wpdb WordPress database abstraction object.
 386       *
 387       * @return int|int[]|WP_Comment[] List of comments or number of found comments if `$count` argument is true.
 388       * @phpstan-return array<int, WP_Comment>|non-negative-int[]|non-negative-int
 389       */
 390  	public function get_comments() {
 391          global $wpdb;
 392  
 393          $this->parse_query();
 394  
 395          // Parse meta query.
 396          $this->meta_query = new WP_Meta_Query();
 397          $this->meta_query->parse_query_vars( $this->query_vars );
 398  
 399          /**
 400           * Fires before comments are retrieved.
 401           *
 402           * @since 3.1.0
 403           *
 404           * @param WP_Comment_Query $query Current instance of WP_Comment_Query (passed by reference).
 405           */
 406          do_action_ref_array( 'pre_get_comments', array( &$this ) );
 407  
 408          // Reparse query vars, in case they were modified in a 'pre_get_comments' callback.
 409          $this->meta_query->parse_query_vars( $this->query_vars );
 410          if ( ! empty( $this->meta_query->queries ) ) {
 411              $this->meta_query_clauses = $this->meta_query->get_sql( 'comment', $wpdb->comments, 'comment_ID', $this );
 412          }
 413  
 414          $comment_data = null;
 415  
 416          /**
 417           * Filters the comments data before the query takes place.
 418           *
 419           * Return a non-null value to bypass WordPress' default comment queries.
 420           *
 421           * The expected return type from this filter depends on the value passed
 422           * in the request query vars:
 423           * - When `$this->query_vars['count']` is set, the filter should return
 424           *   the comment count as an integer.
 425           * - When `'ids' === $this->query_vars['fields']`, the filter should return
 426           *   an array of comment IDs.
 427           * - Otherwise the filter should return an array of WP_Comment objects.
 428           *
 429           * Note that if the filter returns an array of comment data, it will be assigned
 430           * to the `comments` property of the current WP_Comment_Query instance.
 431           *
 432           * Filtering functions that require pagination information are encouraged to set
 433           * the `found_comments` and `max_num_pages` properties of the WP_Comment_Query object,
 434           * passed to the filter by reference. If WP_Comment_Query does not perform a database
 435           * query, it will not have enough information to generate these values itself.
 436           *
 437           * @since 5.3.0
 438           * @since 5.6.0 The returned array of comment data is assigned to the `comments` property
 439           *              of the current WP_Comment_Query instance.
 440           *
 441           * @param array|int|null   $comment_data Return an array of comment data to short-circuit WP's comment query,
 442           *                                       the comment count as an integer if `$this->query_vars['count']` is set,
 443           *                                       or null to allow WP to run its normal queries.
 444           * @param WP_Comment_Query $query        The WP_Comment_Query instance, passed by reference.
 445           */
 446          $comment_data = apply_filters_ref_array( 'comments_pre_query', array( $comment_data, &$this ) );
 447  
 448          if ( null !== $comment_data ) {
 449              if ( is_array( $comment_data ) && ! $this->query_vars['count'] ) {
 450                  $this->comments = $comment_data;
 451              }
 452  
 453              return $comment_data;
 454          }
 455  
 456          /*
 457           * Only use the args defined in the query_var_defaults to compute the key,
 458           * but ignore 'fields', 'update_comment_meta_cache', 'update_comment_post_cache' which does not affect query results.
 459           */
 460          $_args = wp_array_slice_assoc( $this->query_vars, array_keys( $this->query_var_defaults ) );
 461          unset( $_args['fields'], $_args['update_comment_meta_cache'], $_args['update_comment_post_cache'] );
 462  
 463          $key          = md5( serialize( $_args ) );
 464          $last_changed = wp_cache_get_last_changed( 'comment' );
 465  
 466          $cache_key   = "get_comments:$key";
 467          $cache_value = wp_cache_get_salted( $cache_key, 'comment-queries', $last_changed );
 468          if ( false === $cache_value ) {
 469              $comment_ids = $this->get_comment_ids();
 470              if ( $comment_ids ) {
 471                  $this->set_found_comments();
 472              }
 473  
 474              $cache_value = array(
 475                  'comment_ids'    => $comment_ids,
 476                  'found_comments' => $this->found_comments,
 477              );
 478              wp_cache_set_salted( $cache_key, $cache_value, 'comment-queries', $last_changed );
 479          } else {
 480              $comment_ids          = $cache_value['comment_ids'];
 481              $this->found_comments = $cache_value['found_comments'];
 482          }
 483  
 484          if ( $this->found_comments && $this->query_vars['number'] ) {
 485              $this->max_num_pages = (int) ceil( $this->found_comments / $this->query_vars['number'] );
 486          }
 487  
 488          // If querying for a count only, there's nothing more to do.
 489          if ( $this->query_vars['count'] ) {
 490              // $comment_ids is actually a count in this case.
 491              return (int) $comment_ids;
 492          }
 493  
 494          $comment_ids = array_map( 'intval', $comment_ids );
 495  
 496          if ( $this->query_vars['update_comment_meta_cache'] ) {
 497              wp_lazyload_comment_meta( $comment_ids );
 498          }
 499  
 500          if ( 'ids' === $this->query_vars['fields'] ) {
 501              $this->comments = $comment_ids;
 502              return $this->comments;
 503          }
 504  
 505          _prime_comment_caches( $comment_ids, false );
 506  
 507          // Fetch full comment objects from the primed cache.
 508          $_comments = array();
 509          foreach ( $comment_ids as $comment_id ) {
 510              $_comment = get_comment( $comment_id );
 511              if ( $_comment ) {
 512                  $_comments[] = $_comment;
 513              }
 514          }
 515  
 516          // Prime comment post caches.
 517          if ( $this->query_vars['update_comment_post_cache'] ) {
 518              $comment_post_ids = array();
 519              foreach ( $_comments as $_comment ) {
 520                  $comment_post_ids[] = $_comment->comment_post_ID;
 521              }
 522  
 523              _prime_post_caches( $comment_post_ids, false, false );
 524          }
 525  
 526          /**
 527           * Filters the comment query results.
 528           *
 529           * @since 3.1.0
 530           *
 531           * @param WP_Comment[]     $_comments An array of comments.
 532           * @param WP_Comment_Query $query     Current instance of WP_Comment_Query (passed by reference).
 533           */
 534          $_comments = apply_filters_ref_array( 'the_comments', array( $_comments, &$this ) );
 535  
 536          // Convert to WP_Comment instances.
 537          $comments = array_map( 'get_comment', $_comments );
 538  
 539          if ( $this->query_vars['hierarchical'] ) {
 540              $comments = $this->fill_descendants( $comments );
 541          }
 542  
 543          $this->comments = $comments;
 544          return $this->comments;
 545      }
 546  
 547      /**
 548       * Used internally to get a list of comment IDs matching the query vars.
 549       *
 550       * @since 4.4.0
 551       * @since 6.9.0 Excludes the 'note' comment type, unless 'all' or the 'note' types are requested.
 552       * @since 7.2.0 Excludes the 'reaction' comment type, unless 'all' or the 'reaction' types are requested.
 553       *
 554       * @global wpdb $wpdb WordPress database abstraction object.
 555       *
 556       * @return int|array A single count of comment IDs if a count query. An array of comment IDs if a full query.
 557       * @phpstan-return non-negative-int|list<non-negative-int>
 558       */
 559  	protected function get_comment_ids() {
 560          global $wpdb;
 561  
 562          // Assemble clauses related to 'comment_approved'.
 563          $approved_clauses = array();
 564  
 565          // 'status' accepts an array or a comma-separated string.
 566          $status_clauses = array();
 567          $statuses       = wp_parse_list( $this->query_vars['status'] );
 568  
 569          // Empty 'status' should be interpreted as 'all'.
 570          if ( empty( $statuses ) ) {
 571              $statuses = array( 'all' );
 572          }
 573  
 574          // 'any' overrides other statuses.
 575          if ( ! in_array( 'any', $statuses, true ) ) {
 576              foreach ( $statuses as $status ) {
 577                  switch ( $status ) {
 578                      case 'hold':
 579                          $status_clauses[] = "comment_approved = '0'";
 580                          break;
 581  
 582                      case 'approve':
 583                          $status_clauses[] = "comment_approved = '1'";
 584                          break;
 585  
 586                      case 'all':
 587                      case '':
 588                          $status_clauses[] = "( comment_approved = '0' OR comment_approved = '1' )";
 589                          break;
 590  
 591                      default:
 592                          $status_clauses[] = $wpdb->prepare( 'comment_approved = %s', $status );
 593                          break;
 594                  }
 595              }
 596  
 597              $approved_clauses[] = '( ' . implode( ' OR ', $status_clauses ) . ' )';
 598          }
 599  
 600          // User IDs or emails whose unapproved comments are included, regardless of $status.
 601          if ( ! empty( $this->query_vars['include_unapproved'] ) ) {
 602              $include_unapproved = wp_parse_list( $this->query_vars['include_unapproved'] );
 603  
 604              foreach ( $include_unapproved as $unapproved_identifier ) {
 605                  // Numeric values are assumed to be user IDs.
 606                  if ( is_numeric( $unapproved_identifier ) ) {
 607                      $approved_clauses[] = $wpdb->prepare( "( user_id = %d AND comment_approved = '0' )", $unapproved_identifier );
 608                  } else {
 609                      // Otherwise we match against email addresses.
 610                      if ( ! empty( $_GET['unapproved'] ) && ! empty( $_GET['moderation-hash'] ) ) {
 611                          // Only include requested comment.
 612                          $approved_clauses[] = $wpdb->prepare( "( comment_author_email = %s AND comment_approved = '0' AND {$wpdb->comments}.comment_ID = %d )", $unapproved_identifier, (int) $_GET['unapproved'] );
 613                      } else {
 614                          // Include all of the author's unapproved comments.
 615                          $approved_clauses[] = $wpdb->prepare( "( comment_author_email = %s AND comment_approved = '0' )", $unapproved_identifier );
 616                      }
 617                  }
 618              }
 619          }
 620  
 621          // Collapse comment_approved clauses into a single OR-separated clause.
 622          if ( ! empty( $approved_clauses ) ) {
 623              if ( 1 === count( $approved_clauses ) ) {
 624                  $this->sql_clauses['where']['approved'] = $approved_clauses[0];
 625              } else {
 626                  $this->sql_clauses['where']['approved'] = '( ' . implode( ' OR ', $approved_clauses ) . ' )';
 627              }
 628          }
 629  
 630          $order = ( 'ASC' === strtoupper( $this->query_vars['order'] ) ) ? 'ASC' : 'DESC';
 631  
 632          // Disable ORDER BY with 'none', an empty array, or boolean false.
 633          if ( in_array( $this->query_vars['orderby'], array( 'none', array(), false ), true ) ) {
 634              $orderby = '';
 635          } elseif ( ! empty( $this->query_vars['orderby'] ) ) {
 636              $ordersby = is_array( $this->query_vars['orderby'] ) ?
 637                  $this->query_vars['orderby'] :
 638                  preg_split( '/[,\s]/', $this->query_vars['orderby'] );
 639  
 640              $orderby_array            = array();
 641              $found_orderby_comment_id = false;
 642              foreach ( $ordersby as $_key => $_value ) {
 643                  if ( ! $_value ) {
 644                      continue;
 645                  }
 646  
 647                  if ( is_int( $_key ) ) {
 648                      $_orderby = $_value;
 649                      $_order   = $order;
 650                  } else {
 651                      $_orderby = $_key;
 652                      $_order   = $_value;
 653                  }
 654  
 655                  if ( ! $found_orderby_comment_id && in_array( $_orderby, array( 'comment_ID', 'comment__in' ), true ) ) {
 656                      $found_orderby_comment_id = true;
 657                  }
 658  
 659                  $parsed = $this->parse_orderby( $_orderby );
 660  
 661                  if ( ! $parsed ) {
 662                      continue;
 663                  }
 664  
 665                  if ( 'comment__in' === $_orderby ) {
 666                      $orderby_array[] = $parsed;
 667                      continue;
 668                  }
 669  
 670                  $orderby_array[] = $parsed . ' ' . $this->parse_order( $_order );
 671              }
 672  
 673              // If no valid clauses were found, order by comment_date_gmt.
 674              if ( empty( $orderby_array ) ) {
 675                  $orderby_array[] = "$wpdb->comments.comment_date_gmt $order";
 676              }
 677  
 678              // To ensure determinate sorting, always include a comment_ID clause.
 679              if ( ! $found_orderby_comment_id ) {
 680                  $comment_id_order = '';
 681  
 682                  // Inherit order from comment_date or comment_date_gmt, if available.
 683                  foreach ( $orderby_array as $orderby_clause ) {
 684                      if ( preg_match( '/comment_date(?:_gmt)*\ (ASC|DESC)/', $orderby_clause, $match ) ) {
 685                          $comment_id_order = $match[1];
 686                          break;
 687                      }
 688                  }
 689  
 690                  // If no date-related order is available, use the date from the first available clause.
 691                  if ( ! $comment_id_order ) {
 692                      foreach ( $orderby_array as $orderby_clause ) {
 693                          if ( str_contains( 'ASC', $orderby_clause ) ) {
 694                              $comment_id_order = 'ASC';
 695                          } else {
 696                              $comment_id_order = 'DESC';
 697                          }
 698  
 699                          break;
 700                      }
 701                  }
 702  
 703                  // Default to DESC.
 704                  if ( ! $comment_id_order ) {
 705                      $comment_id_order = 'DESC';
 706                  }
 707  
 708                  $orderby_array[] = "$wpdb->comments.comment_ID $comment_id_order";
 709              }
 710  
 711              $orderby = implode( ', ', $orderby_array );
 712          } else {
 713              $orderby = "$wpdb->comments.comment_date_gmt $order";
 714          }
 715  
 716          $number = absint( $this->query_vars['number'] );
 717          $offset = absint( $this->query_vars['offset'] );
 718          $paged  = absint( $this->query_vars['paged'] );
 719          $limits = '';
 720  
 721          if ( ! empty( $number ) ) {
 722              if ( $offset ) {
 723                  $limits = 'LIMIT ' . $offset . ',' . $number;
 724              } else {
 725                  $limits = 'LIMIT ' . ( $number * ( $paged - 1 ) ) . ',' . $number;
 726              }
 727          }
 728  
 729          if ( $this->query_vars['count'] ) {
 730              $fields = 'COUNT(*)';
 731          } else {
 732              $fields = "$wpdb->comments.comment_ID";
 733          }
 734  
 735          $post_id = absint( $this->query_vars['post_id'] );
 736          if ( ! empty( $post_id ) ) {
 737              $this->sql_clauses['where']['post_id'] = $wpdb->prepare( 'comment_post_ID = %d', $post_id );
 738          }
 739  
 740          // Parse comment IDs for an IN clause.
 741          if ( ! empty( $this->query_vars['comment__in'] ) ) {
 742              $this->sql_clauses['where']['comment__in'] = "$wpdb->comments.comment_ID IN ( " . implode( ',', wp_parse_id_list( $this->query_vars['comment__in'] ) ) . ' )';
 743          }
 744  
 745          // Parse comment IDs for a NOT IN clause.
 746          if ( ! empty( $this->query_vars['comment__not_in'] ) ) {
 747              $this->sql_clauses['where']['comment__not_in'] = "$wpdb->comments.comment_ID NOT IN ( " . implode( ',', wp_parse_id_list( $this->query_vars['comment__not_in'] ) ) . ' )';
 748          }
 749  
 750          // Parse comment parent IDs for an IN clause.
 751          if ( ! empty( $this->query_vars['parent__in'] ) ) {
 752              $this->sql_clauses['where']['parent__in'] = 'comment_parent IN ( ' . implode( ',', wp_parse_id_list( $this->query_vars['parent__in'] ) ) . ' )';
 753          }
 754  
 755          // Parse comment parent IDs for a NOT IN clause.
 756          if ( ! empty( $this->query_vars['parent__not_in'] ) ) {
 757              $this->sql_clauses['where']['parent__not_in'] = 'comment_parent NOT IN ( ' . implode( ',', wp_parse_id_list( $this->query_vars['parent__not_in'] ) ) . ' )';
 758          }
 759  
 760          // Parse comment post IDs for an IN clause.
 761          if ( ! empty( $this->query_vars['post__in'] ) ) {
 762              $this->sql_clauses['where']['post__in'] = 'comment_post_ID IN ( ' . implode( ',', wp_parse_id_list( $this->query_vars['post__in'] ) ) . ' )';
 763          }
 764  
 765          // Parse comment post IDs for a NOT IN clause.
 766          if ( ! empty( $this->query_vars['post__not_in'] ) ) {
 767              $this->sql_clauses['where']['post__not_in'] = 'comment_post_ID NOT IN ( ' . implode( ',', wp_parse_id_list( $this->query_vars['post__not_in'] ) ) . ' )';
 768          }
 769  
 770          if ( '' !== $this->query_vars['author_email'] ) {
 771              $this->sql_clauses['where']['author_email'] = $wpdb->prepare( 'comment_author_email = %s', $this->query_vars['author_email'] );
 772          }
 773  
 774          if ( '' !== $this->query_vars['author_url'] ) {
 775              $this->sql_clauses['where']['author_url'] = $wpdb->prepare( 'comment_author_url = %s', $this->query_vars['author_url'] );
 776          }
 777  
 778          if ( '' !== $this->query_vars['karma'] ) {
 779              $this->sql_clauses['where']['karma'] = $wpdb->prepare( 'comment_karma = %d', $this->query_vars['karma'] );
 780          }
 781  
 782          // Filtering by comment_type: 'type', 'type__in', 'type__not_in'.
 783          $raw_types = array(
 784              'IN'     => array_merge( (array) $this->query_vars['type'], (array) $this->query_vars['type__in'] ),
 785              'NOT IN' => (array) $this->query_vars['type__not_in'],
 786          );
 787  
 788          // Exclude the 'note' and 'reaction' comment types, unless 'all' types or that type explicitly are requested.
 789          if ( ! in_array( 'all', $raw_types['IN'], true ) ) {
 790              foreach ( array( 'note', 'reaction' ) as $excluded_type ) {
 791                  if (
 792                      ! in_array( $excluded_type, $raw_types['IN'], true ) &&
 793                      ! in_array( $excluded_type, $raw_types['NOT IN'], true )
 794                  ) {
 795                      $raw_types['NOT IN'][] = $excluded_type;
 796                  }
 797              }
 798          }
 799  
 800          $comment_types = array();
 801          foreach ( $raw_types as $operator => $_raw_types ) {
 802              $_raw_types = array_unique( $_raw_types );
 803  
 804              foreach ( $_raw_types as $type ) {
 805                  switch ( $type ) {
 806                      // An empty translates to 'all', for backward compatibility.
 807                      case '':
 808                      case 'all':
 809                          break;
 810  
 811                      case 'comment':
 812                      case 'comments':
 813                          $comment_types[ $operator ][] = "''";
 814                          $comment_types[ $operator ][] = "'comment'";
 815                          break;
 816  
 817                      case 'pings':
 818                          $comment_types[ $operator ][] = "'pingback'";
 819                          $comment_types[ $operator ][] = "'trackback'";
 820                          break;
 821  
 822                      default:
 823                          $comment_types[ $operator ][] = $wpdb->prepare( '%s', $type );
 824                          break;
 825                  }
 826              }
 827  
 828              if ( ! empty( $comment_types[ $operator ] ) ) {
 829                  $types_sql = implode( ', ', $comment_types[ $operator ] );
 830                  $this->sql_clauses['where'][ 'comment_type__' . strtolower( str_replace( ' ', '_', $operator ) ) ] = "comment_type $operator ($types_sql)";
 831              }
 832          }
 833  
 834          $parent = $this->query_vars['parent'];
 835          if ( $this->query_vars['hierarchical'] && ! $parent ) {
 836              $parent = 0;
 837          }
 838  
 839          if ( '' !== $parent ) {
 840              $this->sql_clauses['where']['parent'] = $wpdb->prepare( 'comment_parent = %d', $parent );
 841          }
 842  
 843          if ( is_array( $this->query_vars['user_id'] ) ) {
 844              $this->sql_clauses['where']['user_id'] = 'user_id IN (' . implode( ',', array_map( 'absint', $this->query_vars['user_id'] ) ) . ')';
 845          } elseif ( '' !== $this->query_vars['user_id'] ) {
 846              $this->sql_clauses['where']['user_id'] = $wpdb->prepare( 'user_id = %d', $this->query_vars['user_id'] );
 847          }
 848  
 849          // Falsey search strings are ignored.
 850          if ( isset( $this->query_vars['search'] ) && strlen( $this->query_vars['search'] ) ) {
 851              $search_sql = $this->get_search_sql(
 852                  $this->query_vars['search'],
 853                  array( 'comment_author', 'comment_author_email', 'comment_author_url', 'comment_author_IP', 'comment_content' )
 854              );
 855  
 856              // Strip leading 'AND'.
 857              $this->sql_clauses['where']['search'] = preg_replace( '/^\s*AND\s*/', '', $search_sql );
 858          }
 859  
 860          // If any post-related query vars are passed, join the posts table.
 861          $join_posts_table = false;
 862          $plucked          = wp_array_slice_assoc( $this->query_vars, array( 'post_author', 'post_name', 'post_parent' ) );
 863          $post_fields      = array_filter( $plucked );
 864  
 865          if ( ! empty( $post_fields ) ) {
 866              $join_posts_table = true;
 867              foreach ( $post_fields as $field_name => $field_value ) {
 868                  // $field_value may be an array.
 869                  $esses = array_fill( 0, count( (array) $field_value ), '%s' );
 870  
 871                  // phpcs:ignore WordPress.DB.PreparedSQLPlaceholders.UnfinishedPrepare
 872                  $this->sql_clauses['where'][ $field_name ] = $wpdb->prepare( " {$wpdb->posts}.{$field_name} IN (" . implode( ',', $esses ) . ')', $field_value );
 873              }
 874          }
 875  
 876          // 'post_status' and 'post_type' are handled separately, due to the specialized behavior of 'any'.
 877          foreach ( array( 'post_status', 'post_type' ) as $field_name ) {
 878              $q_values = array();
 879              if ( ! empty( $this->query_vars[ $field_name ] ) ) {
 880                  $q_values = $this->query_vars[ $field_name ];
 881                  if ( ! is_array( $q_values ) ) {
 882                      $q_values = explode( ',', $q_values );
 883                  }
 884  
 885                  // 'any' will cause the query var to be ignored.
 886                  if ( in_array( 'any', $q_values, true ) || empty( $q_values ) ) {
 887                      continue;
 888                  }
 889  
 890                  $join_posts_table = true;
 891  
 892                  $esses = array_fill( 0, count( $q_values ), '%s' );
 893  
 894                  // phpcs:ignore WordPress.DB.PreparedSQLPlaceholders.UnfinishedPrepare
 895                  $this->sql_clauses['where'][ $field_name ] = $wpdb->prepare( " {$wpdb->posts}.{$field_name} IN (" . implode( ',', $esses ) . ')', $q_values );
 896              }
 897          }
 898  
 899          // Comment author IDs for an IN clause.
 900          if ( ! empty( $this->query_vars['author__in'] ) ) {
 901              $this->sql_clauses['where']['author__in'] = 'user_id IN ( ' . implode( ',', wp_parse_id_list( $this->query_vars['author__in'] ) ) . ' )';
 902          }
 903  
 904          // Comment author IDs for a NOT IN clause.
 905          if ( ! empty( $this->query_vars['author__not_in'] ) ) {
 906              $this->sql_clauses['where']['author__not_in'] = 'user_id NOT IN ( ' . implode( ',', wp_parse_id_list( $this->query_vars['author__not_in'] ) ) . ' )';
 907          }
 908  
 909          // Post author IDs for an IN clause.
 910          if ( ! empty( $this->query_vars['post_author__in'] ) ) {
 911              $join_posts_table                              = true;
 912              $this->sql_clauses['where']['post_author__in'] = 'post_author IN ( ' . implode( ',', wp_parse_id_list( $this->query_vars['post_author__in'] ) ) . ' )';
 913          }
 914  
 915          // Post author IDs for a NOT IN clause.
 916          if ( ! empty( $this->query_vars['post_author__not_in'] ) ) {
 917              $join_posts_table                                  = true;
 918              $this->sql_clauses['where']['post_author__not_in'] = 'post_author NOT IN ( ' . implode( ',', wp_parse_id_list( $this->query_vars['post_author__not_in'] ) ) . ' )';
 919          }
 920  
 921          $join    = '';
 922          $groupby = '';
 923  
 924          if ( $join_posts_table ) {
 925              $join .= "JOIN $wpdb->posts ON $wpdb->posts.ID = $wpdb->comments.comment_post_ID";
 926          }
 927  
 928          if ( ! empty( $this->meta_query_clauses ) ) {
 929              $join .= $this->meta_query_clauses['join'];
 930  
 931              // Strip leading 'AND'.
 932              $this->sql_clauses['where']['meta_query'] = preg_replace( '/^\s*AND\s*/', '', $this->meta_query_clauses['where'] );
 933  
 934              if ( ! $this->query_vars['count'] ) {
 935                  $groupby = "{$wpdb->comments}.comment_ID";
 936              }
 937          }
 938  
 939          if ( ! empty( $this->query_vars['date_query'] ) && is_array( $this->query_vars['date_query'] ) ) {
 940              $this->date_query = new WP_Date_Query( $this->query_vars['date_query'], 'comment_date' );
 941  
 942              // Strip leading 'AND'.
 943              $this->sql_clauses['where']['date_query'] = preg_replace( '/^\s*AND\s*/', '', $this->date_query->get_sql() );
 944          }
 945  
 946          $where = implode( ' AND ', $this->sql_clauses['where'] );
 947  
 948          $pieces = array( 'fields', 'join', 'where', 'orderby', 'limits', 'groupby' );
 949  
 950          /**
 951           * Filters the comment query clauses.
 952           *
 953           * @since 3.1.0
 954           *
 955           * @param string[]         $clauses {
 956           *     Associative array of the clauses for the query.
 957           *
 958           *     @type string $fields   The SELECT clause of the query.
 959           *     @type string $join     The JOIN clause of the query.
 960           *     @type string $where    The WHERE clause of the query.
 961           *     @type string $orderby  The ORDER BY clause of the query.
 962           *     @type string $limits   The LIMIT clause of the query.
 963           *     @type string $groupby  The GROUP BY clause of the query.
 964           * }
 965           * @param WP_Comment_Query $query   Current instance of WP_Comment_Query (passed by reference).
 966           */
 967          $clauses = apply_filters_ref_array( 'comments_clauses', array( compact( $pieces ), &$this ) );
 968  
 969          $fields  = $clauses['fields'] ?? '';
 970          $join    = $clauses['join'] ?? '';
 971          $where   = $clauses['where'] ?? '';
 972          $orderby = $clauses['orderby'] ?? '';
 973          $limits  = $clauses['limits'] ?? '';
 974          $groupby = $clauses['groupby'] ?? '';
 975  
 976          $this->filtered_where_clause = $where;
 977  
 978          if ( $where ) {
 979              $where = 'WHERE ' . $where;
 980          }
 981  
 982          if ( $groupby ) {
 983              $groupby = 'GROUP BY ' . $groupby;
 984          }
 985  
 986          if ( $orderby ) {
 987              $orderby = "ORDER BY $orderby";
 988          }
 989  
 990          $found_rows = '';
 991          if ( ! $this->query_vars['no_found_rows'] ) {
 992              $found_rows = 'SQL_CALC_FOUND_ROWS';
 993          }
 994  
 995          $this->sql_clauses['select']  = "SELECT $found_rows $fields";
 996          $this->sql_clauses['from']    = "FROM $wpdb->comments $join";
 997          $this->sql_clauses['groupby'] = $groupby;
 998          $this->sql_clauses['orderby'] = $orderby;
 999          $this->sql_clauses['limits']  = $limits;
1000  
1001          // Beginning of the string is on a new line to prevent leading whitespace. See https://core.trac.wordpress.org/ticket/56841.
1002          $this->request =
1003              "{$this->sql_clauses['select']}
1004               {$this->sql_clauses['from']}
1005               {$where}
1006               {$this->sql_clauses['groupby']}
1007               {$this->sql_clauses['orderby']}
1008               {$this->sql_clauses['limits']}";
1009  
1010          if ( $this->query_vars['count'] ) {
1011              return (int) $wpdb->get_var( $this->request );
1012          } else {
1013              $comment_ids = $wpdb->get_col( $this->request );
1014              return array_map( 'intval', $comment_ids );
1015          }
1016      }
1017  
1018      /**
1019       * Populates found_comments and max_num_pages properties for the current
1020       * query if the limit clause was used.
1021       *
1022       * @since 4.6.0
1023       *
1024       * @global wpdb $wpdb WordPress database abstraction object.
1025       */
1026  	private function set_found_comments() {
1027          global $wpdb;
1028  
1029          if ( $this->query_vars['number'] && ! $this->query_vars['no_found_rows'] ) {
1030              /**
1031               * Filters the query used to retrieve found comment count.
1032               *
1033               * @since 4.4.0
1034               *
1035               * @param string           $found_comments_query SQL query. Default 'SELECT FOUND_ROWS()'.
1036               * @param WP_Comment_Query $comment_query        The `WP_Comment_Query` instance.
1037               */
1038              $found_comments_query = apply_filters( 'found_comments_query', 'SELECT FOUND_ROWS()', $this );
1039  
1040              $this->found_comments = (int) $wpdb->get_var( $found_comments_query );
1041          }
1042      }
1043  
1044      /**
1045       * Fetch descendants for located comments.
1046       *
1047       * Instead of calling `get_children()` separately on each child comment, we do a single set of queries to fetch
1048       * the descendant trees for all matched top-level comments.
1049       *
1050       * @since 4.4.0
1051       *
1052       * @param WP_Comment[] $comments Array of top-level comments whose descendants should be filled in.
1053       * @return array
1054       */
1055  	protected function fill_descendants( $comments ) {
1056          $levels = array(
1057              0 => wp_list_pluck( $comments, 'comment_ID' ),
1058          );
1059  
1060          $key          = md5( serialize( wp_array_slice_assoc( $this->query_vars, array_keys( $this->query_var_defaults ) ) ) );
1061          $last_changed = wp_cache_get_last_changed( 'comment' );
1062  
1063          // Fetch an entire level of the descendant tree at a time.
1064          $level        = 0;
1065          $exclude_keys = array( 'parent', 'parent__in', 'parent__not_in' );
1066          do {
1067              // Parent-child relationships may be cached. Only query for those that are not.
1068              $child_ids           = array();
1069              $uncached_parent_ids = array();
1070              $_parent_ids         = $levels[ $level ];
1071              if ( $_parent_ids ) {
1072                  $cache_keys = array();
1073                  foreach ( $_parent_ids as $parent_id ) {
1074                      $cache_keys[ $parent_id ] = "get_comment_child_ids:$parent_id:$key";
1075                  }
1076                  $cache_data = wp_cache_get_multiple_salted( array_values( $cache_keys ), 'comment-queries', $last_changed );
1077                  foreach ( $_parent_ids as $parent_id ) {
1078                      $parent_child_ids = $cache_data[ $cache_keys[ $parent_id ] ];
1079                      if ( false !== $parent_child_ids ) {
1080                          $child_ids = array_merge( $child_ids, $parent_child_ids );
1081                      } else {
1082                          $uncached_parent_ids[] = $parent_id;
1083                      }
1084                  }
1085              }
1086  
1087              if ( $uncached_parent_ids ) {
1088                  // Fetch this level of comments.
1089                  $parent_query_args = $this->query_vars;
1090                  foreach ( $exclude_keys as $exclude_key ) {
1091                      $parent_query_args[ $exclude_key ] = '';
1092                  }
1093                  $parent_query_args['parent__in']    = $uncached_parent_ids;
1094                  $parent_query_args['no_found_rows'] = true;
1095                  $parent_query_args['hierarchical']  = false;
1096                  $parent_query_args['offset']        = 0;
1097                  $parent_query_args['number']        = 0;
1098  
1099                  $level_comments = get_comments( $parent_query_args );
1100  
1101                  // Cache parent-child relationships.
1102                  $parent_map = array_fill_keys( $uncached_parent_ids, array() );
1103                  foreach ( $level_comments as $level_comment ) {
1104                      $parent_map[ $level_comment->comment_parent ][] = $level_comment->comment_ID;
1105                      $child_ids[]                                    = $level_comment->comment_ID;
1106                  }
1107  
1108                  $data = array();
1109                  foreach ( $parent_map as $parent_id => $children ) {
1110                      $cache_key          = "get_comment_child_ids:$parent_id:$key";
1111                      $data[ $cache_key ] = $children;
1112                  }
1113                  wp_cache_set_multiple_salted( $data, 'comment-queries', $last_changed );
1114              }
1115  
1116              ++$level;
1117              $levels[ $level ] = $child_ids;
1118          } while ( $child_ids );
1119  
1120          // Prime comment caches for non-top-level comments.
1121          $descendant_ids = array();
1122          for ( $i = 1, $c = count( $levels ); $i < $c; $i++ ) {
1123              $descendant_ids = array_merge( $descendant_ids, $levels[ $i ] );
1124          }
1125  
1126          _prime_comment_caches( $descendant_ids, $this->query_vars['update_comment_meta_cache'] );
1127  
1128          // Assemble a flat array of all comments + descendants.
1129          $all_comments = $comments;
1130          foreach ( $descendant_ids as $descendant_id ) {
1131              $descendant = get_comment( $descendant_id );
1132              if ( $descendant instanceof WP_Comment ) {
1133                  $all_comments[] = $descendant;
1134              }
1135          }
1136  
1137          // If a threaded representation was requested, build the tree.
1138          if ( 'threaded' === $this->query_vars['hierarchical'] ) {
1139              $threaded_comments = array();
1140              $ref               = array();
1141              foreach ( $all_comments as $k => $c ) {
1142                  $_c = get_comment( $c->comment_ID );
1143  
1144                  // If the comment isn't in the reference array, it goes in the top level of the thread.
1145                  if ( ! isset( $ref[ $c->comment_parent ] ) ) {
1146                      $threaded_comments[ $_c->comment_ID ] = $_c;
1147                      $ref[ $_c->comment_ID ]               = $threaded_comments[ $_c->comment_ID ];
1148  
1149                      // Otherwise, set it as a child of its parent.
1150                  } else {
1151  
1152                      $ref[ $_c->comment_parent ]->add_child( $_c );
1153                      $ref[ $_c->comment_ID ] = $ref[ $_c->comment_parent ]->get_child( $_c->comment_ID );
1154                  }
1155              }
1156  
1157              // Set the 'populated_children' flag, to ensure additional database queries aren't run.
1158              foreach ( $ref as $_ref ) {
1159                  $_ref->populated_children( true );
1160              }
1161  
1162              $comments = $threaded_comments;
1163          } else {
1164              $comments = $all_comments;
1165          }
1166  
1167          return $comments;
1168      }
1169  
1170      /**
1171       * Used internally to generate an SQL string for searching across multiple columns.
1172       *
1173       * @since 3.1.0
1174       *
1175       * @global wpdb $wpdb WordPress database abstraction object.
1176       *
1177       * @param string   $search  Search string.
1178       * @param string[] $columns Array of columns to search.
1179       * @return string Search SQL.
1180       */
1181  	protected function get_search_sql( $search, $columns ) {
1182          global $wpdb;
1183  
1184          $like = '%' . $wpdb->esc_like( $search ) . '%';
1185  
1186          $searches = array();
1187          foreach ( $columns as $column ) {
1188              $searches[] = $wpdb->prepare( "$column LIKE %s", $like );
1189          }
1190  
1191          return ' AND (' . implode( ' OR ', $searches ) . ')';
1192      }
1193  
1194      /**
1195       * Parse and sanitize 'orderby' keys passed to the comment query.
1196       *
1197       * @since 4.2.0
1198       *
1199       * @global wpdb $wpdb WordPress database abstraction object.
1200       *
1201       * @param string $orderby Alias for the field to order by.
1202       * @return string|false Value to used in the ORDER clause. False otherwise.
1203       */
1204  	protected function parse_orderby( $orderby ) {
1205          global $wpdb;
1206  
1207          $allowed_keys = array(
1208              'comment_agent',
1209              'comment_approved',
1210              'comment_author',
1211              'comment_author_email',
1212              'comment_author_IP',
1213              'comment_author_url',
1214              'comment_content',
1215              'comment_date',
1216              'comment_date_gmt',
1217              'comment_ID',
1218              'comment_karma',
1219              'comment_parent',
1220              'comment_post_ID',
1221              'comment_type',
1222              'user_id',
1223          );
1224  
1225          if ( ! empty( $this->query_vars['meta_key'] ) ) {
1226              $allowed_keys[] = $this->query_vars['meta_key'];
1227              $allowed_keys[] = 'meta_value';
1228              $allowed_keys[] = 'meta_value_num';
1229          }
1230  
1231          $meta_query_clauses = $this->meta_query->get_clauses();
1232          if ( $meta_query_clauses ) {
1233              $allowed_keys = array_merge( $allowed_keys, array_keys( $meta_query_clauses ) );
1234          }
1235  
1236          $parsed = false;
1237          if ( $this->query_vars['meta_key'] === $orderby || 'meta_value' === $orderby ) {
1238              $parsed = "$wpdb->commentmeta.meta_value";
1239          } elseif ( 'meta_value_num' === $orderby ) {
1240              $parsed = "$wpdb->commentmeta.meta_value+0";
1241          } elseif ( 'comment__in' === $orderby ) {
1242              $comment__in = implode( ',', array_map( 'absint', $this->query_vars['comment__in'] ) );
1243              $parsed      = "FIELD( {$wpdb->comments}.comment_ID, $comment__in )";
1244          } elseif ( in_array( $orderby, $allowed_keys, true ) ) {
1245  
1246              if ( isset( $meta_query_clauses[ $orderby ] ) ) {
1247                  $meta_clause = $meta_query_clauses[ $orderby ];
1248                  $parsed      = sprintf( 'CAST(%s.meta_value AS %s)', esc_sql( $meta_clause['alias'] ), esc_sql( $meta_clause['cast'] ) );
1249              } else {
1250                  $parsed = "$wpdb->comments.$orderby";
1251              }
1252          }
1253  
1254          return $parsed;
1255      }
1256  
1257      /**
1258       * Parse an 'order' query variable and cast it to ASC or DESC as necessary.
1259       *
1260       * @since 4.2.0
1261       *
1262       * @param string $order The 'order' query variable.
1263       * @return string The sanitized 'order' query variable.
1264       */
1265  	protected function parse_order( $order ) {
1266          if ( ! is_string( $order ) || empty( $order ) ) {
1267              return 'DESC';
1268          }
1269  
1270          if ( 'ASC' === strtoupper( $order ) ) {
1271              return 'ASC';
1272          } else {
1273              return 'DESC';
1274          }
1275      }
1276  }


Generated : Sun Oct 25 08:20:35 2026 Cross-referenced by PHPXref