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


Generated : Mon Jul 27 08:20:18 2026 Cross-referenced by PHPXref