[ Index ]

PHP Cross Reference of WordPress Trunk (Updated Daily)

Search

title

Body

[close]

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

   1  <?php
   2  /**
   3   * Comment API: WP_Comment class
   4   *
   5   * @package WordPress
   6   * @subpackage Comments
   7   * @since 4.4.0
   8   */
   9  
  10  /**
  11   * Core class used to organize comments as instantiated objects with defined members.
  12   *
  13   * The `@property-read` fields below are not stored on the comment. They are proxied to the
  14   * comment's post by {@see WP_Comment::__get()}, and are null when the comment is not attached
  15   * to a post or when that post no longer exists.
  16   *
  17   * @since 4.4.0
  18   *
  19   * @property-read numeric-string|''|null $post_author
  20   * @property-read string|null            $post_date
  21   * @property-read string|null            $post_date_gmt
  22   * @property-read string|null            $post_content
  23   * @property-read string|null            $post_title
  24   * @property-read string|null            $post_excerpt
  25   * @property-read non-empty-string|null  $post_status
  26   * @property-read non-empty-string|null  $comment_status
  27   * @property-read non-empty-string|null  $ping_status
  28   * @property-read string|null            $post_name
  29   * @property-read string|null            $to_ping
  30   * @property-read string|null            $pinged
  31   * @property-read string|null            $post_modified
  32   * @property-read string|null            $post_modified_gmt
  33   * @property-read string|null            $post_content_filtered
  34   * @property-read non-negative-int|null  $post_parent
  35   * @property-read string|null            $guid
  36   * @property-read int|null               $menu_order
  37   * @property-read non-empty-string|null  $post_type
  38   * @property-read string|null            $post_mime_type
  39   * @property-read numeric-string|null    $comment_count
  40   *
  41   * @phpstan-type Data_Array array{
  42   *     comment_ID: numeric-string,
  43   *     comment_post_ID: numeric-string,
  44   *     comment_author: string,
  45   *     comment_author_email: string,
  46   *     comment_author_url: string,
  47   *     comment_author_IP: string,
  48   *     comment_date: non-empty-string,
  49   *     comment_date_gmt: non-empty-string,
  50   *     comment_content: string,
  51   *     comment_karma: numeric-string,
  52   *     comment_approved: non-empty-string,
  53   *     comment_agent: string,
  54   *     comment_type: string,
  55   *     comment_parent: numeric-string,
  56   *     user_id: numeric-string,
  57   *     ...
  58   * }
  59   */
  60  #[AllowDynamicProperties]
  61  final class WP_Comment {
  62  
  63      /**
  64       * Comment ID.
  65       *
  66       * A numeric string, for compatibility reasons.
  67       *
  68       * @since 4.4.0
  69       * @var string
  70       * @phpstan-var numeric-string
  71       */
  72      public $comment_ID;
  73  
  74      /**
  75       * ID of the post the comment is associated with.
  76       *
  77       * A numeric string, for compatibility reasons.
  78       *
  79       * @since 4.4.0
  80       * @var string
  81       * @phpstan-var numeric-string
  82       */
  83      public $comment_post_ID = '0';
  84  
  85      /**
  86       * Comment author name.
  87       *
  88       * @since 4.4.0
  89       * @var string
  90       */
  91      public $comment_author = '';
  92  
  93      /**
  94       * Comment author email address.
  95       *
  96       * @since 4.4.0
  97       * @var string
  98       */
  99      public $comment_author_email = '';
 100  
 101      /**
 102       * Comment author URL.
 103       *
 104       * @since 4.4.0
 105       * @var string
 106       */
 107      public $comment_author_url = '';
 108  
 109      /**
 110       * Comment author IP address (IPv4 format).
 111       *
 112       * @since 4.4.0
 113       * @var string
 114       */
 115      public $comment_author_IP = '';
 116  
 117      /**
 118       * Comment date in YYYY-MM-DD HH:MM:SS format.
 119       *
 120       * @since 4.4.0
 121       * @var string
 122       * @phpstan-var non-empty-string
 123       */
 124      public $comment_date = '0000-00-00 00:00:00';
 125  
 126      /**
 127       * Comment GMT date in YYYY-MM-DD HH::MM:SS format.
 128       *
 129       * @since 4.4.0
 130       * @var string
 131       * @phpstan-var non-empty-string
 132       */
 133      public $comment_date_gmt = '0000-00-00 00:00:00';
 134  
 135      /**
 136       * Comment content.
 137       *
 138       * @since 4.4.0
 139       * @var string
 140       */
 141      public $comment_content;
 142  
 143      /**
 144       * Comment karma count.
 145       *
 146       * A numeric string, for compatibility reasons.
 147       *
 148       * @since 4.4.0
 149       * @var string
 150       * @phpstan-var numeric-string
 151       */
 152      public $comment_karma = '0';
 153  
 154      /**
 155       * Comment approval status.
 156       *
 157       * The values used in core are '0' (unapproved), '1' (approved), 'spam', 'trash',
 158       * and 'post-trashed' (set for every comment on a post that is moved to the trash).
 159       *
 160       * @since 4.4.0
 161       * @var string
 162       * @phpstan-var non-empty-string
 163       */
 164      public $comment_approved = '1';
 165  
 166      /**
 167       * Comment author HTTP user agent.
 168       *
 169       * @since 4.4.0
 170       * @var string
 171       */
 172      public $comment_agent = '';
 173  
 174      /**
 175       * Comment type.
 176       *
 177       * The values used in core are 'comment', 'pingback', 'trackback', and 'note'. Custom
 178       * comment types are possible.
 179       *
 180       * Comments created before 5.5.0 may store an empty string rather than 'comment', so this
 181       * cannot be relied upon to be non-empty. {@see get_comment_type()} normalizes that case
 182       * when reading.
 183       *
 184       * @since 4.4.0
 185       * @since 5.5.0 Default value changed to `comment`.
 186       * @var string
 187       */
 188      public $comment_type = 'comment';
 189  
 190      /**
 191       * Parent comment ID.
 192       *
 193       * A numeric string, for compatibility reasons.
 194       *
 195       * @since 4.4.0
 196       * @var string
 197       * @phpstan-var numeric-string
 198       */
 199      public $comment_parent = '0';
 200  
 201      /**
 202       * Comment author ID.
 203       *
 204       * A numeric string, for compatibility reasons.
 205       *
 206       * @since 4.4.0
 207       * @var string
 208       * @phpstan-var numeric-string
 209       */
 210      public $user_id = '0';
 211  
 212      /**
 213       * Comment children.
 214       *
 215       * Mapping of comment ID to WP_Comment object, as populated by the default
 216       * `hierarchical => 'threaded'` argument of get_children(). Note that if a
 217       * caller passes a `hierarchical` value of 'flat' or `false` to
 218       * get_children(), a sequentially-keyed array of WP_Comment objects (also
 219       * including all descendants, in the 'flat' case) is stored here instead.
 220       *
 221       * Null until populated by {@see WP_Comment::get_children()}.
 222       *
 223       * @since 4.4.0
 224       * @var array<int, WP_Comment>|null
 225       */
 226      protected $children;
 227  
 228      /**
 229       * Whether children have been populated for this comment object.
 230       *
 231       * @since 4.4.0
 232       * @var bool
 233       */
 234      protected $populated_children = false;
 235  
 236      /**
 237       * Post fields.
 238       *
 239       * @since 4.4.0
 240       * @var string[]
 241       * @phpstan-var list<non-empty-string>
 242       */
 243      protected $post_fields = array( 'post_author', 'post_date', 'post_date_gmt', 'post_content', 'post_title', 'post_excerpt', 'post_status', 'comment_status', 'ping_status', 'post_name', 'to_ping', 'pinged', 'post_modified', 'post_modified_gmt', 'post_content_filtered', 'post_parent', 'guid', 'menu_order', 'post_type', 'post_mime_type', 'comment_count' );
 244  
 245      /**
 246       * Retrieves a WP_Comment instance.
 247       *
 248       * @since 4.4.0
 249       *
 250       * @global wpdb $wpdb WordPress database abstraction object.
 251       *
 252       * @param int $id Comment ID.
 253       * @phpstan-param int|numeric-string $id
 254       * @return WP_Comment|false Comment object, otherwise false.
 255       */
 256  	public static function get_instance( $id ) {
 257          global $wpdb;
 258  
 259          $comment_id = (int) $id;
 260          if ( ! $comment_id ) {
 261              return false;
 262          }
 263  
 264          $_comment = wp_cache_get( $comment_id, 'comment' );
 265  
 266          if ( ! is_object( $_comment ) ) {
 267              /** @var object{ comment_ID: string, comment_post_ID: string, comment_author: string, comment_author_email: string, comment_author_url: string, comment_author_IP: string, comment_date: string, comment_date_gmt: string, comment_content: string, comment_karma: string, comment_approved: string, comment_agent: string, comment_type: string, comment_parent: string, user_id: string }|null $_comment */
 268              $_comment = $wpdb->get_row( $wpdb->prepare( "SELECT * FROM $wpdb->comments WHERE comment_ID = %d LIMIT 1", $comment_id ) );
 269  
 270              if ( ! $_comment ) {
 271                  return false;
 272              }
 273  
 274              wp_cache_add( $_comment->comment_ID, $_comment, 'comment' );
 275          }
 276  
 277          return new WP_Comment( $_comment );
 278      }
 279  
 280      /**
 281       * Constructor.
 282       *
 283       * Populates properties with object vars.
 284       *
 285       * @since 4.4.0
 286       *
 287       * @param object $comment Comment object.
 288       */
 289  	public function __construct( $comment ) {
 290          foreach ( get_object_vars( $comment ) as $key => $value ) {
 291              $this->$key = $value;
 292          }
 293      }
 294  
 295      /**
 296       * Converts object to array.
 297       *
 298       * @since 4.4.0
 299       *
 300       * @return array<string, mixed> Object as array.
 301       * @phpstan-return Data_Array
 302       */
 303  	public function to_array(): array {
 304          /** @var Data_Array $comment */
 305          $comment = get_object_vars( $this );
 306          return $comment;
 307      }
 308  
 309      /**
 310       * Gets the children of a comment.
 311       *
 312       * @since 4.4.0
 313       * @since 7.1.0 A `count` or `fields` query now returns its result directly rather than
 314       *              erroneously storing it in the comment's children cache.
 315       *
 316       * @param array $args {
 317       *     Array of arguments used to pass to {@see get_comments()} and determine format.
 318       *     Any other argument accepted by {@see WP_Comment_Query::__construct()} may also be passed, and is
 319       *     forwarded to `get_comments()`. Note that `parent` is always overridden with this comment's ID.
 320       *     A `$count` or `$fields` query returns the direct children only, and does not populate the
 321       *     comment's cached children, since that cache holds `WP_Comment` objects.
 322       *
 323       *     @type string $format        Return value format. 'tree' for a hierarchical tree, 'flat' for a flattened array.
 324       *                                 Default 'tree'.
 325       *     @type string $status        Comment status to limit results by. Accepts 'hold' (`comment_status=0`),
 326       *                                 'approve' (`comment_status=1`), 'all', or a custom comment status.
 327       *                                 Default 'all'.
 328       *     @type string $hierarchical  Whether to include comment descendants in the results.
 329       *                                 'threaded' returns a tree, with each comment's children
 330       *                                 stored in a `children` property on the `WP_Comment` object.
 331       *                                 'flat' returns a flat array of found comments plus their children.
 332       *                                 Pass `false` to leave out descendants.
 333       *                                 The parameter is ignored (forced to `false`) when `$fields` is 'ids' or 'counts'.
 334       *                                 Accepts 'threaded', 'flat', or false. Default: 'threaded'.
 335       *     @type string|array $orderby Comment status or array of statuses. To use 'meta_value'
 336       *                                 or 'meta_value_num', `$meta_key` must also be defined.
 337       *                                 To sort by a specific `$meta_query` clause, use that
 338       *                                 clause's array key. Accepts 'comment_agent',
 339       *                                 'comment_approved', 'comment_author',
 340       *                                 'comment_author_email', 'comment_author_IP',
 341       *                                 'comment_author_url', 'comment_content', 'comment_date',
 342       *                                 'comment_date_gmt', 'comment_ID', 'comment_karma',
 343       *                                 'comment_parent', 'comment_post_ID', 'comment_type',
 344       *                                 'user_id', 'comment__in', 'meta_value', 'meta_value_num',
 345       *                                 the value of $meta_key, and the array keys of
 346       *                                 `$meta_query`. Also accepts false, an empty array, or
 347       *                                 'none' to disable `ORDER BY` clause.
 348       *     @type string $fields        Which fields to return. Accepts 'ids' for comment IDs, or an
 349       *                                 empty string for full `WP_Comment` objects. Default empty.
 350       *     @type bool   $count         Whether to return a comment count rather than comments.
 351       *                                 Default false.
 352       *     @type string $type          Limit results to comments of a given type, such as 'comment',
 353       *                                 'pingback', 'trackback', or 'note'. Accepts 'all' for every
 354       *                                 type. Default empty.
 355       *     @type int    $number        Maximum number of comments to retrieve. Default empty (no limit).
 356       *     @type int    $post_id       Limit results to comments on a given post. Default 0.
 357       *     @type string $order         How to order retrieved comments. Accepts 'ASC' or 'DESC'.
 358       *                                 Default 'DESC'.
 359       * }
 360       * @return WP_Comment[]|int[]|int Array of `WP_Comment` objects, an array of comment IDs when
 361       *                                `$fields` is 'ids', or the number of children when `$count`
 362       *                                is true.
 363       *
 364       * @phpstan-param array{
 365       *                    format?: 'tree'|'flat',
 366       *                    status?: 'hold'|'approve'|'all'|string,
 367       *                    hierarchical?: 'threaded'|'flat'|false,
 368       *                    orderby?: string|string[]|false,
 369       *                    fields?: 'ids'|'',
 370       *                    count?: bool,
 371       *                    type?: string,
 372       *                    number?: int,
 373       *                    post_id?: int,
 374       *                    order?: 'ASC'|'DESC',
 375       *                    ...
 376       *                } $args
 377       * @phpstan-return (
 378       *     $args is array{ count: true, ... } ? non-negative-int : (
 379       *         $args is array{ fields: 'ids', ... } ? non-negative-int[] : (
 380       *             $args is array{ format: 'flat', ... } ? list<WP_Comment> : array<int, WP_Comment>
 381       *         )
 382       *     )
 383       * )
 384       */
 385  	public function get_children( $args = array() ) {
 386          $defaults = array(
 387              'format'       => 'tree',
 388              'status'       => 'all',
 389              'hierarchical' => 'threaded',
 390              'orderby'      => '',
 391          );
 392  
 393          /** @var array{ format: 'tree'|'flat', status: string, hierarchical: 'threaded'|'flat'|false, orderby: string|string[]|false, fields?: 'ids'|'', count?: bool, type?: string, number?: int, post_id?: int, order?: 'ASC'|'DESC', ... } $_args */
 394          $_args           = wp_parse_args( $args, $defaults );
 395          $_args['parent'] = $this->comment_ID;
 396  
 397          /*
 398           * A 'count' or 'ids' query returns an integer or a list of comment IDs rather than
 399           * WP_Comment objects. Neither may be written to the children cache, which holds
 400           * WP_Comment objects and is read back by add_child(), get_child(), and the 'flat'
 401           * format below. Return the result directly and leave the cache untouched. The two
 402           * branches must stay separate: each is narrowed independently, and `count` is only
 403           * safe to overwrite in the 'ids' branch.
 404           */
 405          if ( ! empty( $_args['count'] ) ) {
 406              return get_comments( $_args );
 407          } elseif ( isset( $_args['fields'] ) && 'ids' === $_args['fields'] ) {
 408              $_args['count'] = false; // For static analysis of the conditional return type.
 409              return get_comments( $_args );
 410          }
 411  
 412          // Only WP_Comment objects are returned past this point. Stated positively for static analysis.
 413          $_args['count']  = false;
 414          $_args['fields'] = '';
 415  
 416          if ( is_null( $this->children ) ) {
 417              if ( $this->populated_children ) {
 418                  $this->children = array();
 419              } else {
 420                  $this->children = get_comments( $_args );
 421              }
 422          }
 423  
 424          if ( 'flat' === $_args['format'] ) {
 425              $children = array();
 426              foreach ( $this->children as $child ) {
 427                  $child_args           = $_args;
 428                  $child_args['format'] = 'flat';
 429                  // get_children() resets this value automatically.
 430                  unset( $child_args['parent'] );
 431  
 432                  $children = array_merge( $children, array( $child ), $child->get_children( $child_args ) );
 433              }
 434          } else {
 435              $children = $this->children;
 436          }
 437  
 438          return $children;
 439      }
 440  
 441      /**
 442       * Adds a child to the comment.
 443       *
 444       * Used by `WP_Comment_Query` when bulk-filling descendants.
 445       *
 446       * @since 4.4.0
 447       *
 448       * @param WP_Comment $child Child comment.
 449       */
 450  	public function add_child( WP_Comment $child ): void {
 451          $this->children[ (int) $child->comment_ID ] = $child;
 452      }
 453  
 454      /**
 455       * Gets a child comment by ID.
 456       *
 457       * @since 4.4.0
 458       *
 459       * @param int $child_id ID of the child.
 460       * @return WP_Comment|false Returns the comment object if found, otherwise false.
 461       */
 462  	public function get_child( $child_id ) {
 463          return $this->children[ $child_id ] ?? false;
 464      }
 465  
 466      /**
 467       * Sets the 'populated_children' flag.
 468       *
 469       * This flag is important for ensuring that calling `get_children()` on a childless comment will not trigger
 470       * unneeded database queries.
 471       *
 472       * @since 4.4.0
 473       *
 474       * @param bool $set Whether the comment's children have already been populated.
 475       */
 476  	public function populated_children( $set ): void {
 477          $this->populated_children = (bool) $set;
 478      }
 479  
 480      /**
 481       * Determines whether a non-public property is set.
 482       *
 483       * If `$name` matches a post field, the comment post will be loaded and the post's value checked.
 484       *
 485       * @since 4.4.0
 486       * @since 7.1.0 Returns false instead of causing a fatal error when the comment's post cannot be found.
 487       *
 488       * @param string $name Property to check if set.
 489       * @return bool Whether the property is set.
 490       */
 491  	public function __isset( $name ) {
 492          if ( in_array( $name, $this->post_fields, true ) && 0 !== (int) $this->comment_post_ID ) {
 493              $post = get_post( (int) $this->comment_post_ID );
 494              return $post && property_exists( $post, $name );
 495          }
 496  
 497          return false;
 498      }
 499  
 500      /**
 501       * Magic getter.
 502       *
 503       * If `$name` matches a post field, the comment post will be loaded and the post's value returned.
 504       *
 505       * @since 4.4.0
 506       * @since 7.1.0 Returns null instead of the global post's field when the comment is not attached to
 507       *              a post, and no longer raises a warning when the comment's post cannot be found.
 508       *
 509       * @param string $name Property name.
 510       * @return mixed
 511       */
 512  	public function __get( $name ) {
 513          if ( in_array( $name, $this->post_fields, true ) && 0 !== (int) $this->comment_post_ID ) {
 514              $post = get_post( (int) $this->comment_post_ID );
 515              if ( ! $post ) {
 516                  return null;
 517              }
 518              return $post->$name;
 519          }
 520          return null;
 521      }
 522  }


Generated : Thu Jul 30 08:20:17 2026 Cross-referenced by PHPXref