[ 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       *
 553       * @global wpdb $wpdb WordPress database abstraction object.
 554       *
 555       * @return int|array A single count of comment IDs if a count query. An array of comment IDs if a full query.
 556       * @phpstan-return non-negative-int|list<non-negative-int>
 557       */
 558  	protected function get_comment_ids() {
 559          global $wpdb;
 560  
 561          // Assemble clauses related to 'comment_approved'.
 562          $approved_clauses = array();
 563  
 564          // 'status' accepts an array or a comma-separated string.
 565          $status_clauses = array();
 566          $statuses       = wp_parse_list( $this->query_vars['status'] );
 567  
 568          // Empty 'status' should be interpreted as 'all'.
 569          if ( empty( $statuses ) ) {
 570              $statuses = array( 'all' );
 571          }
 572  
 573          // 'any' overrides other statuses.
 574          if ( ! in_array( 'any', $statuses, true ) ) {
 575              foreach ( $statuses as $status ) {
 576                  switch ( $status ) {
 577                      case 'hold':
 578                          $status_clauses[] = "comment_approved = '0'";
 579                          break;
 580  
 581                      case 'approve':
 582                          $status_clauses[] = "comment_approved = '1'";
 583                          break;
 584  
 585                      case 'all':
 586                      case '':
 587                          $status_clauses[] = "( comment_approved = '0' OR comment_approved = '1' )";
 588                          break;
 589  
 590                      default:
 591                          $status_clauses[] = $wpdb->prepare( 'comment_approved = %s', $status );
 592                          break;
 593                  }
 594              }
 595  
 596              $approved_clauses[] = '( ' . implode( ' OR ', $status_clauses ) . ' )';
 597          }
 598  
 599          // User IDs or emails whose unapproved comments are included, regardless of $status.
 600          if ( ! empty( $this->query_vars['include_unapproved'] ) ) {
 601              $include_unapproved = wp_parse_list( $this->query_vars['include_unapproved'] );
 602  
 603              foreach ( $include_unapproved as $unapproved_identifier ) {
 604                  // Numeric values are assumed to be user IDs.
 605                  if ( is_numeric( $unapproved_identifier ) ) {
 606                      $approved_clauses[] = $wpdb->prepare( "( user_id = %d AND comment_approved = '0' )", $unapproved_identifier );
 607                  } else {
 608                      // Otherwise we match against email addresses.
 609                      if ( ! empty( $_GET['unapproved'] ) && ! empty( $_GET['moderation-hash'] ) ) {
 610                          // Only include requested comment.
 611                          $approved_clauses[] = $wpdb->prepare( "( comment_author_email = %s AND comment_approved = '0' AND {$wpdb->comments}.comment_ID = %d )", $unapproved_identifier, (int) $_GET['unapproved'] );
 612                      } else {
 613                          // Include all of the author's unapproved comments.
 614                          $approved_clauses[] = $wpdb->prepare( "( comment_author_email = %s AND comment_approved = '0' )", $unapproved_identifier );
 615                      }
 616                  }
 617              }
 618          }
 619  
 620          // Collapse comment_approved clauses into a single OR-separated clause.
 621          if ( ! empty( $approved_clauses ) ) {
 622              if ( 1 === count( $approved_clauses ) ) {
 623                  $this->sql_clauses['where']['approved'] = $approved_clauses[0];
 624              } else {
 625                  $this->sql_clauses['where']['approved'] = '( ' . implode( ' OR ', $approved_clauses ) . ' )';
 626              }
 627          }
 628  
 629          $order = ( 'ASC' === strtoupper( $this->query_vars['order'] ) ) ? 'ASC' : 'DESC';
 630  
 631          // Disable ORDER BY with 'none', an empty array, or boolean false.
 632          if ( in_array( $this->query_vars['orderby'], array( 'none', array(), false ), true ) ) {
 633              $orderby = '';
 634          } elseif ( ! empty( $this->query_vars['orderby'] ) ) {
 635              $ordersby = is_array( $this->query_vars['orderby'] ) ?
 636                  $this->query_vars['orderby'] :
 637                  preg_split( '/[,\s]/', $this->query_vars['orderby'] );
 638  
 639              $orderby_array            = array();
 640              $found_orderby_comment_id = false;
 641              foreach ( $ordersby as $_key => $_value ) {
 642                  if ( ! $_value ) {
 643                      continue;
 644                  }
 645  
 646                  if ( is_int( $_key ) ) {
 647                      $_orderby = $_value;
 648                      $_order   = $order;
 649                  } else {
 650                      $_orderby = $_key;
 651                      $_order   = $_value;
 652                  }
 653  
 654                  if ( ! $found_orderby_comment_id && in_array( $_orderby, array( 'comment_ID', 'comment__in' ), true ) ) {
 655                      $found_orderby_comment_id = true;
 656                  }
 657  
 658                  $parsed = $this->parse_orderby( $_orderby );
 659  
 660                  if ( ! $parsed ) {
 661                      continue;
 662                  }
 663  
 664                  if ( 'comment__in' === $_orderby ) {
 665                      $orderby_array[] = $parsed;
 666                      continue;
 667                  }
 668  
 669                  $orderby_array[] = $parsed . ' ' . $this->parse_order( $_order );
 670              }
 671  
 672              // If no valid clauses were found, order by comment_date_gmt.
 673              if ( empty( $orderby_array ) ) {
 674                  $orderby_array[] = "$wpdb->comments.comment_date_gmt $order";
 675              }
 676  
 677              // To ensure determinate sorting, always include a comment_ID clause.
 678              if ( ! $found_orderby_comment_id ) {
 679                  $comment_id_order = '';
 680  
 681                  // Inherit order from comment_date or comment_date_gmt, if available.
 682                  foreach ( $orderby_array as $orderby_clause ) {
 683                      if ( preg_match( '/comment_date(?:_gmt)*\ (ASC|DESC)/', $orderby_clause, $match ) ) {
 684                          $comment_id_order = $match[1];
 685                          break;
 686                      }
 687                  }
 688  
 689                  // If no date-related order is available, use the date from the first available clause.
 690                  if ( ! $comment_id_order ) {
 691                      foreach ( $orderby_array as $orderby_clause ) {
 692                          if ( str_contains( 'ASC', $orderby_clause ) ) {
 693                              $comment_id_order = 'ASC';
 694                          } else {
 695                              $comment_id_order = 'DESC';
 696                          }
 697  
 698                          break;
 699                      }
 700                  }
 701  
 702                  // Default to DESC.
 703                  if ( ! $comment_id_order ) {
 704                      $comment_id_order = 'DESC';
 705                  }
 706  
 707                  $orderby_array[] = "$wpdb->comments.comment_ID $comment_id_order";
 708              }
 709  
 710              $orderby = implode( ', ', $orderby_array );
 711          } else {
 712              $orderby = "$wpdb->comments.comment_date_gmt $order";
 713          }
 714  
 715          $number = absint( $this->query_vars['number'] );
 716          $offset = absint( $this->query_vars['offset'] );
 717          $paged  = absint( $this->query_vars['paged'] );
 718          $limits = '';
 719  
 720          if ( ! empty( $number ) ) {
 721              if ( $offset ) {
 722                  $limits = 'LIMIT ' . $offset . ',' . $number;
 723              } else {
 724                  $limits = 'LIMIT ' . ( $number * ( $paged - 1 ) ) . ',' . $number;
 725              }
 726          }
 727  
 728          if ( $this->query_vars['count'] ) {
 729              $fields = 'COUNT(*)';
 730          } else {
 731              $fields = "$wpdb->comments.comment_ID";
 732          }
 733  
 734          $post_id = absint( $this->query_vars['post_id'] );
 735          if ( ! empty( $post_id ) ) {
 736              $this->sql_clauses['where']['post_id'] = $wpdb->prepare( 'comment_post_ID = %d', $post_id );
 737          }
 738  
 739          // Parse comment IDs for an IN clause.
 740          if ( ! empty( $this->query_vars['comment__in'] ) ) {
 741              $this->sql_clauses['where']['comment__in'] = "$wpdb->comments.comment_ID IN ( " . implode( ',', wp_parse_id_list( $this->query_vars['comment__in'] ) ) . ' )';
 742          }
 743  
 744          // Parse comment IDs for a NOT IN clause.
 745          if ( ! empty( $this->query_vars['comment__not_in'] ) ) {
 746              $this->sql_clauses['where']['comment__not_in'] = "$wpdb->comments.comment_ID NOT IN ( " . implode( ',', wp_parse_id_list( $this->query_vars['comment__not_in'] ) ) . ' )';
 747          }
 748  
 749          // Parse comment parent IDs for an IN clause.
 750          if ( ! empty( $this->query_vars['parent__in'] ) ) {
 751              $this->sql_clauses['where']['parent__in'] = 'comment_parent IN ( ' . implode( ',', wp_parse_id_list( $this->query_vars['parent__in'] ) ) . ' )';
 752          }
 753  
 754          // Parse comment parent IDs for a NOT IN clause.
 755          if ( ! empty( $this->query_vars['parent__not_in'] ) ) {
 756              $this->sql_clauses['where']['parent__not_in'] = 'comment_parent NOT IN ( ' . implode( ',', wp_parse_id_list( $this->query_vars['parent__not_in'] ) ) . ' )';
 757          }
 758  
 759          // Parse comment post IDs for an IN clause.
 760          if ( ! empty( $this->query_vars['post__in'] ) ) {
 761              $this->sql_clauses['where']['post__in'] = 'comment_post_ID IN ( ' . implode( ',', wp_parse_id_list( $this->query_vars['post__in'] ) ) . ' )';
 762          }
 763  
 764          // Parse comment post IDs for a NOT IN clause.
 765          if ( ! empty( $this->query_vars['post__not_in'] ) ) {
 766              $this->sql_clauses['where']['post__not_in'] = 'comment_post_ID NOT IN ( ' . implode( ',', wp_parse_id_list( $this->query_vars['post__not_in'] ) ) . ' )';
 767          }
 768  
 769          if ( '' !== $this->query_vars['author_email'] ) {
 770              $this->sql_clauses['where']['author_email'] = $wpdb->prepare( 'comment_author_email = %s', $this->query_vars['author_email'] );
 771          }
 772  
 773          if ( '' !== $this->query_vars['author_url'] ) {
 774              $this->sql_clauses['where']['author_url'] = $wpdb->prepare( 'comment_author_url = %s', $this->query_vars['author_url'] );
 775          }
 776  
 777          if ( '' !== $this->query_vars['karma'] ) {
 778              $this->sql_clauses['where']['karma'] = $wpdb->prepare( 'comment_karma = %d', $this->query_vars['karma'] );
 779          }
 780  
 781          // Filtering by comment_type: 'type', 'type__in', 'type__not_in'.
 782          $raw_types = array(
 783              'IN'     => array_merge( (array) $this->query_vars['type'], (array) $this->query_vars['type__in'] ),
 784              'NOT IN' => (array) $this->query_vars['type__not_in'],
 785          );
 786  
 787          // Exclude the 'note' comment type, unless 'all' types or the 'note' type explicitly are requested.
 788          if (
 789              ! in_array( 'all', $raw_types['IN'], true ) &&
 790              ! in_array( 'note', $raw_types['IN'], true ) &&
 791              ! in_array( 'note', $raw_types['NOT IN'], true )
 792          ) {
 793              $raw_types['NOT IN'][] = 'note';
 794          }
 795  
 796          $comment_types = array();
 797          foreach ( $raw_types as $operator => $_raw_types ) {
 798              $_raw_types = array_unique( $_raw_types );
 799  
 800              foreach ( $_raw_types as $type ) {
 801                  switch ( $type ) {
 802                      // An empty translates to 'all', for backward compatibility.
 803                      case '':
 804                      case 'all':
 805                          break;
 806  
 807                      case 'comment':
 808                      case 'comments':
 809                          $comment_types[ $operator ][] = "''";
 810                          $comment_types[ $operator ][] = "'comment'";
 811                          break;
 812  
 813                      case 'pings':
 814                          $comment_types[ $operator ][] = "'pingback'";
 815                          $comment_types[ $operator ][] = "'trackback'";
 816                          break;
 817  
 818                      default:
 819                          $comment_types[ $operator ][] = $wpdb->prepare( '%s', $type );
 820                          break;
 821                  }
 822              }
 823  
 824              if ( ! empty( $comment_types[ $operator ] ) ) {
 825                  $types_sql = implode( ', ', $comment_types[ $operator ] );
 826                  $this->sql_clauses['where'][ 'comment_type__' . strtolower( str_replace( ' ', '_', $operator ) ) ] = "comment_type $operator ($types_sql)";
 827              }
 828          }
 829  
 830          $parent = $this->query_vars['parent'];
 831          if ( $this->query_vars['hierarchical'] && ! $parent ) {
 832              $parent = 0;
 833          }
 834  
 835          if ( '' !== $parent ) {
 836              $this->sql_clauses['where']['parent'] = $wpdb->prepare( 'comment_parent = %d', $parent );
 837          }
 838  
 839          if ( is_array( $this->query_vars['user_id'] ) ) {
 840              $this->sql_clauses['where']['user_id'] = 'user_id IN (' . implode( ',', array_map( 'absint', $this->query_vars['user_id'] ) ) . ')';
 841          } elseif ( '' !== $this->query_vars['user_id'] ) {
 842              $this->sql_clauses['where']['user_id'] = $wpdb->prepare( 'user_id = %d', $this->query_vars['user_id'] );
 843          }
 844  
 845          // Falsey search strings are ignored.
 846          if ( isset( $this->query_vars['search'] ) && strlen( $this->query_vars['search'] ) ) {
 847              $search_sql = $this->get_search_sql(
 848                  $this->query_vars['search'],
 849                  array( 'comment_author', 'comment_author_email', 'comment_author_url', 'comment_author_IP', 'comment_content' )
 850              );
 851  
 852              // Strip leading 'AND'.
 853              $this->sql_clauses['where']['search'] = preg_replace( '/^\s*AND\s*/', '', $search_sql );
 854          }
 855  
 856          // If any post-related query vars are passed, join the posts table.
 857          $join_posts_table = false;
 858          $plucked          = wp_array_slice_assoc( $this->query_vars, array( 'post_author', 'post_name', 'post_parent' ) );
 859          $post_fields      = array_filter( $plucked );
 860  
 861          if ( ! empty( $post_fields ) ) {
 862              $join_posts_table = true;
 863              foreach ( $post_fields as $field_name => $field_value ) {
 864                  // $field_value may be an array.
 865                  $esses = array_fill( 0, count( (array) $field_value ), '%s' );
 866  
 867                  // phpcs:ignore WordPress.DB.PreparedSQLPlaceholders.UnfinishedPrepare
 868                  $this->sql_clauses['where'][ $field_name ] = $wpdb->prepare( " {$wpdb->posts}.{$field_name} IN (" . implode( ',', $esses ) . ')', $field_value );
 869              }
 870          }
 871  
 872          // 'post_status' and 'post_type' are handled separately, due to the specialized behavior of 'any'.
 873          foreach ( array( 'post_status', 'post_type' ) as $field_name ) {
 874              $q_values = array();
 875              if ( ! empty( $this->query_vars[ $field_name ] ) ) {
 876                  $q_values = $this->query_vars[ $field_name ];
 877                  if ( ! is_array( $q_values ) ) {
 878                      $q_values = explode( ',', $q_values );
 879                  }
 880  
 881                  // 'any' will cause the query var to be ignored.
 882                  if ( in_array( 'any', $q_values, true ) || empty( $q_values ) ) {
 883                      continue;
 884                  }
 885  
 886                  $join_posts_table = true;
 887  
 888                  $esses = array_fill( 0, count( $q_values ), '%s' );
 889  
 890                  // phpcs:ignore WordPress.DB.PreparedSQLPlaceholders.UnfinishedPrepare
 891                  $this->sql_clauses['where'][ $field_name ] = $wpdb->prepare( " {$wpdb->posts}.{$field_name} IN (" . implode( ',', $esses ) . ')', $q_values );
 892              }
 893          }
 894  
 895          // Comment author IDs for an IN clause.
 896          if ( ! empty( $this->query_vars['author__in'] ) ) {
 897              $this->sql_clauses['where']['author__in'] = 'user_id IN ( ' . implode( ',', wp_parse_id_list( $this->query_vars['author__in'] ) ) . ' )';
 898          }
 899  
 900          // Comment author IDs for a NOT IN clause.
 901          if ( ! empty( $this->query_vars['author__not_in'] ) ) {
 902              $this->sql_clauses['where']['author__not_in'] = 'user_id NOT IN ( ' . implode( ',', wp_parse_id_list( $this->query_vars['author__not_in'] ) ) . ' )';
 903          }
 904  
 905          // Post author IDs for an IN clause.
 906          if ( ! empty( $this->query_vars['post_author__in'] ) ) {
 907              $join_posts_table                              = true;
 908              $this->sql_clauses['where']['post_author__in'] = 'post_author IN ( ' . implode( ',', wp_parse_id_list( $this->query_vars['post_author__in'] ) ) . ' )';
 909          }
 910  
 911          // Post author IDs for a NOT IN clause.
 912          if ( ! empty( $this->query_vars['post_author__not_in'] ) ) {
 913              $join_posts_table                                  = true;
 914              $this->sql_clauses['where']['post_author__not_in'] = 'post_author NOT IN ( ' . implode( ',', wp_parse_id_list( $this->query_vars['post_author__not_in'] ) ) . ' )';
 915          }
 916  
 917          $join    = '';
 918          $groupby = '';
 919  
 920          if ( $join_posts_table ) {
 921              $join .= "JOIN $wpdb->posts ON $wpdb->posts.ID = $wpdb->comments.comment_post_ID";
 922          }
 923  
 924          if ( ! empty( $this->meta_query_clauses ) ) {
 925              $join .= $this->meta_query_clauses['join'];
 926  
 927              // Strip leading 'AND'.
 928              $this->sql_clauses['where']['meta_query'] = preg_replace( '/^\s*AND\s*/', '', $this->meta_query_clauses['where'] );
 929  
 930              if ( ! $this->query_vars['count'] ) {
 931                  $groupby = "{$wpdb->comments}.comment_ID";
 932              }
 933          }
 934  
 935          if ( ! empty( $this->query_vars['date_query'] ) && is_array( $this->query_vars['date_query'] ) ) {
 936              $this->date_query = new WP_Date_Query( $this->query_vars['date_query'], 'comment_date' );
 937  
 938              // Strip leading 'AND'.
 939              $this->sql_clauses['where']['date_query'] = preg_replace( '/^\s*AND\s*/', '', $this->date_query->get_sql() );
 940          }
 941  
 942          $where = implode( ' AND ', $this->sql_clauses['where'] );
 943  
 944          $pieces = array( 'fields', 'join', 'where', 'orderby', 'limits', 'groupby' );
 945  
 946          /**
 947           * Filters the comment query clauses.
 948           *
 949           * @since 3.1.0
 950           *
 951           * @param string[]         $clauses {
 952           *     Associative array of the clauses for the query.
 953           *
 954           *     @type string $fields   The SELECT clause of the query.
 955           *     @type string $join     The JOIN clause of the query.
 956           *     @type string $where    The WHERE clause of the query.
 957           *     @type string $orderby  The ORDER BY clause of the query.
 958           *     @type string $limits   The LIMIT clause of the query.
 959           *     @type string $groupby  The GROUP BY clause of the query.
 960           * }
 961           * @param WP_Comment_Query $query   Current instance of WP_Comment_Query (passed by reference).
 962           */
 963          $clauses = apply_filters_ref_array( 'comments_clauses', array( compact( $pieces ), &$this ) );
 964  
 965          $fields  = $clauses['fields'] ?? '';
 966          $join    = $clauses['join'] ?? '';
 967          $where   = $clauses['where'] ?? '';
 968          $orderby = $clauses['orderby'] ?? '';
 969          $limits  = $clauses['limits'] ?? '';
 970          $groupby = $clauses['groupby'] ?? '';
 971  
 972          $this->filtered_where_clause = $where;
 973  
 974          if ( $where ) {
 975              $where = 'WHERE ' . $where;
 976          }
 977  
 978          if ( $groupby ) {
 979              $groupby = 'GROUP BY ' . $groupby;
 980          }
 981  
 982          if ( $orderby ) {
 983              $orderby = "ORDER BY $orderby";
 984          }
 985  
 986          $found_rows = '';
 987          if ( ! $this->query_vars['no_found_rows'] ) {
 988              $found_rows = 'SQL_CALC_FOUND_ROWS';
 989          }
 990  
 991          $this->sql_clauses['select']  = "SELECT $found_rows $fields";
 992          $this->sql_clauses['from']    = "FROM $wpdb->comments $join";
 993          $this->sql_clauses['groupby'] = $groupby;
 994          $this->sql_clauses['orderby'] = $orderby;
 995          $this->sql_clauses['limits']  = $limits;
 996  
 997          // Beginning of the string is on a new line to prevent leading whitespace. See https://core.trac.wordpress.org/ticket/56841.
 998          $this->request =
 999              "{$this->sql_clauses['select']}
1000               {$this->sql_clauses['from']}
1001               {$where}
1002               {$this->sql_clauses['groupby']}
1003               {$this->sql_clauses['orderby']}
1004               {$this->sql_clauses['limits']}";
1005  
1006          if ( $this->query_vars['count'] ) {
1007              return (int) $wpdb->get_var( $this->request );
1008          } else {
1009              $comment_ids = $wpdb->get_col( $this->request );
1010              return array_map( 'intval', $comment_ids );
1011          }
1012      }
1013  
1014      /**
1015       * Populates found_comments and max_num_pages properties for the current
1016       * query if the limit clause was used.
1017       *
1018       * @since 4.6.0
1019       *
1020       * @global wpdb $wpdb WordPress database abstraction object.
1021       */
1022  	private function set_found_comments() {
1023          global $wpdb;
1024  
1025          if ( $this->query_vars['number'] && ! $this->query_vars['no_found_rows'] ) {
1026              /**
1027               * Filters the query used to retrieve found comment count.
1028               *
1029               * @since 4.4.0
1030               *
1031               * @param string           $found_comments_query SQL query. Default 'SELECT FOUND_ROWS()'.
1032               * @param WP_Comment_Query $comment_query        The `WP_Comment_Query` instance.
1033               */
1034              $found_comments_query = apply_filters( 'found_comments_query', 'SELECT FOUND_ROWS()', $this );
1035  
1036              $this->found_comments = (int) $wpdb->get_var( $found_comments_query );
1037          }
1038      }
1039  
1040      /**
1041       * Fetch descendants for located comments.
1042       *
1043       * Instead of calling `get_children()` separately on each child comment, we do a single set of queries to fetch
1044       * the descendant trees for all matched top-level comments.
1045       *
1046       * @since 4.4.0
1047       *
1048       * @param WP_Comment[] $comments Array of top-level comments whose descendants should be filled in.
1049       * @return array
1050       */
1051  	protected function fill_descendants( $comments ) {
1052          $levels = array(
1053              0 => wp_list_pluck( $comments, 'comment_ID' ),
1054          );
1055  
1056          $key          = md5( serialize( wp_array_slice_assoc( $this->query_vars, array_keys( $this->query_var_defaults ) ) ) );
1057          $last_changed = wp_cache_get_last_changed( 'comment' );
1058  
1059          // Fetch an entire level of the descendant tree at a time.
1060          $level        = 0;
1061          $exclude_keys = array( 'parent', 'parent__in', 'parent__not_in' );
1062          do {
1063              // Parent-child relationships may be cached. Only query for those that are not.
1064              $child_ids           = array();
1065              $uncached_parent_ids = array();
1066              $_parent_ids         = $levels[ $level ];
1067              if ( $_parent_ids ) {
1068                  $cache_keys = array();
1069                  foreach ( $_parent_ids as $parent_id ) {
1070                      $cache_keys[ $parent_id ] = "get_comment_child_ids:$parent_id:$key";
1071                  }
1072                  $cache_data = wp_cache_get_multiple_salted( array_values( $cache_keys ), 'comment-queries', $last_changed );
1073                  foreach ( $_parent_ids as $parent_id ) {
1074                      $parent_child_ids = $cache_data[ $cache_keys[ $parent_id ] ];
1075                      if ( false !== $parent_child_ids ) {
1076                          $child_ids = array_merge( $child_ids, $parent_child_ids );
1077                      } else {
1078                          $uncached_parent_ids[] = $parent_id;
1079                      }
1080                  }
1081              }
1082  
1083              if ( $uncached_parent_ids ) {
1084                  // Fetch this level of comments.
1085                  $parent_query_args = $this->query_vars;
1086                  foreach ( $exclude_keys as $exclude_key ) {
1087                      $parent_query_args[ $exclude_key ] = '';
1088                  }
1089                  $parent_query_args['parent__in']    = $uncached_parent_ids;
1090                  $parent_query_args['no_found_rows'] = true;
1091                  $parent_query_args['hierarchical']  = false;
1092                  $parent_query_args['offset']        = 0;
1093                  $parent_query_args['number']        = 0;
1094  
1095                  $level_comments = get_comments( $parent_query_args );
1096  
1097                  // Cache parent-child relationships.
1098                  $parent_map = array_fill_keys( $uncached_parent_ids, array() );
1099                  foreach ( $level_comments as $level_comment ) {
1100                      $parent_map[ $level_comment->comment_parent ][] = $level_comment->comment_ID;
1101                      $child_ids[]                                    = $level_comment->comment_ID;
1102                  }
1103  
1104                  $data = array();
1105                  foreach ( $parent_map as $parent_id => $children ) {
1106                      $cache_key          = "get_comment_child_ids:$parent_id:$key";
1107                      $data[ $cache_key ] = $children;
1108                  }
1109                  wp_cache_set_multiple_salted( $data, 'comment-queries', $last_changed );
1110              }
1111  
1112              ++$level;
1113              $levels[ $level ] = $child_ids;
1114          } while ( $child_ids );
1115  
1116          // Prime comment caches for non-top-level comments.
1117          $descendant_ids = array();
1118          for ( $i = 1, $c = count( $levels ); $i < $c; $i++ ) {
1119              $descendant_ids = array_merge( $descendant_ids, $levels[ $i ] );
1120          }
1121  
1122          _prime_comment_caches( $descendant_ids, $this->query_vars['update_comment_meta_cache'] );
1123  
1124          // Assemble a flat array of all comments + descendants.
1125          $all_comments = $comments;
1126          foreach ( $descendant_ids as $descendant_id ) {
1127              $descendant = get_comment( $descendant_id );
1128              if ( $descendant instanceof WP_Comment ) {
1129                  $all_comments[] = $descendant;
1130              }
1131          }
1132  
1133          // If a threaded representation was requested, build the tree.
1134          if ( 'threaded' === $this->query_vars['hierarchical'] ) {
1135              $threaded_comments = array();
1136              $ref               = array();
1137              foreach ( $all_comments as $k => $c ) {
1138                  $_c = get_comment( $c->comment_ID );
1139  
1140                  // If the comment isn't in the reference array, it goes in the top level of the thread.
1141                  if ( ! isset( $ref[ $c->comment_parent ] ) ) {
1142                      $threaded_comments[ $_c->comment_ID ] = $_c;
1143                      $ref[ $_c->comment_ID ]               = $threaded_comments[ $_c->comment_ID ];
1144  
1145                      // Otherwise, set it as a child of its parent.
1146                  } else {
1147  
1148                      $ref[ $_c->comment_parent ]->add_child( $_c );
1149                      $ref[ $_c->comment_ID ] = $ref[ $_c->comment_parent ]->get_child( $_c->comment_ID );
1150                  }
1151              }
1152  
1153              // Set the 'populated_children' flag, to ensure additional database queries aren't run.
1154              foreach ( $ref as $_ref ) {
1155                  $_ref->populated_children( true );
1156              }
1157  
1158              $comments = $threaded_comments;
1159          } else {
1160              $comments = $all_comments;
1161          }
1162  
1163          return $comments;
1164      }
1165  
1166      /**
1167       * Used internally to generate an SQL string for searching across multiple columns.
1168       *
1169       * @since 3.1.0
1170       *
1171       * @global wpdb $wpdb WordPress database abstraction object.
1172       *
1173       * @param string   $search  Search string.
1174       * @param string[] $columns Array of columns to search.
1175       * @return string Search SQL.
1176       */
1177  	protected function get_search_sql( $search, $columns ) {
1178          global $wpdb;
1179  
1180          $like = '%' . $wpdb->esc_like( $search ) . '%';
1181  
1182          $searches = array();
1183          foreach ( $columns as $column ) {
1184              $searches[] = $wpdb->prepare( "$column LIKE %s", $like );
1185          }
1186  
1187          return ' AND (' . implode( ' OR ', $searches ) . ')';
1188      }
1189  
1190      /**
1191       * Parse and sanitize 'orderby' keys passed to the comment query.
1192       *
1193       * @since 4.2.0
1194       *
1195       * @global wpdb $wpdb WordPress database abstraction object.
1196       *
1197       * @param string $orderby Alias for the field to order by.
1198       * @return string|false Value to used in the ORDER clause. False otherwise.
1199       */
1200  	protected function parse_orderby( $orderby ) {
1201          global $wpdb;
1202  
1203          $allowed_keys = array(
1204              'comment_agent',
1205              'comment_approved',
1206              'comment_author',
1207              'comment_author_email',
1208              'comment_author_IP',
1209              'comment_author_url',
1210              'comment_content',
1211              'comment_date',
1212              'comment_date_gmt',
1213              'comment_ID',
1214              'comment_karma',
1215              'comment_parent',
1216              'comment_post_ID',
1217              'comment_type',
1218              'user_id',
1219          );
1220  
1221          if ( ! empty( $this->query_vars['meta_key'] ) ) {
1222              $allowed_keys[] = $this->query_vars['meta_key'];
1223              $allowed_keys[] = 'meta_value';
1224              $allowed_keys[] = 'meta_value_num';
1225          }
1226  
1227          $meta_query_clauses = $this->meta_query->get_clauses();
1228          if ( $meta_query_clauses ) {
1229              $allowed_keys = array_merge( $allowed_keys, array_keys( $meta_query_clauses ) );
1230          }
1231  
1232          $parsed = false;
1233          if ( $this->query_vars['meta_key'] === $orderby || 'meta_value' === $orderby ) {
1234              $parsed = "$wpdb->commentmeta.meta_value";
1235          } elseif ( 'meta_value_num' === $orderby ) {
1236              $parsed = "$wpdb->commentmeta.meta_value+0";
1237          } elseif ( 'comment__in' === $orderby ) {
1238              $comment__in = implode( ',', array_map( 'absint', $this->query_vars['comment__in'] ) );
1239              $parsed      = "FIELD( {$wpdb->comments}.comment_ID, $comment__in )";
1240          } elseif ( in_array( $orderby, $allowed_keys, true ) ) {
1241  
1242              if ( isset( $meta_query_clauses[ $orderby ] ) ) {
1243                  $meta_clause = $meta_query_clauses[ $orderby ];
1244                  $parsed      = sprintf( 'CAST(%s.meta_value AS %s)', esc_sql( $meta_clause['alias'] ), esc_sql( $meta_clause['cast'] ) );
1245              } else {
1246                  $parsed = "$wpdb->comments.$orderby";
1247              }
1248          }
1249  
1250          return $parsed;
1251      }
1252  
1253      /**
1254       * Parse an 'order' query variable and cast it to ASC or DESC as necessary.
1255       *
1256       * @since 4.2.0
1257       *
1258       * @param string $order The 'order' query variable.
1259       * @return string The sanitized 'order' query variable.
1260       */
1261  	protected function parse_order( $order ) {
1262          if ( ! is_string( $order ) || empty( $order ) ) {
1263              return 'DESC';
1264          }
1265  
1266          if ( 'ASC' === strtoupper( $order ) ) {
1267              return 'ASC';
1268          } else {
1269              return 'DESC';
1270          }
1271      }
1272  }


Generated : Mon Oct 5 08:20:36 2026 Cross-referenced by PHPXref