[ Index ]

PHP Cross Reference of WordPress

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


Generated: Thu Jul 9 01:00:03 2020 Cross-referenced by PHPXref 0.7.1