[ Index ]

PHP Cross Reference of WordPress Trunk (Updated Daily)

Search

title

Body

[close]

/wp-includes/ -> meta.php (source)

   1  <?php
   2  /**
   3   * Core Metadata API
   4   *
   5   * Functions for retrieving and manipulating metadata of various WordPress object types. Metadata
   6   * for an object is a represented by a simple key-value pair. Objects may contain multiple
   7   * metadata entries that share the same key and differ only in their value.
   8   *
   9   * @package WordPress
  10   * @subpackage Meta
  11   */
  12  
  13  /**
  14   * Adds metadata for the specified object.
  15   *
  16   * @since 2.9.0
  17   *
  18   * @global wpdb $wpdb WordPress database abstraction object.
  19   *
  20   * @param string $meta_type  Type of object metadata is for. Accepts 'post', 'comment', 'term', 'user',
  21   *                           or any other object type with an associated meta table.
  22   * @param int    $object_id  ID of the object metadata is for.
  23   * @param string $meta_key   Metadata key.
  24   * @param mixed  $meta_value Metadata value. Must be serializable if non-scalar.
  25   * @param bool   $unique     Optional. Whether the specified metadata key should be unique for the object.
  26   *                           If true, and the object already has a value for the specified metadata key,
  27   *                           no change will be made. Default false.
  28   * @return int|false The meta ID on success, false on failure.
  29   */
  30  function add_metadata( $meta_type, $object_id, $meta_key, $meta_value, $unique = false ) {
  31      global $wpdb;
  32  
  33      if ( ! $meta_type || ! $meta_key || ! is_numeric( $object_id ) ) {
  34          return false;
  35      }
  36  
  37      $object_id = absint( $object_id );
  38      if ( ! $object_id ) {
  39          return false;
  40      }
  41  
  42      $table = _get_meta_table( $meta_type );
  43      if ( ! $table ) {
  44          return false;
  45      }
  46  
  47      $meta_subtype = get_object_subtype( $meta_type, $object_id );
  48  
  49      $column = sanitize_key( $meta_type . '_id' );
  50  
  51      // expected_slashed ($meta_key)
  52      $meta_key   = wp_unslash( $meta_key );
  53      $meta_value = wp_unslash( $meta_value );
  54      $meta_value = sanitize_meta( $meta_key, $meta_value, $meta_type, $meta_subtype );
  55  
  56      /**
  57       * Short-circuits adding metadata of a specific type.
  58       *
  59       * The dynamic portion of the hook name, `$meta_type`, refers to the meta object type
  60       * (post, comment, term, user, or any other type with an associated meta table).
  61       * Returning a non-null value will effectively short-circuit the function.
  62       *
  63       * Possible hook names include:
  64       *
  65       *  - `add_post_metadata`
  66       *  - `add_comment_metadata`
  67       *  - `add_term_metadata`
  68       *  - `add_user_metadata`
  69       *
  70       * @since 3.1.0
  71       *
  72       * @param null|bool $check      Whether to allow adding metadata for the given type.
  73       * @param int       $object_id  ID of the object metadata is for.
  74       * @param string    $meta_key   Metadata key.
  75       * @param mixed     $meta_value Metadata value. Must be serializable if non-scalar.
  76       * @param bool      $unique     Whether the specified meta key should be unique for the object.
  77       */
  78      $check = apply_filters( "add_{$meta_type}_metadata", null, $object_id, $meta_key, $meta_value, $unique );
  79      if ( null !== $check ) {
  80          return $check;
  81      }
  82  
  83      if ( $unique && $wpdb->get_var(
  84          $wpdb->prepare(
  85              "SELECT COUNT(*) FROM $table WHERE meta_key = %s AND $column = %d",
  86              $meta_key,
  87              $object_id
  88          )
  89      ) ) {
  90          return false;
  91      }
  92  
  93      $_meta_value = $meta_value;
  94      $meta_value  = maybe_serialize( $meta_value );
  95  
  96      /**
  97       * Fires immediately before meta of a specific type is added.
  98       *
  99       * The dynamic portion of the hook name, `$meta_type`, refers to the meta object type
 100       * (post, comment, term, user, or any other type with an associated meta table).
 101       *
 102       * Possible hook names include:
 103       *
 104       *  - `add_post_meta`
 105       *  - `add_comment_meta`
 106       *  - `add_term_meta`
 107       *  - `add_user_meta`
 108       *
 109       * @since 3.1.0
 110       *
 111       * @param int    $object_id   ID of the object metadata is for.
 112       * @param string $meta_key    Metadata key.
 113       * @param mixed  $_meta_value Metadata value.
 114       */
 115      do_action( "add_{$meta_type}_meta", $object_id, $meta_key, $_meta_value );
 116  
 117      $result = $wpdb->insert(
 118          $table,
 119          array(
 120              $column      => $object_id,
 121              'meta_key'   => $meta_key,
 122              'meta_value' => $meta_value,
 123          )
 124      );
 125  
 126      if ( ! $result ) {
 127          return false;
 128      }
 129  
 130      $mid = (int) $wpdb->insert_id;
 131  
 132      wp_cache_delete( $object_id, $meta_type . '_meta' );
 133  
 134      /**
 135       * Fires immediately after meta of a specific type is added.
 136       *
 137       * The dynamic portion of the hook name, `$meta_type`, refers to the meta object type
 138       * (post, comment, term, user, or any other type with an associated meta table).
 139       *
 140       * Possible hook names include:
 141       *
 142       *  - `added_post_meta`
 143       *  - `added_comment_meta`
 144       *  - `added_term_meta`
 145       *  - `added_user_meta`
 146       *
 147       * @since 2.9.0
 148       *
 149       * @param int    $mid         The meta ID after successful update.
 150       * @param int    $object_id   ID of the object metadata is for.
 151       * @param string $meta_key    Metadata key.
 152       * @param mixed  $_meta_value Metadata value.
 153       */
 154      do_action( "added_{$meta_type}_meta", $mid, $object_id, $meta_key, $_meta_value );
 155  
 156      return $mid;
 157  }
 158  
 159  /**
 160   * Updates metadata for the specified object. If no value already exists for the specified object
 161   * ID and metadata key, the metadata will be added.
 162   *
 163   * @since 2.9.0
 164   *
 165   * @global wpdb $wpdb WordPress database abstraction object.
 166   *
 167   * @param string $meta_type  Type of object metadata is for. Accepts 'post', 'comment', 'term', 'user',
 168   *                           or any other object type with an associated meta table.
 169   * @param int    $object_id  ID of the object metadata is for.
 170   * @param string $meta_key   Metadata key.
 171   * @param mixed  $meta_value Metadata value. Must be serializable if non-scalar.
 172   * @param mixed  $prev_value Optional. Previous value to check before updating.
 173   *                           If specified, only update existing metadata entries with
 174   *                           this value. Otherwise, update all entries. Default empty.
 175   * @return int|bool The new meta field ID if a field with the given key didn't exist
 176   *                  and was therefore added, true on successful update,
 177   *                  false on failure or if the value passed to the function
 178   *                  is the same as the one that is already in the database.
 179   */
 180  function update_metadata( $meta_type, $object_id, $meta_key, $meta_value, $prev_value = '' ) {
 181      global $wpdb;
 182  
 183      if ( ! $meta_type || ! $meta_key || ! is_numeric( $object_id ) ) {
 184          return false;
 185      }
 186  
 187      $object_id = absint( $object_id );
 188      if ( ! $object_id ) {
 189          return false;
 190      }
 191  
 192      $table = _get_meta_table( $meta_type );
 193      if ( ! $table ) {
 194          return false;
 195      }
 196  
 197      $meta_subtype = get_object_subtype( $meta_type, $object_id );
 198  
 199      $column    = sanitize_key( $meta_type . '_id' );
 200      $id_column = ( 'user' === $meta_type ) ? 'umeta_id' : 'meta_id';
 201  
 202      // expected_slashed ($meta_key)
 203      $raw_meta_key = $meta_key;
 204      $meta_key     = wp_unslash( $meta_key );
 205      $passed_value = $meta_value;
 206      $meta_value   = wp_unslash( $meta_value );
 207      $meta_value   = sanitize_meta( $meta_key, $meta_value, $meta_type, $meta_subtype );
 208  
 209      /**
 210       * Short-circuits updating metadata of a specific type.
 211       *
 212       * The dynamic portion of the hook name, `$meta_type`, refers to the meta object type
 213       * (post, comment, term, user, or any other type with an associated meta table).
 214       * Returning a non-null value will effectively short-circuit the function.
 215       *
 216       * Possible hook names include:
 217       *
 218       *  - `update_post_metadata`
 219       *  - `update_comment_metadata`
 220       *  - `update_term_metadata`
 221       *  - `update_user_metadata`
 222       *
 223       * @since 3.1.0
 224       *
 225       * @param null|bool $check      Whether to allow updating metadata for the given type.
 226       * @param int       $object_id  ID of the object metadata is for.
 227       * @param string    $meta_key   Metadata key.
 228       * @param mixed     $meta_value Metadata value. Must be serializable if non-scalar.
 229       * @param mixed     $prev_value Optional. Previous value to check before updating.
 230       *                              If specified, only update existing metadata entries with
 231       *                              this value. Otherwise, update all entries.
 232       */
 233      $check = apply_filters( "update_{$meta_type}_metadata", null, $object_id, $meta_key, $meta_value, $prev_value );
 234      if ( null !== $check ) {
 235          return (bool) $check;
 236      }
 237  
 238      // Compare existing value to new value if no prev value given and the key exists only once.
 239      if ( empty( $prev_value ) ) {
 240          $old_value = get_metadata_raw( $meta_type, $object_id, $meta_key );
 241          if ( is_countable( $old_value ) && count( $old_value ) === 1 ) {
 242              if ( $old_value[0] === $meta_value ) {
 243                  return false;
 244              }
 245          }
 246      }
 247  
 248      $meta_ids = $wpdb->get_col( $wpdb->prepare( "SELECT $id_column FROM $table WHERE meta_key = %s AND $column = %d", $meta_key, $object_id ) );
 249      if ( empty( $meta_ids ) ) {
 250          return add_metadata( $meta_type, $object_id, $raw_meta_key, $passed_value );
 251      }
 252  
 253      $_meta_value = $meta_value;
 254      $meta_value  = maybe_serialize( $meta_value );
 255  
 256      $data  = compact( 'meta_value' );
 257      $where = array(
 258          $column    => $object_id,
 259          'meta_key' => $meta_key,
 260      );
 261  
 262      if ( ! empty( $prev_value ) ) {
 263          $prev_value          = maybe_serialize( $prev_value );
 264          $where['meta_value'] = $prev_value;
 265      }
 266  
 267      foreach ( $meta_ids as $meta_id ) {
 268          /**
 269           * Fires immediately before updating metadata of a specific type.
 270           *
 271           * The dynamic portion of the hook name, `$meta_type`, refers to the meta object type
 272           * (post, comment, term, user, or any other type with an associated meta table).
 273           *
 274           * Possible hook names include:
 275           *
 276           *  - `update_post_meta`
 277           *  - `update_comment_meta`
 278           *  - `update_term_meta`
 279           *  - `update_user_meta`
 280           *
 281           * @since 2.9.0
 282           *
 283           * @param int    $meta_id     ID of the metadata entry to update.
 284           * @param int    $object_id   ID of the object metadata is for.
 285           * @param string $meta_key    Metadata key.
 286           * @param mixed  $_meta_value Metadata value.
 287           */
 288          do_action( "update_{$meta_type}_meta", $meta_id, $object_id, $meta_key, $_meta_value );
 289  
 290          if ( 'post' === $meta_type ) {
 291              /**
 292               * Fires immediately before updating a post's metadata.
 293               *
 294               * @since 2.9.0
 295               *
 296               * @param int    $meta_id    ID of metadata entry to update.
 297               * @param int    $object_id  Post ID.
 298               * @param string $meta_key   Metadata key.
 299               * @param mixed  $meta_value Metadata value. This will be a PHP-serialized string representation of the value
 300               *                           if the value is an array, an object, or itself a PHP-serialized string.
 301               */
 302              do_action( 'update_postmeta', $meta_id, $object_id, $meta_key, $meta_value );
 303          }
 304      }
 305  
 306      $result = $wpdb->update( $table, $data, $where );
 307      if ( ! $result ) {
 308          return false;
 309      }
 310  
 311      wp_cache_delete( $object_id, $meta_type . '_meta' );
 312  
 313      foreach ( $meta_ids as $meta_id ) {
 314          /**
 315           * Fires immediately after updating metadata of a specific type.
 316           *
 317           * The dynamic portion of the hook name, `$meta_type`, refers to the meta object type
 318           * (post, comment, term, user, or any other type with an associated meta table).
 319           *
 320           * Possible hook names include:
 321           *
 322           *  - `updated_post_meta`
 323           *  - `updated_comment_meta`
 324           *  - `updated_term_meta`
 325           *  - `updated_user_meta`
 326           *
 327           * @since 2.9.0
 328           *
 329           * @param int    $meta_id     ID of updated metadata entry.
 330           * @param int    $object_id   ID of the object metadata is for.
 331           * @param string $meta_key    Metadata key.
 332           * @param mixed  $_meta_value Metadata value.
 333           */
 334          do_action( "updated_{$meta_type}_meta", $meta_id, $object_id, $meta_key, $_meta_value );
 335  
 336          if ( 'post' === $meta_type ) {
 337              /**
 338               * Fires immediately after updating a post's metadata.
 339               *
 340               * @since 2.9.0
 341               *
 342               * @param int    $meta_id    ID of updated metadata entry.
 343               * @param int    $object_id  Post ID.
 344               * @param string $meta_key   Metadata key.
 345               * @param mixed  $meta_value Metadata value. This will be a PHP-serialized string representation of the value
 346               *                           if the value is an array, an object, or itself a PHP-serialized string.
 347               */
 348              do_action( 'updated_postmeta', $meta_id, $object_id, $meta_key, $meta_value );
 349          }
 350      }
 351  
 352      return true;
 353  }
 354  
 355  /**
 356   * Deletes metadata for the specified object.
 357   *
 358   * @since 2.9.0
 359   *
 360   * @global wpdb $wpdb WordPress database abstraction object.
 361   *
 362   * @param string $meta_type  Type of object metadata is for. Accepts 'post', 'comment', 'term', 'user',
 363   *                           or any other object type with an associated meta table.
 364   * @param int    $object_id  ID of the object metadata is for.
 365   * @param string $meta_key   Metadata key.
 366   * @param mixed  $meta_value Optional. Metadata value. Must be serializable if non-scalar.
 367   *                           If specified, only delete metadata entries with this value.
 368   *                           Otherwise, delete all entries with the specified meta_key.
 369   *                           Pass `null`, `false`, or an empty string to skip this check.
 370   *                           (For backward compatibility, it is not possible to pass an empty string
 371   *                           to delete those entries with an empty string for a value.)
 372   * @param bool   $delete_all Optional. If true, delete matching metadata entries for all objects,
 373   *                           ignoring the specified object_id. Otherwise, only delete
 374   *                           matching metadata entries for the specified object_id. Default false.
 375   * @return bool True on successful delete, false on failure.
 376   */
 377  function delete_metadata( $meta_type, $object_id, $meta_key, $meta_value = '', $delete_all = false ) {
 378      global $wpdb;
 379  
 380      if ( ! $meta_type || ! $meta_key || ! is_numeric( $object_id ) && ! $delete_all ) {
 381          return false;
 382      }
 383  
 384      $object_id = absint( $object_id );
 385      if ( ! $object_id && ! $delete_all ) {
 386          return false;
 387      }
 388  
 389      $table = _get_meta_table( $meta_type );
 390      if ( ! $table ) {
 391          return false;
 392      }
 393  
 394      $type_column = sanitize_key( $meta_type . '_id' );
 395      $id_column   = ( 'user' === $meta_type ) ? 'umeta_id' : 'meta_id';
 396  
 397      // expected_slashed ($meta_key)
 398      $meta_key   = wp_unslash( $meta_key );
 399      $meta_value = wp_unslash( $meta_value );
 400  
 401      /**
 402       * Short-circuits deleting metadata of a specific type.
 403       *
 404       * The dynamic portion of the hook name, `$meta_type`, refers to the meta object type
 405       * (post, comment, term, user, or any other type with an associated meta table).
 406       * Returning a non-null value will effectively short-circuit the function.
 407       *
 408       * Possible hook names include:
 409       *
 410       *  - `delete_post_metadata`
 411       *  - `delete_comment_metadata`
 412       *  - `delete_term_metadata`
 413       *  - `delete_user_metadata`
 414       *
 415       * @since 3.1.0
 416       *
 417       * @param null|bool $delete     Whether to allow metadata deletion of the given type.
 418       * @param int       $object_id  ID of the object metadata is for.
 419       * @param string    $meta_key   Metadata key.
 420       * @param mixed     $meta_value Metadata value. Must be serializable if non-scalar.
 421       * @param bool      $delete_all Whether to delete the matching metadata entries
 422       *                              for all objects, ignoring the specified $object_id.
 423       *                              Default false.
 424       */
 425      $check = apply_filters( "delete_{$meta_type}_metadata", null, $object_id, $meta_key, $meta_value, $delete_all );
 426      if ( null !== $check ) {
 427          return (bool) $check;
 428      }
 429  
 430      $_meta_value = $meta_value;
 431      $meta_value  = maybe_serialize( $meta_value );
 432  
 433      $query = $wpdb->prepare( "SELECT $id_column FROM $table WHERE meta_key = %s", $meta_key );
 434  
 435      if ( ! $delete_all ) {
 436          $query .= $wpdb->prepare( " AND $type_column = %d", $object_id );
 437      }
 438  
 439      if ( '' !== $meta_value && null !== $meta_value && false !== $meta_value ) {
 440          $query .= $wpdb->prepare( ' AND meta_value = %s', $meta_value );
 441      }
 442  
 443      $meta_ids = $wpdb->get_col( $query );
 444      if ( ! count( $meta_ids ) ) {
 445          return false;
 446      }
 447  
 448      if ( $delete_all ) {
 449          if ( '' !== $meta_value && null !== $meta_value && false !== $meta_value ) {
 450              $object_ids = $wpdb->get_col( $wpdb->prepare( "SELECT $type_column FROM $table WHERE meta_key = %s AND meta_value = %s", $meta_key, $meta_value ) );
 451          } else {
 452              $object_ids = $wpdb->get_col( $wpdb->prepare( "SELECT $type_column FROM $table WHERE meta_key = %s", $meta_key ) );
 453          }
 454      }
 455  
 456      /**
 457       * Fires immediately before deleting metadata of a specific type.
 458       *
 459       * The dynamic portion of the hook name, `$meta_type`, refers to the meta object type
 460       * (post, comment, term, user, or any other type with an associated meta table).
 461       *
 462       * Possible hook names include:
 463       *
 464       *  - `delete_post_meta`
 465       *  - `delete_comment_meta`
 466       *  - `delete_term_meta`
 467       *  - `delete_user_meta`
 468       *
 469       * @since 3.1.0
 470       *
 471       * @param string[] $meta_ids    An array of metadata entry IDs to delete.
 472       * @param int      $object_id   ID of the object metadata is for.
 473       * @param string   $meta_key    Metadata key.
 474       * @param mixed    $_meta_value Metadata value.
 475       */
 476      do_action( "delete_{$meta_type}_meta", $meta_ids, $object_id, $meta_key, $_meta_value );
 477  
 478      // Old-style action.
 479      if ( 'post' === $meta_type ) {
 480          /**
 481           * Fires immediately before deleting metadata for a post.
 482           *
 483           * @since 2.9.0
 484           *
 485           * @param string[] $meta_ids An array of metadata entry IDs to delete.
 486           */
 487          do_action( 'delete_postmeta', $meta_ids );
 488      }
 489  
 490      $query = "DELETE FROM $table WHERE $id_column IN( " . implode( ',', $meta_ids ) . ' )';
 491  
 492      $count = $wpdb->query( $query );
 493  
 494      if ( ! $count ) {
 495          return false;
 496      }
 497  
 498      if ( $delete_all ) {
 499          $data = (array) $object_ids;
 500      } else {
 501          $data = array( $object_id );
 502      }
 503      wp_cache_delete_multiple( $data, $meta_type . '_meta' );
 504  
 505      /**
 506       * Fires immediately after deleting metadata of a specific type.
 507       *
 508       * The dynamic portion of the hook name, `$meta_type`, refers to the meta object type
 509       * (post, comment, term, user, or any other type with an associated meta table).
 510       *
 511       * Possible hook names include:
 512       *
 513       *  - `deleted_post_meta`
 514       *  - `deleted_comment_meta`
 515       *  - `deleted_term_meta`
 516       *  - `deleted_user_meta`
 517       *
 518       * @since 2.9.0
 519       *
 520       * @param string[] $meta_ids    An array of metadata entry IDs to delete.
 521       * @param int      $object_id   ID of the object metadata is for.
 522       * @param string   $meta_key    Metadata key.
 523       * @param mixed    $_meta_value Metadata value.
 524       */
 525      do_action( "deleted_{$meta_type}_meta", $meta_ids, $object_id, $meta_key, $_meta_value );
 526  
 527      // Old-style action.
 528      if ( 'post' === $meta_type ) {
 529          /**
 530           * Fires immediately after deleting metadata for a post.
 531           *
 532           * @since 2.9.0
 533           *
 534           * @param string[] $meta_ids An array of metadata entry IDs to delete.
 535           */
 536          do_action( 'deleted_postmeta', $meta_ids );
 537      }
 538  
 539      return true;
 540  }
 541  
 542  /**
 543   * Retrieves the value of a metadata field for the specified object type and ID.
 544   *
 545   * If the meta field exists, a single value is returned if `$single` is true,
 546   * or an array of values if it's false.
 547   *
 548   * If the meta field does not exist, the result depends on get_metadata_default().
 549   * By default, an empty string is returned if `$single` is true, or an empty array
 550   * if it's false.
 551   *
 552   * @since 2.9.0
 553   *
 554   * @see get_metadata_raw()
 555   * @see get_metadata_default()
 556   *
 557   * @param string $meta_type Type of object metadata is for. Accepts 'post', 'comment', 'term', 'user',
 558   *                          or any other object type with an associated meta table.
 559   * @param int    $object_id ID of the object metadata is for.
 560   * @param string $meta_key  Optional. Metadata key. If not specified, retrieve all metadata for
 561   *                          the specified object. Default empty.
 562   * @param bool   $single    Optional. If true, return only the first value of the specified `$meta_key`.
 563   *                          This parameter has no effect if `$meta_key` is not specified. Default false.
 564   * @return mixed An array of values if `$single` is false.
 565   *               The value of the meta field if `$single` is true.
 566   *               False for an invalid `$object_id` (non-numeric, zero, or negative value),
 567   *               or if `$meta_type` is not specified.
 568   *               An empty string if a valid but non-existing object ID is passed.
 569   */
 570  function get_metadata( $meta_type, $object_id, $meta_key = '', $single = false ) {
 571      $value = get_metadata_raw( $meta_type, $object_id, $meta_key, $single );
 572      if ( ! is_null( $value ) ) {
 573          return $value;
 574      }
 575  
 576      return get_metadata_default( $meta_type, $object_id, $meta_key, $single );
 577  }
 578  
 579  /**
 580   * Retrieves raw metadata value for the specified object.
 581   *
 582   * @since 5.5.0
 583   *
 584   * @param string $meta_type Type of object metadata is for. Accepts 'post', 'comment', 'term', 'user',
 585   *                          or any other object type with an associated meta table.
 586   * @param int    $object_id ID of the object metadata is for.
 587   * @param string $meta_key  Optional. Metadata key. If not specified, retrieve all metadata for
 588   *                          the specified object. Default empty.
 589   * @param bool   $single    Optional. If true, return only the first value of the specified `$meta_key`.
 590   *                          This parameter has no effect if `$meta_key` is not specified. Default false.
 591   * @return mixed An array of values if `$single` is false.
 592   *               The value of the meta field if `$single` is true.
 593   *               False for an invalid `$object_id` (non-numeric, zero, or negative value),
 594   *               or if `$meta_type` is not specified.
 595   *               Null if the value does not exist.
 596   */
 597  function get_metadata_raw( $meta_type, $object_id, $meta_key = '', $single = false ) {
 598      if ( ! $meta_type || ! is_numeric( $object_id ) ) {
 599          return false;
 600      }
 601  
 602      $object_id = absint( $object_id );
 603      if ( ! $object_id ) {
 604          return false;
 605      }
 606  
 607      /**
 608       * Short-circuits the return value of a meta field.
 609       *
 610       * The dynamic portion of the hook name, `$meta_type`, refers to the meta object type
 611       * (post, comment, term, user, or any other type with an associated meta table).
 612       * Returning a non-null value will effectively short-circuit the function.
 613       *
 614       * Possible filter names include:
 615       *
 616       *  - `get_post_metadata`
 617       *  - `get_comment_metadata`
 618       *  - `get_term_metadata`
 619       *  - `get_user_metadata`
 620       *
 621       * @since 3.1.0
 622       * @since 5.5.0 Added the `$meta_type` parameter.
 623       *
 624       * @param mixed  $value     The value to return, either a single metadata value or an array
 625       *                          of values depending on the value of `$single`. Default null.
 626       * @param int    $object_id ID of the object metadata is for.
 627       * @param string $meta_key  Metadata key.
 628       * @param bool   $single    Whether to return only the first value of the specified `$meta_key`.
 629       * @param string $meta_type Type of object metadata is for. Accepts 'post', 'comment', 'term', 'user',
 630       *                          or any other object type with an associated meta table.
 631       */
 632      $check = apply_filters( "get_{$meta_type}_metadata", null, $object_id, $meta_key, $single, $meta_type );
 633      if ( null !== $check ) {
 634          if ( $single && is_array( $check ) ) {
 635              return $check[0];
 636          } else {
 637              return $check;
 638          }
 639      }
 640  
 641      $meta_cache = wp_cache_get( $object_id, $meta_type . '_meta' );
 642  
 643      if ( ! $meta_cache ) {
 644          $meta_cache = update_meta_cache( $meta_type, array( $object_id ) );
 645          if ( isset( $meta_cache[ $object_id ] ) ) {
 646              $meta_cache = $meta_cache[ $object_id ];
 647          } else {
 648              $meta_cache = null;
 649          }
 650      }
 651  
 652      if ( ! $meta_key ) {
 653          return $meta_cache;
 654      }
 655  
 656      if ( isset( $meta_cache[ $meta_key ] ) ) {
 657          if ( $single ) {
 658              return maybe_unserialize( $meta_cache[ $meta_key ][0] );
 659          } else {
 660              return array_map( 'maybe_unserialize', $meta_cache[ $meta_key ] );
 661          }
 662      }
 663  
 664      return null;
 665  }
 666  
 667  /**
 668   * Retrieves default metadata value for the specified meta key and object.
 669   *
 670   * By default, an empty string is returned if `$single` is true, or an empty array
 671   * if it's false.
 672   *
 673   * @since 5.5.0
 674   *
 675   * @param string $meta_type Type of object metadata is for. Accepts 'post', 'comment', 'term', 'user',
 676   *                          or any other object type with an associated meta table.
 677   * @param int    $object_id ID of the object metadata is for.
 678   * @param string $meta_key  Metadata key.
 679   * @param bool   $single    Optional. If true, return only the first value of the specified `$meta_key`.
 680   *                          This parameter has no effect if `$meta_key` is not specified. Default false.
 681   * @return mixed An array of default values if `$single` is false.
 682   *               The default value of the meta field if `$single` is true.
 683   */
 684  function get_metadata_default( $meta_type, $object_id, $meta_key, $single = false ) {
 685      if ( $single ) {
 686          $value = '';
 687      } else {
 688          $value = array();
 689      }
 690  
 691      /**
 692       * Filters the default metadata value for a specified meta key and object.
 693       *
 694       * The dynamic portion of the hook name, `$meta_type`, refers to the meta object type
 695       * (post, comment, term, user, or any other type with an associated meta table).
 696       *
 697       * Possible filter names include:
 698       *
 699       *  - `default_post_metadata`
 700       *  - `default_comment_metadata`
 701       *  - `default_term_metadata`
 702       *  - `default_user_metadata`
 703       *
 704       * @since 5.5.0
 705       *
 706       * @param mixed  $value     The value to return, either a single metadata value or an array
 707       *                          of values depending on the value of `$single`.
 708       * @param int    $object_id ID of the object metadata is for.
 709       * @param string $meta_key  Metadata key.
 710       * @param bool   $single    Whether to return only the first value of the specified `$meta_key`.
 711       * @param string $meta_type Type of object metadata is for. Accepts 'post', 'comment', 'term', 'user',
 712       *                          or any other object type with an associated meta table.
 713       */
 714      $value = apply_filters( "default_{$meta_type}_metadata", $value, $object_id, $meta_key, $single, $meta_type );
 715  
 716      if ( ! $single && ! wp_is_numeric_array( $value ) ) {
 717          $value = array( $value );
 718      }
 719  
 720      return $value;
 721  }
 722  
 723  /**
 724   * Determines if a meta field with the given key exists for the given object ID.
 725   *
 726   * @since 3.3.0
 727   *
 728   * @param string $meta_type Type of object metadata is for. Accepts 'post', 'comment', 'term', 'user',
 729   *                          or any other object type with an associated meta table.
 730   * @param int    $object_id ID of the object metadata is for.
 731   * @param string $meta_key  Metadata key.
 732   * @return bool Whether a meta field with the given key exists.
 733   */
 734  function metadata_exists( $meta_type, $object_id, $meta_key ) {
 735      if ( ! $meta_type || ! is_numeric( $object_id ) ) {
 736          return false;
 737      }
 738  
 739      $object_id = absint( $object_id );
 740      if ( ! $object_id ) {
 741          return false;
 742      }
 743  
 744      /** This filter is documented in wp-includes/meta.php */
 745      $check = apply_filters( "get_{$meta_type}_metadata", null, $object_id, $meta_key, true, $meta_type );
 746      if ( null !== $check ) {
 747          return (bool) $check;
 748      }
 749  
 750      $meta_cache = wp_cache_get( $object_id, $meta_type . '_meta' );
 751  
 752      if ( ! $meta_cache ) {
 753          $meta_cache = update_meta_cache( $meta_type, array( $object_id ) );
 754          $meta_cache = $meta_cache[ $object_id ];
 755      }
 756  
 757      if ( isset( $meta_cache[ $meta_key ] ) ) {
 758          return true;
 759      }
 760  
 761      return false;
 762  }
 763  
 764  /**
 765   * Retrieves metadata by meta ID.
 766   *
 767   * @since 3.3.0
 768   *
 769   * @global wpdb $wpdb WordPress database abstraction object.
 770   *
 771   * @param string $meta_type Type of object metadata is for. Accepts 'post', 'comment', 'term', 'user',
 772   *                          or any other object type with an associated meta table.
 773   * @param int    $meta_id   ID for a specific meta row.
 774   * @return stdClass|false {
 775   *     Metadata object, or boolean `false` if the metadata doesn't exist.
 776   *
 777   *     @type string $meta_key   The meta key.
 778   *     @type mixed  $meta_value The unserialized meta value.
 779   *     @type string $meta_id    Optional. The meta ID when the meta type is any value except 'user'.
 780   *     @type string $umeta_id   Optional. The meta ID when the meta type is 'user'.
 781   *     @type string $post_id    Optional. The object ID when the meta type is 'post'.
 782   *     @type string $comment_id Optional. The object ID when the meta type is 'comment'.
 783   *     @type string $term_id    Optional. The object ID when the meta type is 'term'.
 784   *     @type string $user_id    Optional. The object ID when the meta type is 'user'.
 785   * }
 786   */
 787  function get_metadata_by_mid( $meta_type, $meta_id ) {
 788      global $wpdb;
 789  
 790      if ( ! $meta_type || ! is_numeric( $meta_id ) || floor( $meta_id ) != $meta_id ) {
 791          return false;
 792      }
 793  
 794      $meta_id = (int) $meta_id;
 795      if ( $meta_id <= 0 ) {
 796          return false;
 797      }
 798  
 799      $table = _get_meta_table( $meta_type );
 800      if ( ! $table ) {
 801          return false;
 802      }
 803  
 804      /**
 805       * Short-circuits the return value when fetching a meta field by meta ID.
 806       *
 807       * The dynamic portion of the hook name, `$meta_type`, refers to the meta object type
 808       * (post, comment, term, user, or any other type with an associated meta table).
 809       * Returning a non-null value will effectively short-circuit the function.
 810       *
 811       * Possible hook names include:
 812       *
 813       *  - `get_post_metadata_by_mid`
 814       *  - `get_comment_metadata_by_mid`
 815       *  - `get_term_metadata_by_mid`
 816       *  - `get_user_metadata_by_mid`
 817       *
 818       * @since 5.0.0
 819       *
 820       * @param stdClass|null $value   The value to return.
 821       * @param int           $meta_id Meta ID.
 822       */
 823      $check = apply_filters( "get_{$meta_type}_metadata_by_mid", null, $meta_id );
 824      if ( null !== $check ) {
 825          return $check;
 826      }
 827  
 828      $id_column = ( 'user' === $meta_type ) ? 'umeta_id' : 'meta_id';
 829  
 830      $meta = $wpdb->get_row( $wpdb->prepare( "SELECT * FROM $table WHERE $id_column = %d", $meta_id ) );
 831  
 832      if ( empty( $meta ) ) {
 833          return false;
 834      }
 835  
 836      if ( isset( $meta->meta_value ) ) {
 837          $meta->meta_value = maybe_unserialize( $meta->meta_value );
 838      }
 839  
 840      return $meta;
 841  }
 842  
 843  /**
 844   * Updates metadata by meta ID.
 845   *
 846   * @since 3.3.0
 847   *
 848   * @global wpdb $wpdb WordPress database abstraction object.
 849   *
 850   * @param string       $meta_type  Type of object metadata is for. Accepts 'post', 'comment', 'term', 'user',
 851   *                                 or any other object type with an associated meta table.
 852   * @param int          $meta_id    ID for a specific meta row.
 853   * @param string       $meta_value Metadata value. Must be serializable if non-scalar.
 854   * @param string|false $meta_key   Optional. You can provide a meta key to update it. Default false.
 855   * @return bool True on successful update, false on failure.
 856   */
 857  function update_metadata_by_mid( $meta_type, $meta_id, $meta_value, $meta_key = false ) {
 858      global $wpdb;
 859  
 860      // Make sure everything is valid.
 861      if ( ! $meta_type || ! is_numeric( $meta_id ) || floor( $meta_id ) != $meta_id ) {
 862          return false;
 863      }
 864  
 865      $meta_id = (int) $meta_id;
 866      if ( $meta_id <= 0 ) {
 867          return false;
 868      }
 869  
 870      $table = _get_meta_table( $meta_type );
 871      if ( ! $table ) {
 872          return false;
 873      }
 874  
 875      $column    = sanitize_key( $meta_type . '_id' );
 876      $id_column = ( 'user' === $meta_type ) ? 'umeta_id' : 'meta_id';
 877  
 878      /**
 879       * Short-circuits updating metadata of a specific type by meta ID.
 880       *
 881       * The dynamic portion of the hook name, `$meta_type`, refers to the meta object type
 882       * (post, comment, term, user, or any other type with an associated meta table).
 883       * Returning a non-null value will effectively short-circuit the function.
 884       *
 885       * Possible hook names include:
 886       *
 887       *  - `update_post_metadata_by_mid`
 888       *  - `update_comment_metadata_by_mid`
 889       *  - `update_term_metadata_by_mid`
 890       *  - `update_user_metadata_by_mid`
 891       *
 892       * @since 5.0.0
 893       *
 894       * @param null|bool    $check      Whether to allow updating metadata for the given type.
 895       * @param int          $meta_id    Meta ID.
 896       * @param mixed        $meta_value Meta value. Must be serializable if non-scalar.
 897       * @param string|false $meta_key   Meta key, if provided.
 898       */
 899      $check = apply_filters( "update_{$meta_type}_metadata_by_mid", null, $meta_id, $meta_value, $meta_key );
 900      if ( null !== $check ) {
 901          return (bool) $check;
 902      }
 903  
 904      // Fetch the meta and go on if it's found.
 905      $meta = get_metadata_by_mid( $meta_type, $meta_id );
 906      if ( $meta ) {
 907          $original_key = $meta->meta_key;
 908          $object_id    = $meta->{$column};
 909  
 910          // If a new meta_key (last parameter) was specified, change the meta key,
 911          // otherwise use the original key in the update statement.
 912          if ( false === $meta_key ) {
 913              $meta_key = $original_key;
 914          } elseif ( ! is_string( $meta_key ) ) {
 915              return false;
 916          }
 917  
 918          $meta_subtype = get_object_subtype( $meta_type, $object_id );
 919  
 920          // Sanitize the meta.
 921          $_meta_value = $meta_value;
 922          $meta_value  = sanitize_meta( $meta_key, $meta_value, $meta_type, $meta_subtype );
 923          $meta_value  = maybe_serialize( $meta_value );
 924  
 925          // Format the data query arguments.
 926          $data = array(
 927              'meta_key'   => $meta_key,
 928              'meta_value' => $meta_value,
 929          );
 930  
 931          // Format the where query arguments.
 932          $where               = array();
 933          $where[ $id_column ] = $meta_id;
 934  
 935          /** This action is documented in wp-includes/meta.php */
 936          do_action( "update_{$meta_type}_meta", $meta_id, $object_id, $meta_key, $_meta_value );
 937  
 938          if ( 'post' === $meta_type ) {
 939              /** This action is documented in wp-includes/meta.php */
 940              do_action( 'update_postmeta', $meta_id, $object_id, $meta_key, $meta_value );
 941          }
 942  
 943          // Run the update query, all fields in $data are %s, $where is a %d.
 944          $result = $wpdb->update( $table, $data, $where, '%s', '%d' );
 945          if ( ! $result ) {
 946              return false;
 947          }
 948  
 949          // Clear the caches.
 950          wp_cache_delete( $object_id, $meta_type . '_meta' );
 951  
 952          /** This action is documented in wp-includes/meta.php */
 953          do_action( "updated_{$meta_type}_meta", $meta_id, $object_id, $meta_key, $_meta_value );
 954  
 955          if ( 'post' === $meta_type ) {
 956              /** This action is documented in wp-includes/meta.php */
 957              do_action( 'updated_postmeta', $meta_id, $object_id, $meta_key, $meta_value );
 958          }
 959  
 960          return true;
 961      }
 962  
 963      // And if the meta was not found.
 964      return false;
 965  }
 966  
 967  /**
 968   * Deletes metadata by meta ID.
 969   *
 970   * @since 3.3.0
 971   *
 972   * @global wpdb $wpdb WordPress database abstraction object.
 973   *
 974   * @param string $meta_type Type of object metadata is for. Accepts 'post', 'comment', 'term', 'user',
 975   *                          or any other object type with an associated meta table.
 976   * @param int    $meta_id   ID for a specific meta row.
 977   * @return bool True on successful delete, false on failure.
 978   */
 979  function delete_metadata_by_mid( $meta_type, $meta_id ) {
 980      global $wpdb;
 981  
 982      // Make sure everything is valid.
 983      if ( ! $meta_type || ! is_numeric( $meta_id ) || floor( $meta_id ) != $meta_id ) {
 984          return false;
 985      }
 986  
 987      $meta_id = (int) $meta_id;
 988      if ( $meta_id <= 0 ) {
 989          return false;
 990      }
 991  
 992      $table = _get_meta_table( $meta_type );
 993      if ( ! $table ) {
 994          return false;
 995      }
 996  
 997      // Object and ID columns.
 998      $column    = sanitize_key( $meta_type . '_id' );
 999      $id_column = ( 'user' === $meta_type ) ? 'umeta_id' : 'meta_id';
1000  
1001      /**
1002       * Short-circuits deleting metadata of a specific type by meta ID.
1003       *
1004       * The dynamic portion of the hook name, `$meta_type`, refers to the meta object type
1005       * (post, comment, term, user, or any other type with an associated meta table).
1006       * Returning a non-null value will effectively short-circuit the function.
1007       *
1008       * Possible hook names include:
1009       *
1010       *  - `delete_post_metadata_by_mid`
1011       *  - `delete_comment_metadata_by_mid`
1012       *  - `delete_term_metadata_by_mid`
1013       *  - `delete_user_metadata_by_mid`
1014       *
1015       * @since 5.0.0
1016       *
1017       * @param null|bool $delete  Whether to allow metadata deletion of the given type.
1018       * @param int       $meta_id Meta ID.
1019       */
1020      $check = apply_filters( "delete_{$meta_type}_metadata_by_mid", null, $meta_id );
1021      if ( null !== $check ) {
1022          return (bool) $check;
1023      }
1024  
1025      // Fetch the meta and go on if it's found.
1026      $meta = get_metadata_by_mid( $meta_type, $meta_id );
1027      if ( $meta ) {
1028          $object_id = (int) $meta->{$column};
1029  
1030          /** This action is documented in wp-includes/meta.php */
1031          do_action( "delete_{$meta_type}_meta", (array) $meta_id, $object_id, $meta->meta_key, $meta->meta_value );
1032  
1033          // Old-style action.
1034          if ( 'post' === $meta_type || 'comment' === $meta_type ) {
1035              /**
1036               * Fires immediately before deleting post or comment metadata of a specific type.
1037               *
1038               * The dynamic portion of the hook name, `$meta_type`, refers to the meta
1039               * object type (post or comment).
1040               *
1041               * Possible hook names include:
1042               *
1043               *  - `delete_postmeta`
1044               *  - `delete_commentmeta`
1045               *  - `delete_termmeta`
1046               *  - `delete_usermeta`
1047               *
1048               * @since 3.4.0
1049               *
1050               * @param int $meta_id ID of the metadata entry to delete.
1051               */
1052              do_action( "delete_{$meta_type}meta", $meta_id );
1053          }
1054  
1055          // Run the query, will return true if deleted, false otherwise.
1056          $result = (bool) $wpdb->delete( $table, array( $id_column => $meta_id ) );
1057  
1058          // Clear the caches.
1059          wp_cache_delete( $object_id, $meta_type . '_meta' );
1060  
1061          /** This action is documented in wp-includes/meta.php */
1062          do_action( "deleted_{$meta_type}_meta", (array) $meta_id, $object_id, $meta->meta_key, $meta->meta_value );
1063  
1064          // Old-style action.
1065          if ( 'post' === $meta_type || 'comment' === $meta_type ) {
1066              /**
1067               * Fires immediately after deleting post or comment metadata of a specific type.
1068               *
1069               * The dynamic portion of the hook name, `$meta_type`, refers to the meta
1070               * object type (post or comment).
1071               *
1072               * Possible hook names include:
1073               *
1074               *  - `deleted_postmeta`
1075               *  - `deleted_commentmeta`
1076               *  - `deleted_termmeta`
1077               *  - `deleted_usermeta`
1078               *
1079               * @since 3.4.0
1080               *
1081               * @param int $meta_ids Deleted metadata entry ID.
1082               */
1083              do_action( "deleted_{$meta_type}meta", $meta_id );
1084          }
1085  
1086          return $result;
1087  
1088      }
1089  
1090      // Meta ID was not found.
1091      return false;
1092  }
1093  
1094  /**
1095   * Updates the metadata cache for the specified objects.
1096   *
1097   * @since 2.9.0
1098   *
1099   * @global wpdb $wpdb WordPress database abstraction object.
1100   *
1101   * @param string       $meta_type  Type of object metadata is for. Accepts 'post', 'comment', 'term', 'user',
1102   *                                 or any other object type with an associated meta table.
1103   * @param string|int[] $object_ids Array or comma delimited list of object IDs to update cache for.
1104   * @return array|false Metadata cache for the specified objects, or false on failure.
1105   */
1106  function update_meta_cache( $meta_type, $object_ids ) {
1107      global $wpdb;
1108  
1109      if ( ! $meta_type || ! $object_ids ) {
1110          return false;
1111      }
1112  
1113      $table = _get_meta_table( $meta_type );
1114      if ( ! $table ) {
1115          return false;
1116      }
1117  
1118      $column = sanitize_key( $meta_type . '_id' );
1119  
1120      if ( ! is_array( $object_ids ) ) {
1121          $object_ids = preg_replace( '|[^0-9,]|', '', $object_ids );
1122          $object_ids = explode( ',', $object_ids );
1123      }
1124  
1125      $object_ids = array_map( 'intval', $object_ids );
1126  
1127      /**
1128       * Short-circuits updating the metadata cache of a specific type.
1129       *
1130       * The dynamic portion of the hook name, `$meta_type`, refers to the meta object type
1131       * (post, comment, term, user, or any other type with an associated meta table).
1132       * Returning a non-null value will effectively short-circuit the function.
1133       *
1134       * Possible hook names include:
1135       *
1136       *  - `update_post_metadata_cache`
1137       *  - `update_comment_metadata_cache`
1138       *  - `update_term_metadata_cache`
1139       *  - `update_user_metadata_cache`
1140       *
1141       * @since 5.0.0
1142       *
1143       * @param mixed $check      Whether to allow updating the meta cache of the given type.
1144       * @param int[] $object_ids Array of object IDs to update the meta cache for.
1145       */
1146      $check = apply_filters( "update_{$meta_type}_metadata_cache", null, $object_ids );
1147      if ( null !== $check ) {
1148          return (bool) $check;
1149      }
1150  
1151      $cache_key      = $meta_type . '_meta';
1152      $non_cached_ids = array();
1153      $cache          = array();
1154      $cache_values   = wp_cache_get_multiple( $object_ids, $cache_key );
1155  
1156      foreach ( $cache_values as $id => $cached_object ) {
1157          if ( false === $cached_object ) {
1158              $non_cached_ids[] = $id;
1159          } else {
1160              $cache[ $id ] = $cached_object;
1161          }
1162      }
1163  
1164      if ( empty( $non_cached_ids ) ) {
1165          return $cache;
1166      }
1167  
1168      // Get meta info.
1169      $id_list   = implode( ',', $non_cached_ids );
1170      $id_column = ( 'user' === $meta_type ) ? 'umeta_id' : 'meta_id';
1171  
1172      $meta_list = $wpdb->get_results( "SELECT $column, meta_key, meta_value FROM $table WHERE $column IN ($id_list) ORDER BY $id_column ASC", ARRAY_A );
1173  
1174      if ( ! empty( $meta_list ) ) {
1175          foreach ( $meta_list as $metarow ) {
1176              $mpid = (int) $metarow[ $column ];
1177              $mkey = $metarow['meta_key'];
1178              $mval = $metarow['meta_value'];
1179  
1180              // Force subkeys to be array type.
1181              if ( ! isset( $cache[ $mpid ] ) || ! is_array( $cache[ $mpid ] ) ) {
1182                  $cache[ $mpid ] = array();
1183              }
1184              if ( ! isset( $cache[ $mpid ][ $mkey ] ) || ! is_array( $cache[ $mpid ][ $mkey ] ) ) {
1185                  $cache[ $mpid ][ $mkey ] = array();
1186              }
1187  
1188              // Add a value to the current pid/key.
1189              $cache[ $mpid ][ $mkey ][] = $mval;
1190          }
1191      }
1192  
1193      $data = array();
1194      foreach ( $non_cached_ids as $id ) {
1195          if ( ! isset( $cache[ $id ] ) ) {
1196              $cache[ $id ] = array();
1197          }
1198          $data[ $id ] = $cache[ $id ];
1199      }
1200      wp_cache_add_multiple( $data, $cache_key );
1201  
1202      return $cache;
1203  }
1204  
1205  /**
1206   * Retrieves the queue for lazy-loading metadata.
1207   *
1208   * @since 4.5.0
1209   *
1210   * @return WP_Metadata_Lazyloader Metadata lazyloader queue.
1211   */
1212  function wp_metadata_lazyloader() {
1213      static $wp_metadata_lazyloader;
1214  
1215      if ( null === $wp_metadata_lazyloader ) {
1216          $wp_metadata_lazyloader = new WP_Metadata_Lazyloader();
1217      }
1218  
1219      return $wp_metadata_lazyloader;
1220  }
1221  
1222  /**
1223   * Given a meta query, generates SQL clauses to be appended to a main query.
1224   *
1225   * @since 3.2.0
1226   *
1227   * @see WP_Meta_Query
1228   *
1229   * @param array  $meta_query        A meta query.
1230   * @param string $type              Type of meta.
1231   * @param string $primary_table     Primary database table name.
1232   * @param string $primary_id_column Primary ID column name.
1233   * @param object $context           Optional. The main query object
1234   * @return string[]|false {
1235   *     Array containing JOIN and WHERE SQL clauses to append to the main query,
1236   *     or false if no table exists for the requested meta type.
1237   *
1238   *     @type string $join  SQL fragment to append to the main JOIN clause.
1239   *     @type string $where SQL fragment to append to the main WHERE clause.
1240   * }
1241   */
1242  function get_meta_sql( $meta_query, $type, $primary_table, $primary_id_column, $context = null ) {
1243      $meta_query_obj = new WP_Meta_Query( $meta_query );
1244      return $meta_query_obj->get_sql( $type, $primary_table, $primary_id_column, $context );
1245  }
1246  
1247  /**
1248   * Retrieves the name of the metadata table for the specified object type.
1249   *
1250   * @since 2.9.0
1251   *
1252   * @global wpdb $wpdb WordPress database abstraction object.
1253   *
1254   * @param string $type Type of object metadata is for. Accepts 'post', 'comment', 'term', 'user',
1255   *                     or any other object type with an associated meta table.
1256   * @return string|false Metadata table name, or false if no metadata table exists
1257   */
1258  function _get_meta_table( $type ) {
1259      global $wpdb;
1260  
1261      $table_name = $type . 'meta';
1262  
1263      if ( empty( $wpdb->$table_name ) ) {
1264          return false;
1265      }
1266  
1267      return $wpdb->$table_name;
1268  }
1269  
1270  /**
1271   * Determines whether a meta key is considered protected.
1272   *
1273   * @since 3.1.3
1274   *
1275   * @param string $meta_key  Metadata key.
1276   * @param string $meta_type Optional. Type of object metadata is for. Accepts 'post', 'comment', 'term', 'user',
1277   *                          or any other object type with an associated meta table. Default empty.
1278   * @return bool Whether the meta key is considered protected.
1279   */
1280  function is_protected_meta( $meta_key, $meta_type = '' ) {
1281      $sanitized_key = preg_replace( "/[^\x20-\x7E\p{L}]/", '', $meta_key );
1282      $protected     = strlen( $sanitized_key ) > 0 && ( '_' === $sanitized_key[0] );
1283  
1284      /**
1285       * Filters whether a meta key is considered protected.
1286       *
1287       * @since 3.2.0
1288       *
1289       * @param bool   $protected Whether the key is considered protected.
1290       * @param string $meta_key  Metadata key.
1291       * @param string $meta_type Type of object metadata is for. Accepts 'post', 'comment', 'term', 'user',
1292       *                          or any other object type with an associated meta table.
1293       */
1294      return apply_filters( 'is_protected_meta', $protected, $meta_key, $meta_type );
1295  }
1296  
1297  /**
1298   * Sanitizes meta value.
1299   *
1300   * @since 3.1.3
1301   * @since 4.9.8 The `$object_subtype` parameter was added.
1302   *
1303   * @param string $meta_key       Metadata key.
1304   * @param mixed  $meta_value     Metadata value to sanitize.
1305   * @param string $object_type    Type of object metadata is for. Accepts 'post', 'comment', 'term', 'user',
1306   *                               or any other object type with an associated meta table.
1307   * @param string $object_subtype Optional. The subtype of the object type.
1308   * @return mixed Sanitized $meta_value.
1309   */
1310  function sanitize_meta( $meta_key, $meta_value, $object_type, $object_subtype = '' ) {
1311      if ( ! empty( $object_subtype ) && has_filter( "sanitize_{$object_type}_meta_{$meta_key}_for_{$object_subtype}" ) ) {
1312  
1313          /**
1314           * Filters the sanitization of a specific meta key of a specific meta type and subtype.
1315           *
1316           * The dynamic portions of the hook name, `$object_type`, `$meta_key`,
1317           * and `$object_subtype`, refer to the metadata object type (comment, post, term, or user),
1318           * the meta key value, and the object subtype respectively.
1319           *
1320           * @since 4.9.8
1321           *
1322           * @param mixed  $meta_value     Metadata value to sanitize.
1323           * @param string $meta_key       Metadata key.
1324           * @param string $object_type    Type of object metadata is for. Accepts 'post', 'comment', 'term', 'user',
1325           *                               or any other object type with an associated meta table.
1326           * @param string $object_subtype Object subtype.
1327           */
1328          return apply_filters( "sanitize_{$object_type}_meta_{$meta_key}_for_{$object_subtype}", $meta_value, $meta_key, $object_type, $object_subtype );
1329      }
1330  
1331      /**
1332       * Filters the sanitization of a specific meta key of a specific meta type.
1333       *
1334       * The dynamic portions of the hook name, `$meta_type`, and `$meta_key`,
1335       * refer to the metadata object type (comment, post, term, or user) and the meta
1336       * key value, respectively.
1337       *
1338       * @since 3.3.0
1339       *
1340       * @param mixed  $meta_value  Metadata value to sanitize.
1341       * @param string $meta_key    Metadata key.
1342       * @param string $object_type Type of object metadata is for. Accepts 'post', 'comment', 'term', 'user',
1343       *                            or any other object type with an associated meta table.
1344       */
1345      return apply_filters( "sanitize_{$object_type}_meta_{$meta_key}", $meta_value, $meta_key, $object_type );
1346  }
1347  
1348  /**
1349   * Registers a meta key.
1350   *
1351   * It is recommended to register meta keys for a specific combination of object type and object subtype. If passing
1352   * an object subtype is omitted, the meta key will be registered for the entire object type, however it can be partly
1353   * overridden in case a more specific meta key of the same name exists for the same object type and a subtype.
1354   *
1355   * If an object type does not support any subtypes, such as users or comments, you should commonly call this function
1356   * without passing a subtype.
1357   *
1358   * @since 3.3.0
1359   * @since 4.6.0 {@link https://core.trac.wordpress.org/ticket/35658 Modified
1360   *              to support an array of data to attach to registered meta keys}. Previous arguments for
1361   *              `$sanitize_callback` and `$auth_callback` have been folded into this array.
1362   * @since 4.9.8 The `$object_subtype` argument was added to the arguments array.
1363   * @since 5.3.0 Valid meta types expanded to include "array" and "object".
1364   * @since 5.5.0 The `$default` argument was added to the arguments array.
1365   *
1366   * @param string       $object_type Type of object metadata is for. Accepts 'post', 'comment', 'term', 'user',
1367   *                                  or any other object type with an associated meta table.
1368   * @param string       $meta_key    Meta key to register.
1369   * @param array        $args {
1370   *     Data used to describe the meta key when registered.
1371   *
1372   *     @type string     $object_subtype    A subtype; e.g. if the object type is "post", the post type. If left empty,
1373   *                                         the meta key will be registered on the entire object type. Default empty.
1374   *     @type string     $type              The type of data associated with this meta key.
1375   *                                         Valid values are 'string', 'boolean', 'integer', 'number', 'array', and 'object'.
1376   *     @type string     $description       A description of the data attached to this meta key.
1377   *     @type bool       $single            Whether the meta key has one value per object, or an array of values per object.
1378   *     @type mixed      $default           The default value returned from get_metadata() if no value has been set yet.
1379   *                                         When using a non-single meta key, the default value is for the first entry.
1380   *                                         In other words, when calling get_metadata() with `$single` set to `false`,
1381   *                                         the default value given here will be wrapped in an array.
1382   *     @type callable   $sanitize_callback A function or method to call when sanitizing `$meta_key` data.
1383   *     @type callable   $auth_callback     Optional. A function or method to call when performing edit_post_meta,
1384   *                                         add_post_meta, and delete_post_meta capability checks.
1385   *     @type bool|array $show_in_rest      Whether data associated with this meta key can be considered public and
1386   *                                         should be accessible via the REST API. A custom post type must also declare
1387   *                                         support for custom fields for registered meta to be accessible via REST.
1388   *                                         When registering complex meta values this argument may optionally be an
1389   *                                         array with 'schema' or 'prepare_callback' keys instead of a boolean.
1390   * }
1391   * @param string|array $deprecated Deprecated. Use `$args` instead.
1392   * @return bool True if the meta key was successfully registered in the global array, false if not.
1393   *              Registering a meta key with distinct sanitize and auth callbacks will fire those callbacks,
1394   *              but will not add to the global registry.
1395   */
1396  function register_meta( $object_type, $meta_key, $args, $deprecated = null ) {
1397      global $wp_meta_keys;
1398  
1399      if ( ! is_array( $wp_meta_keys ) ) {
1400          $wp_meta_keys = array();
1401      }
1402  
1403      $defaults = array(
1404          'object_subtype'    => '',
1405          'type'              => 'string',
1406          'description'       => '',
1407          'default'           => '',
1408          'single'            => false,
1409          'sanitize_callback' => null,
1410          'auth_callback'     => null,
1411          'show_in_rest'      => false,
1412      );
1413  
1414      // There used to be individual args for sanitize and auth callbacks.
1415      $has_old_sanitize_cb = false;
1416      $has_old_auth_cb     = false;
1417  
1418      if ( is_callable( $args ) ) {
1419          $args = array(
1420              'sanitize_callback' => $args,
1421          );
1422  
1423          $has_old_sanitize_cb = true;
1424      } else {
1425          $args = (array) $args;
1426      }
1427  
1428      if ( is_callable( $deprecated ) ) {
1429          $args['auth_callback'] = $deprecated;
1430          $has_old_auth_cb       = true;
1431      }
1432  
1433      /**
1434       * Filters the registration arguments when registering meta.
1435       *
1436       * @since 4.6.0
1437       *
1438       * @param array  $args        Array of meta registration arguments.
1439       * @param array  $defaults    Array of default arguments.
1440       * @param string $object_type Type of object metadata is for. Accepts 'post', 'comment', 'term', 'user',
1441       *                            or any other object type with an associated meta table.
1442       * @param string $meta_key    Meta key.
1443       */
1444      $args = apply_filters( 'register_meta_args', $args, $defaults, $object_type, $meta_key );
1445      unset( $defaults['default'] );
1446      $args = wp_parse_args( $args, $defaults );
1447  
1448      // Require an item schema when registering array meta.
1449      if ( false !== $args['show_in_rest'] && 'array' === $args['type'] ) {
1450          if ( ! is_array( $args['show_in_rest'] ) || ! isset( $args['show_in_rest']['schema']['items'] ) ) {
1451              _doing_it_wrong( __FUNCTION__, __( 'When registering an "array" meta type to show in the REST API, you must specify the schema for each array item in "show_in_rest.schema.items".' ), '5.3.0' );
1452  
1453              return false;
1454          }
1455      }
1456  
1457      $object_subtype = ! empty( $args['object_subtype'] ) ? $args['object_subtype'] : '';
1458  
1459      // If `auth_callback` is not provided, fall back to `is_protected_meta()`.
1460      if ( empty( $args['auth_callback'] ) ) {
1461          if ( is_protected_meta( $meta_key, $object_type ) ) {
1462              $args['auth_callback'] = '__return_false';
1463          } else {
1464              $args['auth_callback'] = '__return_true';
1465          }
1466      }
1467  
1468      // Back-compat: old sanitize and auth callbacks are applied to all of an object type.
1469      if ( is_callable( $args['sanitize_callback'] ) ) {
1470          if ( ! empty( $object_subtype ) ) {
1471              add_filter( "sanitize_{$object_type}_meta_{$meta_key}_for_{$object_subtype}", $args['sanitize_callback'], 10, 4 );
1472          } else {
1473              add_filter( "sanitize_{$object_type}_meta_{$meta_key}", $args['sanitize_callback'], 10, 3 );
1474          }
1475      }
1476  
1477      if ( is_callable( $args['auth_callback'] ) ) {
1478          if ( ! empty( $object_subtype ) ) {
1479              add_filter( "auth_{$object_type}_meta_{$meta_key}_for_{$object_subtype}", $args['auth_callback'], 10, 6 );
1480          } else {
1481              add_filter( "auth_{$object_type}_meta_{$meta_key}", $args['auth_callback'], 10, 6 );
1482          }
1483      }
1484  
1485      if ( array_key_exists( 'default', $args ) ) {
1486          $schema = $args;
1487          if ( is_array( $args['show_in_rest'] ) && isset( $args['show_in_rest']['schema'] ) ) {
1488              $schema = array_merge( $schema, $args['show_in_rest']['schema'] );
1489          }
1490  
1491          $check = rest_validate_value_from_schema( $args['default'], $schema );
1492          if ( is_wp_error( $check ) ) {
1493              _doing_it_wrong( __FUNCTION__, __( 'When registering a default meta value the data must match the type provided.' ), '5.5.0' );
1494  
1495              return false;
1496          }
1497  
1498          if ( ! has_filter( "default_{$object_type}_metadata", 'filter_default_metadata' ) ) {
1499              add_filter( "default_{$object_type}_metadata", 'filter_default_metadata', 10, 5 );
1500          }
1501      }
1502  
1503      // Global registry only contains meta keys registered with the array of arguments added in 4.6.0.
1504      if ( ! $has_old_auth_cb && ! $has_old_sanitize_cb ) {
1505          unset( $args['object_subtype'] );
1506  
1507          $wp_meta_keys[ $object_type ][ $object_subtype ][ $meta_key ] = $args;
1508  
1509          return true;
1510      }
1511  
1512      return false;
1513  }
1514  
1515  /**
1516   * Filters into default_{$object_type}_metadata and adds in default value.
1517   *
1518   * @since 5.5.0
1519   *
1520   * @param mixed  $value     Current value passed to filter.
1521   * @param int    $object_id ID of the object metadata is for.
1522   * @param string $meta_key  Metadata key.
1523   * @param bool   $single    If true, return only the first value of the specified `$meta_key`.
1524   *                          This parameter has no effect if `$meta_key` is not specified.
1525   * @param string $meta_type Type of object metadata is for. Accepts 'post', 'comment', 'term', 'user',
1526   *                          or any other object type with an associated meta table.
1527   * @return mixed An array of default values if `$single` is false.
1528   *               The default value of the meta field if `$single` is true.
1529   */
1530  function filter_default_metadata( $value, $object_id, $meta_key, $single, $meta_type ) {
1531      global $wp_meta_keys;
1532  
1533      if ( wp_installing() ) {
1534          return $value;
1535      }
1536  
1537      if ( ! is_array( $wp_meta_keys ) || ! isset( $wp_meta_keys[ $meta_type ] ) ) {
1538          return $value;
1539      }
1540  
1541      $defaults = array();
1542      foreach ( $wp_meta_keys[ $meta_type ] as $sub_type => $meta_data ) {
1543          foreach ( $meta_data as $_meta_key => $args ) {
1544              if ( $_meta_key === $meta_key && array_key_exists( 'default', $args ) ) {
1545                  $defaults[ $sub_type ] = $args;
1546              }
1547          }
1548      }
1549  
1550      if ( ! $defaults ) {
1551          return $value;
1552      }
1553  
1554      // If this meta type does not have subtypes, then the default is keyed as an empty string.
1555      if ( isset( $defaults[''] ) ) {
1556          $metadata = $defaults[''];
1557      } else {
1558          $sub_type = get_object_subtype( $meta_type, $object_id );
1559          if ( ! isset( $defaults[ $sub_type ] ) ) {
1560              return $value;
1561          }
1562          $metadata = $defaults[ $sub_type ];
1563      }
1564  
1565      if ( $single ) {
1566          $value = $metadata['default'];
1567      } else {
1568          $value = array( $metadata['default'] );
1569      }
1570  
1571      return $value;
1572  }
1573  
1574  /**
1575   * Checks if a meta key is registered.
1576   *
1577   * @since 4.6.0
1578   * @since 4.9.8 The `$object_subtype` parameter was added.
1579   *
1580   * @param string $object_type    Type of object metadata is for. Accepts 'post', 'comment', 'term', 'user',
1581   *                               or any other object type with an associated meta table.
1582   * @param string $meta_key       Metadata key.
1583   * @param string $object_subtype Optional. The subtype of the object type.
1584   * @return bool True if the meta key is registered to the object type and, if provided,
1585   *              the object subtype. False if not.
1586   */
1587  function registered_meta_key_exists( $object_type, $meta_key, $object_subtype = '' ) {
1588      $meta_keys = get_registered_meta_keys( $object_type, $object_subtype );
1589  
1590      return isset( $meta_keys[ $meta_key ] );
1591  }
1592  
1593  /**
1594   * Unregisters a meta key from the list of registered keys.
1595   *
1596   * @since 4.6.0
1597   * @since 4.9.8 The `$object_subtype` parameter was added.
1598   *
1599   * @param string $object_type    Type of object metadata is for. Accepts 'post', 'comment', 'term', 'user',
1600   *                               or any other object type with an associated meta table.
1601   * @param string $meta_key       Metadata key.
1602   * @param string $object_subtype Optional. The subtype of the object type.
1603   * @return bool True if successful. False if the meta key was not registered.
1604   */
1605  function unregister_meta_key( $object_type, $meta_key, $object_subtype = '' ) {
1606      global $wp_meta_keys;
1607  
1608      if ( ! registered_meta_key_exists( $object_type, $meta_key, $object_subtype ) ) {
1609          return false;
1610      }
1611  
1612      $args = $wp_meta_keys[ $object_type ][ $object_subtype ][ $meta_key ];
1613  
1614      if ( isset( $args['sanitize_callback'] ) && is_callable( $args['sanitize_callback'] ) ) {
1615          if ( ! empty( $object_subtype ) ) {
1616              remove_filter( "sanitize_{$object_type}_meta_{$meta_key}_for_{$object_subtype}", $args['sanitize_callback'] );
1617          } else {
1618              remove_filter( "sanitize_{$object_type}_meta_{$meta_key}", $args['sanitize_callback'] );
1619          }
1620      }
1621  
1622      if ( isset( $args['auth_callback'] ) && is_callable( $args['auth_callback'] ) ) {
1623          if ( ! empty( $object_subtype ) ) {
1624              remove_filter( "auth_{$object_type}_meta_{$meta_key}_for_{$object_subtype}", $args['auth_callback'] );
1625          } else {
1626              remove_filter( "auth_{$object_type}_meta_{$meta_key}", $args['auth_callback'] );
1627          }
1628      }
1629  
1630      unset( $wp_meta_keys[ $object_type ][ $object_subtype ][ $meta_key ] );
1631  
1632      // Do some clean up.
1633      if ( empty( $wp_meta_keys[ $object_type ][ $object_subtype ] ) ) {
1634          unset( $wp_meta_keys[ $object_type ][ $object_subtype ] );
1635      }
1636      if ( empty( $wp_meta_keys[ $object_type ] ) ) {
1637          unset( $wp_meta_keys[ $object_type ] );
1638      }
1639  
1640      return true;
1641  }
1642  
1643  /**
1644   * Retrieves a list of registered metadata args for an object type, keyed by their meta keys.
1645   *
1646   * @since 4.6.0
1647   * @since 4.9.8 The `$object_subtype` parameter was added.
1648   *
1649   * @param string $object_type    Type of object metadata is for. Accepts 'post', 'comment', 'term', 'user',
1650   *                               or any other object type with an associated meta table.
1651   * @param string $object_subtype Optional. The subtype of the object type.
1652   * @return array[] List of registered metadata args, keyed by their meta keys.
1653   */
1654  function get_registered_meta_keys( $object_type, $object_subtype = '' ) {
1655      global $wp_meta_keys;
1656  
1657      if ( ! is_array( $wp_meta_keys ) || ! isset( $wp_meta_keys[ $object_type ] ) || ! isset( $wp_meta_keys[ $object_type ][ $object_subtype ] ) ) {
1658          return array();
1659      }
1660  
1661      return $wp_meta_keys[ $object_type ][ $object_subtype ];
1662  }
1663  
1664  /**
1665   * Retrieves registered metadata for a specified object.
1666   *
1667   * The results include both meta that is registered specifically for the
1668   * object's subtype and meta that is registered for the entire object type.
1669   *
1670   * @since 4.6.0
1671   *
1672   * @param string $object_type Type of object metadata is for. Accepts 'post', 'comment', 'term', 'user',
1673   *                            or any other object type with an associated meta table.
1674   * @param int    $object_id   ID of the object the metadata is for.
1675   * @param string $meta_key    Optional. Registered metadata key. If not specified, retrieve all registered
1676   *                            metadata for the specified object.
1677   * @return mixed A single value or array of values for a key if specified. An array of all registered keys
1678   *               and values for an object ID if not. False if a given $meta_key is not registered.
1679   */
1680  function get_registered_metadata( $object_type, $object_id, $meta_key = '' ) {
1681      $object_subtype = get_object_subtype( $object_type, $object_id );
1682  
1683      if ( ! empty( $meta_key ) ) {
1684          if ( ! empty( $object_subtype ) && ! registered_meta_key_exists( $object_type, $meta_key, $object_subtype ) ) {
1685              $object_subtype = '';
1686          }
1687  
1688          if ( ! registered_meta_key_exists( $object_type, $meta_key, $object_subtype ) ) {
1689              return false;
1690          }
1691  
1692          $meta_keys     = get_registered_meta_keys( $object_type, $object_subtype );
1693          $meta_key_data = $meta_keys[ $meta_key ];
1694  
1695          $data = get_metadata( $object_type, $object_id, $meta_key, $meta_key_data['single'] );
1696  
1697          return $data;
1698      }
1699  
1700      $data = get_metadata( $object_type, $object_id );
1701      if ( ! $data ) {
1702          return array();
1703      }
1704  
1705      $meta_keys = get_registered_meta_keys( $object_type );
1706      if ( ! empty( $object_subtype ) ) {
1707          $meta_keys = array_merge( $meta_keys, get_registered_meta_keys( $object_type, $object_subtype ) );
1708      }
1709  
1710      return array_intersect_key( $data, $meta_keys );
1711  }
1712  
1713  /**
1714   * Filters out `register_meta()` args based on an allowed list.
1715   *
1716   * `register_meta()` args may change over time, so requiring the allowed list
1717   * to be explicitly turned off is a warranty seal of sorts.
1718   *
1719   * @access private
1720   * @since 5.5.0
1721   *
1722   * @param array $args         Arguments from `register_meta()`.
1723   * @param array $default_args Default arguments for `register_meta()`.
1724   * @return array Filtered arguments.
1725   */
1726  function _wp_register_meta_args_allowed_list( $args, $default_args ) {
1727      return array_intersect_key( $args, $default_args );
1728  }
1729  
1730  /**
1731   * Returns the object subtype for a given object ID of a specific type.
1732   *
1733   * @since 4.9.8
1734   *
1735   * @param string $object_type Type of object metadata is for. Accepts 'post', 'comment', 'term', 'user',
1736   *                            or any other object type with an associated meta table.
1737   * @param int    $object_id   ID of the object to retrieve its subtype.
1738   * @return string The object subtype or an empty string if unspecified subtype.
1739   */
1740  function get_object_subtype( $object_type, $object_id ) {
1741      $object_id      = (int) $object_id;
1742      $object_subtype = '';
1743  
1744      switch ( $object_type ) {
1745          case 'post':
1746              $post_type = get_post_type( $object_id );
1747  
1748              if ( ! empty( $post_type ) ) {
1749                  $object_subtype = $post_type;
1750              }
1751              break;
1752  
1753          case 'term':
1754              $term = get_term( $object_id );
1755              if ( ! $term instanceof WP_Term ) {
1756                  break;
1757              }
1758  
1759              $object_subtype = $term->taxonomy;
1760              break;
1761  
1762          case 'comment':
1763              $comment = get_comment( $object_id );
1764              if ( ! $comment ) {
1765                  break;
1766              }
1767  
1768              $object_subtype = 'comment';
1769              break;
1770  
1771          case 'user':
1772              $user = get_user_by( 'id', $object_id );
1773              if ( ! $user ) {
1774                  break;
1775              }
1776  
1777              $object_subtype = 'user';
1778              break;
1779      }
1780  
1781      /**
1782       * Filters the object subtype identifier for a non-standard object type.
1783       *
1784       * The dynamic portion of the hook name, `$object_type`, refers to the meta object type
1785       * (post, comment, term, user, or any other type with an associated meta table).
1786       *
1787       * Possible hook names include:
1788       *
1789       *  - `get_object_subtype_post`
1790       *  - `get_object_subtype_comment`
1791       *  - `get_object_subtype_term`
1792       *  - `get_object_subtype_user`
1793       *
1794       * @since 4.9.8
1795       *
1796       * @param string $object_subtype Empty string to override.
1797       * @param int    $object_id      ID of the object to get the subtype for.
1798       */
1799      return apply_filters( "get_object_subtype_{$object_type}", $object_subtype, $object_id );
1800  }


Generated : Fri Aug 19 08:20:02 2022 Cross-referenced by PHPXref