[ 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 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. Serialized if non-scalar.
 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. Serialized if non-scalar.
 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. Serialized if non-scalar.
 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. Serialized if non-scalar.
 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. Serialized if non-scalar.
 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          foreach ( (array) $object_ids as $o_id ) {
 500              wp_cache_delete( $o_id, $meta_type . '_meta' );
 501          }
 502      } else {
 503          wp_cache_delete( $object_id, $meta_type . '_meta' );
 504      }
 505  
 506      /**
 507       * Fires immediately after deleting metadata of a specific type.
 508       *
 509       * The dynamic portion of the hook name, `$meta_type`, refers to the meta object type
 510       * (post, comment, term, user, or any other type with an associated meta table).
 511       *
 512       * Possible hook names include:
 513       *
 514       *  - `deleted_post_meta`
 515       *  - `deleted_comment_meta`
 516       *  - `deleted_term_meta`
 517       *  - `deleted_user_meta`
 518       *
 519       * @since 2.9.0
 520       *
 521       * @param string[] $meta_ids    An array of metadata entry IDs to delete.
 522       * @param int      $object_id   ID of the object metadata is for.
 523       * @param string   $meta_key    Metadata key.
 524       * @param mixed    $_meta_value Metadata value. Serialized if non-scalar.
 525       */
 526      do_action( "deleted_{$meta_type}_meta", $meta_ids, $object_id, $meta_key, $_meta_value );
 527  
 528      // Old-style action.
 529      if ( 'post' === $meta_type ) {
 530          /**
 531           * Fires immediately after deleting metadata for a post.
 532           *
 533           * @since 2.9.0
 534           *
 535           * @param string[] $meta_ids An array of metadata entry IDs to delete.
 536           */
 537          do_action( 'deleted_postmeta', $meta_ids );
 538      }
 539  
 540      return true;
 541  }
 542  
 543  /**
 544   * Retrieves the value of a metadata field for the specified object type and ID.
 545   *
 546   * If the meta field exists, a single value is returned if `$single` is true,
 547   * or an array of values if it's false.
 548   *
 549   * If the meta field does not exist, the result depends on get_metadata_default().
 550   * By default, an empty string is returned if `$single` is true, or an empty array
 551   * if it's false.
 552   *
 553   * @since 2.9.0
 554   *
 555   * @see get_metadata_raw()
 556   * @see get_metadata_default()
 557   *
 558   * @param string $meta_type Type of object metadata is for. Accepts 'post', 'comment', 'term', 'user',
 559   *                          or any other object type with an associated meta table.
 560   * @param int    $object_id ID of the object metadata is for.
 561   * @param string $meta_key  Optional. Metadata key. If not specified, retrieve all metadata for
 562   *                          the specified object. Default empty.
 563   * @param bool   $single    Optional. If true, return only the first value of the specified `$meta_key`.
 564   *                          This parameter has no effect if `$meta_key` is not specified. Default false.
 565   * @return mixed An array of values if `$single` is false.
 566   *               The value of the meta field if `$single` is true.
 567   *               False for an invalid `$object_id` (non-numeric, zero, or negative value),
 568   *               or if `$meta_type` is not specified.
 569   *               An empty string if a valid but non-existing object ID is passed.
 570   */
 571  function get_metadata( $meta_type, $object_id, $meta_key = '', $single = false ) {
 572      $value = get_metadata_raw( $meta_type, $object_id, $meta_key, $single );
 573      if ( ! is_null( $value ) ) {
 574          return $value;
 575      }
 576  
 577      return get_metadata_default( $meta_type, $object_id, $meta_key, $single );
 578  }
 579  
 580  /**
 581   * Retrieves raw metadata value for the specified object.
 582   *
 583   * @since 5.5.0
 584   *
 585   * @param string $meta_type Type of object metadata is for. Accepts 'post', 'comment', 'term', 'user',
 586   *                          or any other object type with an associated meta table.
 587   * @param int    $object_id ID of the object metadata is for.
 588   * @param string $meta_key  Optional. Metadata key. If not specified, retrieve all metadata for
 589   *                          the specified object. Default empty.
 590   * @param bool   $single    Optional. If true, return only the first value of the specified `$meta_key`.
 591   *                          This parameter has no effect if `$meta_key` is not specified. Default false.
 592   * @return mixed An array of values if `$single` is false.
 593   *               The value of the meta field if `$single` is true.
 594   *               False for an invalid `$object_id` (non-numeric, zero, or negative value),
 595   *               or if `$meta_type` is not specified.
 596   *               Null if the value does not exist.
 597   */
 598  function get_metadata_raw( $meta_type, $object_id, $meta_key = '', $single = false ) {
 599      if ( ! $meta_type || ! is_numeric( $object_id ) ) {
 600          return false;
 601      }
 602  
 603      $object_id = absint( $object_id );
 604      if ( ! $object_id ) {
 605          return false;
 606      }
 607  
 608      /**
 609       * Short-circuits the return value of a meta field.
 610       *
 611       * The dynamic portion of the hook name, `$meta_type`, refers to the meta object type
 612       * (post, comment, term, user, or any other type with an associated meta table).
 613       * Returning a non-null value will effectively short-circuit the function.
 614       *
 615       * Possible filter names include:
 616       *
 617       *  - `get_post_metadata`
 618       *  - `get_comment_metadata`
 619       *  - `get_term_metadata`
 620       *  - `get_user_metadata`
 621       *
 622       * @since 3.1.0
 623       * @since 5.5.0 Added the `$meta_type` parameter.
 624       *
 625       * @param mixed  $value     The value to return, either a single metadata value or an array
 626       *                          of values depending on the value of `$single`. Default null.
 627       * @param int    $object_id ID of the object metadata is for.
 628       * @param string $meta_key  Metadata key.
 629       * @param bool   $single    Whether to return only the first value of the specified `$meta_key`.
 630       * @param string $meta_type Type of object metadata is for. Accepts 'post', 'comment', 'term', 'user',
 631       *                          or any other object type with an associated meta table.
 632       */
 633      $check = apply_filters( "get_{$meta_type}_metadata", null, $object_id, $meta_key, $single, $meta_type );
 634      if ( null !== $check ) {
 635          if ( $single && is_array( $check ) ) {
 636              return $check[0];
 637          } else {
 638              return $check;
 639          }
 640      }
 641  
 642      $meta_cache = wp_cache_get( $object_id, $meta_type . '_meta' );
 643  
 644      if ( ! $meta_cache ) {
 645          $meta_cache = update_meta_cache( $meta_type, array( $object_id ) );
 646          if ( isset( $meta_cache[ $object_id ] ) ) {
 647              $meta_cache = $meta_cache[ $object_id ];
 648          } else {
 649              $meta_cache = null;
 650          }
 651      }
 652  
 653      if ( ! $meta_key ) {
 654          return $meta_cache;
 655      }
 656  
 657      if ( isset( $meta_cache[ $meta_key ] ) ) {
 658          if ( $single ) {
 659              return maybe_unserialize( $meta_cache[ $meta_key ][0] );
 660          } else {
 661              return array_map( 'maybe_unserialize', $meta_cache[ $meta_key ] );
 662          }
 663      }
 664  
 665      return null;
 666  }
 667  
 668  /**
 669   * Retrieves default metadata value for the specified meta key and object.
 670   *
 671   * By default, an empty string is returned if `$single` is true, or an empty array
 672   * if it's false.
 673   *
 674   * @since 5.5.0
 675   *
 676   * @param string $meta_type Type of object metadata is for. Accepts 'post', 'comment', 'term', 'user',
 677   *                          or any other object type with an associated meta table.
 678   * @param int    $object_id ID of the object metadata is for.
 679   * @param string $meta_key  Metadata key.
 680   * @param bool   $single    Optional. If true, return only the first value of the specified `$meta_key`.
 681   *                          This parameter has no effect if `$meta_key` is not specified. Default false.
 682   * @return mixed An array of default values if `$single` is false.
 683   *               The default value of the meta field if `$single` is true.
 684   */
 685  function get_metadata_default( $meta_type, $object_id, $meta_key, $single = false ) {
 686      if ( $single ) {
 687          $value = '';
 688      } else {
 689          $value = array();
 690      }
 691  
 692      /**
 693       * Filters the default metadata value for a specified meta key and object.
 694       *
 695       * The dynamic portion of the hook name, `$meta_type`, refers to the meta object type
 696       * (post, comment, term, user, or any other type with an associated meta table).
 697       *
 698       * Possible filter names include:
 699       *
 700       *  - `default_post_metadata`
 701       *  - `default_comment_metadata`
 702       *  - `default_term_metadata`
 703       *  - `default_user_metadata`
 704       *
 705       * @since 5.5.0
 706       *
 707       * @param mixed  $value     The value to return, either a single metadata value or an array
 708       *                          of values depending on the value of `$single`.
 709       * @param int    $object_id ID of the object metadata is for.
 710       * @param string $meta_key  Metadata key.
 711       * @param bool   $single    Whether to return only the first value of the specified `$meta_key`.
 712       * @param string $meta_type Type of object metadata is for. Accepts 'post', 'comment', 'term', 'user',
 713       *                          or any other object type with an associated meta table.
 714       */
 715      $value = apply_filters( "default_{$meta_type}_metadata", $value, $object_id, $meta_key, $single, $meta_type );
 716  
 717      if ( ! $single && ! wp_is_numeric_array( $value ) ) {
 718          $value = array( $value );
 719      }
 720  
 721      return $value;
 722  }
 723  
 724  /**
 725   * Determines if a meta field with the given key exists for the given object ID.
 726   *
 727   * @since 3.3.0
 728   *
 729   * @param string $meta_type Type of object metadata is for. Accepts 'post', 'comment', 'term', 'user',
 730   *                          or any other object type with an associated meta table.
 731   * @param int    $object_id ID of the object metadata is for.
 732   * @param string $meta_key  Metadata key.
 733   * @return bool Whether a meta field with the given key exists.
 734   */
 735  function metadata_exists( $meta_type, $object_id, $meta_key ) {
 736      if ( ! $meta_type || ! is_numeric( $object_id ) ) {
 737          return false;
 738      }
 739  
 740      $object_id = absint( $object_id );
 741      if ( ! $object_id ) {
 742          return false;
 743      }
 744  
 745      /** This filter is documented in wp-includes/meta.php */
 746      $check = apply_filters( "get_{$meta_type}_metadata", null, $object_id, $meta_key, true, $meta_type );
 747      if ( null !== $check ) {
 748          return (bool) $check;
 749      }
 750  
 751      $meta_cache = wp_cache_get( $object_id, $meta_type . '_meta' );
 752  
 753      if ( ! $meta_cache ) {
 754          $meta_cache = update_meta_cache( $meta_type, array( $object_id ) );
 755          $meta_cache = $meta_cache[ $object_id ];
 756      }
 757  
 758      if ( isset( $meta_cache[ $meta_key ] ) ) {
 759          return true;
 760      }
 761  
 762      return false;
 763  }
 764  
 765  /**
 766   * Retrieves metadata by meta ID.
 767   *
 768   * @since 3.3.0
 769   *
 770   * @global wpdb $wpdb WordPress database abstraction object.
 771   *
 772   * @param string $meta_type Type of object metadata is for. Accepts 'post', 'comment', 'term', 'user',
 773   *                          or any other object type with an associated meta table.
 774   * @param int    $meta_id   ID for a specific meta row.
 775   * @return stdClass|false {
 776   *     Metadata object, or boolean `false` if the metadata doesn't exist.
 777   *
 778   *     @type string $meta_key   The meta key.
 779   *     @type mixed  $meta_value The unserialized meta value.
 780   *     @type string $meta_id    Optional. The meta ID when the meta type is any value except 'user'.
 781   *     @type string $umeta_id   Optional. The meta ID when the meta type is 'user'.
 782   *     @type string $post_id    Optional. The object ID when the meta type is 'post'.
 783   *     @type string $comment_id Optional. The object ID when the meta type is 'comment'.
 784   *     @type string $term_id    Optional. The object ID when the meta type is 'term'.
 785   *     @type string $user_id    Optional. The object ID when the meta type is 'user'.
 786   * }
 787   */
 788  function get_metadata_by_mid( $meta_type, $meta_id ) {
 789      global $wpdb;
 790  
 791      if ( ! $meta_type || ! is_numeric( $meta_id ) || floor( $meta_id ) != $meta_id ) {
 792          return false;
 793      }
 794  
 795      $meta_id = (int) $meta_id;
 796      if ( $meta_id <= 0 ) {
 797          return false;
 798      }
 799  
 800      $table = _get_meta_table( $meta_type );
 801      if ( ! $table ) {
 802          return false;
 803      }
 804  
 805      /**
 806       * Short-circuits the return value when fetching a meta field by meta ID.
 807       *
 808       * The dynamic portion of the hook name, `$meta_type`, refers to the meta object type
 809       * (post, comment, term, user, or any other type with an associated meta table).
 810       * Returning a non-null value will effectively short-circuit the function.
 811       *
 812       * Possible hook names include:
 813       *
 814       *  - `get_post_metadata_by_mid`
 815       *  - `get_comment_metadata_by_mid`
 816       *  - `get_term_metadata_by_mid`
 817       *  - `get_user_metadata_by_mid`
 818       *
 819       * @since 5.0.0
 820       *
 821       * @param stdClass|null $value   The value to return.
 822       * @param int           $meta_id Meta ID.
 823       */
 824      $check = apply_filters( "get_{$meta_type}_metadata_by_mid", null, $meta_id );
 825      if ( null !== $check ) {
 826          return $check;
 827      }
 828  
 829      $id_column = ( 'user' === $meta_type ) ? 'umeta_id' : 'meta_id';
 830  
 831      $meta = $wpdb->get_row( $wpdb->prepare( "SELECT * FROM $table WHERE $id_column = %d", $meta_id ) );
 832  
 833      if ( empty( $meta ) ) {
 834          return false;
 835      }
 836  
 837      if ( isset( $meta->meta_value ) ) {
 838          $meta->meta_value = maybe_unserialize( $meta->meta_value );
 839      }
 840  
 841      return $meta;
 842  }
 843  
 844  /**
 845   * Updates metadata by meta ID.
 846   *
 847   * @since 3.3.0
 848   *
 849   * @global wpdb $wpdb WordPress database abstraction object.
 850   *
 851   * @param string       $meta_type  Type of object metadata is for. Accepts 'post', 'comment', 'term', 'user',
 852   *                                 or any other object type with an associated meta table.
 853   * @param int          $meta_id    ID for a specific meta row.
 854   * @param string       $meta_value Metadata value. Must be serializable if non-scalar.
 855   * @param string|false $meta_key   Optional. You can provide a meta key to update it. Default false.
 856   * @return bool True on successful update, false on failure.
 857   */
 858  function update_metadata_by_mid( $meta_type, $meta_id, $meta_value, $meta_key = false ) {
 859      global $wpdb;
 860  
 861      // Make sure everything is valid.
 862      if ( ! $meta_type || ! is_numeric( $meta_id ) || floor( $meta_id ) != $meta_id ) {
 863          return false;
 864      }
 865  
 866      $meta_id = (int) $meta_id;
 867      if ( $meta_id <= 0 ) {
 868          return false;
 869      }
 870  
 871      $table = _get_meta_table( $meta_type );
 872      if ( ! $table ) {
 873          return false;
 874      }
 875  
 876      $column    = sanitize_key( $meta_type . '_id' );
 877      $id_column = ( 'user' === $meta_type ) ? 'umeta_id' : 'meta_id';
 878  
 879      /**
 880       * Short-circuits updating metadata of a specific type by meta ID.
 881       *
 882       * The dynamic portion of the hook name, `$meta_type`, refers to the meta object type
 883       * (post, comment, term, user, or any other type with an associated meta table).
 884       * Returning a non-null value will effectively short-circuit the function.
 885       *
 886       * Possible hook names include:
 887       *
 888       *  - `update_post_metadata_by_mid`
 889       *  - `update_comment_metadata_by_mid`
 890       *  - `update_term_metadata_by_mid`
 891       *  - `update_user_metadata_by_mid`
 892       *
 893       * @since 5.0.0
 894       *
 895       * @param null|bool    $check      Whether to allow updating metadata for the given type.
 896       * @param int          $meta_id    Meta ID.
 897       * @param mixed        $meta_value Meta value. Must be serializable if non-scalar.
 898       * @param string|false $meta_key   Meta key, if provided.
 899       */
 900      $check = apply_filters( "update_{$meta_type}_metadata_by_mid", null, $meta_id, $meta_value, $meta_key );
 901      if ( null !== $check ) {
 902          return (bool) $check;
 903      }
 904  
 905      // Fetch the meta and go on if it's found.
 906      $meta = get_metadata_by_mid( $meta_type, $meta_id );
 907      if ( $meta ) {
 908          $original_key = $meta->meta_key;
 909          $object_id    = $meta->{$column};
 910  
 911          // If a new meta_key (last parameter) was specified, change the meta key,
 912          // otherwise use the original key in the update statement.
 913          if ( false === $meta_key ) {
 914              $meta_key = $original_key;
 915          } elseif ( ! is_string( $meta_key ) ) {
 916              return false;
 917          }
 918  
 919          $meta_subtype = get_object_subtype( $meta_type, $object_id );
 920  
 921          // Sanitize the meta.
 922          $_meta_value = $meta_value;
 923          $meta_value  = sanitize_meta( $meta_key, $meta_value, $meta_type, $meta_subtype );
 924          $meta_value  = maybe_serialize( $meta_value );
 925  
 926          // Format the data query arguments.
 927          $data = array(
 928              'meta_key'   => $meta_key,
 929              'meta_value' => $meta_value,
 930          );
 931  
 932          // Format the where query arguments.
 933          $where               = array();
 934          $where[ $id_column ] = $meta_id;
 935  
 936          /** This action is documented in wp-includes/meta.php */
 937          do_action( "update_{$meta_type}_meta", $meta_id, $object_id, $meta_key, $_meta_value );
 938  
 939          if ( 'post' === $meta_type ) {
 940              /** This action is documented in wp-includes/meta.php */
 941              do_action( 'update_postmeta', $meta_id, $object_id, $meta_key, $meta_value );
 942          }
 943  
 944          // Run the update query, all fields in $data are %s, $where is a %d.
 945          $result = $wpdb->update( $table, $data, $where, '%s', '%d' );
 946          if ( ! $result ) {
 947              return false;
 948          }
 949  
 950          // Clear the caches.
 951          wp_cache_delete( $object_id, $meta_type . '_meta' );
 952  
 953          /** This action is documented in wp-includes/meta.php */
 954          do_action( "updated_{$meta_type}_meta", $meta_id, $object_id, $meta_key, $_meta_value );
 955  
 956          if ( 'post' === $meta_type ) {
 957              /** This action is documented in wp-includes/meta.php */
 958              do_action( 'updated_postmeta', $meta_id, $object_id, $meta_key, $meta_value );
 959          }
 960  
 961          return true;
 962      }
 963  
 964      // And if the meta was not found.
 965      return false;
 966  }
 967  
 968  /**
 969   * Deletes metadata by meta ID.
 970   *
 971   * @since 3.3.0
 972   *
 973   * @global wpdb $wpdb WordPress database abstraction object.
 974   *
 975   * @param string $meta_type Type of object metadata is for. Accepts 'post', 'comment', 'term', 'user',
 976   *                          or any other object type with an associated meta table.
 977   * @param int    $meta_id   ID for a specific meta row.
 978   * @return bool True on successful delete, false on failure.
 979   */
 980  function delete_metadata_by_mid( $meta_type, $meta_id ) {
 981      global $wpdb;
 982  
 983      // Make sure everything is valid.
 984      if ( ! $meta_type || ! is_numeric( $meta_id ) || floor( $meta_id ) != $meta_id ) {
 985          return false;
 986      }
 987  
 988      $meta_id = (int) $meta_id;
 989      if ( $meta_id <= 0 ) {
 990          return false;
 991      }
 992  
 993      $table = _get_meta_table( $meta_type );
 994      if ( ! $table ) {
 995          return false;
 996      }
 997  
 998      // Object and ID columns.
 999      $column    = sanitize_key( $meta_type . '_id' );
1000      $id_column = ( 'user' === $meta_type ) ? 'umeta_id' : 'meta_id';
1001  
1002      /**
1003       * Short-circuits deleting metadata of a specific type by meta ID.
1004       *
1005       * The dynamic portion of the hook name, `$meta_type`, refers to the meta object type
1006       * (post, comment, term, user, or any other type with an associated meta table).
1007       * Returning a non-null value will effectively short-circuit the function.
1008       *
1009       * Possible hook names include:
1010       *
1011       *  - `delete_post_metadata_by_mid`
1012       *  - `delete_comment_metadata_by_mid`
1013       *  - `delete_term_metadata_by_mid`
1014       *  - `delete_user_metadata_by_mid`
1015       *
1016       * @since 5.0.0
1017       *
1018       * @param null|bool $delete  Whether to allow metadata deletion of the given type.
1019       * @param int       $meta_id Meta ID.
1020       */
1021      $check = apply_filters( "delete_{$meta_type}_metadata_by_mid", null, $meta_id );
1022      if ( null !== $check ) {
1023          return (bool) $check;
1024      }
1025  
1026      // Fetch the meta and go on if it's found.
1027      $meta = get_metadata_by_mid( $meta_type, $meta_id );
1028      if ( $meta ) {
1029          $object_id = (int) $meta->{$column};
1030  
1031          /** This action is documented in wp-includes/meta.php */
1032          do_action( "delete_{$meta_type}_meta", (array) $meta_id, $object_id, $meta->meta_key, $meta->meta_value );
1033  
1034          // Old-style action.
1035          if ( 'post' === $meta_type || 'comment' === $meta_type ) {
1036              /**
1037               * Fires immediately before deleting post or comment metadata of a specific type.
1038               *
1039               * The dynamic portion of the hook name, `$meta_type`, refers to the meta
1040               * object type (post or comment).
1041               *
1042               * Possible hook names include:
1043               *
1044               *  - `delete_postmeta`
1045               *  - `delete_commentmeta`
1046               *  - `delete_termmeta`
1047               *  - `delete_usermeta`
1048               *
1049               * @since 3.4.0
1050               *
1051               * @param int $meta_id ID of the metadata entry to delete.
1052               */
1053              do_action( "delete_{$meta_type}meta", $meta_id );
1054          }
1055  
1056          // Run the query, will return true if deleted, false otherwise.
1057          $result = (bool) $wpdb->delete( $table, array( $id_column => $meta_id ) );
1058  
1059          // Clear the caches.
1060          wp_cache_delete( $object_id, $meta_type . '_meta' );
1061  
1062          /** This action is documented in wp-includes/meta.php */
1063          do_action( "deleted_{$meta_type}_meta", (array) $meta_id, $object_id, $meta->meta_key, $meta->meta_value );
1064  
1065          // Old-style action.
1066          if ( 'post' === $meta_type || 'comment' === $meta_type ) {
1067              /**
1068               * Fires immediately after deleting post or comment metadata of a specific type.
1069               *
1070               * The dynamic portion of the hook name, `$meta_type`, refers to the meta
1071               * object type (post or comment).
1072               *
1073               * Possible hook names include:
1074               *
1075               *  - `deleted_postmeta`
1076               *  - `deleted_commentmeta`
1077               *  - `deleted_termmeta`
1078               *  - `deleted_usermeta`
1079               *
1080               * @since 3.4.0
1081               *
1082               * @param int $meta_ids Deleted metadata entry ID.
1083               */
1084              do_action( "deleted_{$meta_type}meta", $meta_id );
1085          }
1086  
1087          return $result;
1088  
1089      }
1090  
1091      // Meta ID was not found.
1092      return false;
1093  }
1094  
1095  /**
1096   * Updates the metadata cache for the specified objects.
1097   *
1098   * @since 2.9.0
1099   *
1100   * @global wpdb $wpdb WordPress database abstraction object.
1101   *
1102   * @param string       $meta_type  Type of object metadata is for. Accepts 'post', 'comment', 'term', 'user',
1103   *                                 or any other object type with an associated meta table.
1104   * @param string|int[] $object_ids Array or comma delimited list of object IDs to update cache for.
1105   * @return array|false Metadata cache for the specified objects, or false on failure.
1106   */
1107  function update_meta_cache( $meta_type, $object_ids ) {
1108      global $wpdb;
1109  
1110      if ( ! $meta_type || ! $object_ids ) {
1111          return false;
1112      }
1113  
1114      $table = _get_meta_table( $meta_type );
1115      if ( ! $table ) {
1116          return false;
1117      }
1118  
1119      $column = sanitize_key( $meta_type . '_id' );
1120  
1121      if ( ! is_array( $object_ids ) ) {
1122          $object_ids = preg_replace( '|[^0-9,]|', '', $object_ids );
1123          $object_ids = explode( ',', $object_ids );
1124      }
1125  
1126      $object_ids = array_map( 'intval', $object_ids );
1127  
1128      /**
1129       * Short-circuits updating the metadata cache of a specific type.
1130       *
1131       * The dynamic portion of the hook name, `$meta_type`, refers to the meta object type
1132       * (post, comment, term, user, or any other type with an associated meta table).
1133       * Returning a non-null value will effectively short-circuit the function.
1134       *
1135       * Possible hook names include:
1136       *
1137       *  - `update_post_metadata_cache`
1138       *  - `update_comment_metadata_cache`
1139       *  - `update_term_metadata_cache`
1140       *  - `update_user_metadata_cache`
1141       *
1142       * @since 5.0.0
1143       *
1144       * @param mixed $check      Whether to allow updating the meta cache of the given type.
1145       * @param int[] $object_ids Array of object IDs to update the meta cache for.
1146       */
1147      $check = apply_filters( "update_{$meta_type}_metadata_cache", null, $object_ids );
1148      if ( null !== $check ) {
1149          return (bool) $check;
1150      }
1151  
1152      $cache_key      = $meta_type . '_meta';
1153      $non_cached_ids = array();
1154      $cache          = array();
1155      $cache_values   = wp_cache_get_multiple( $object_ids, $cache_key );
1156  
1157      foreach ( $cache_values as $id => $cached_object ) {
1158          if ( false === $cached_object ) {
1159              $non_cached_ids[] = $id;
1160          } else {
1161              $cache[ $id ] = $cached_object;
1162          }
1163      }
1164  
1165      if ( empty( $non_cached_ids ) ) {
1166          return $cache;
1167      }
1168  
1169      // Get meta info.
1170      $id_list   = implode( ',', $non_cached_ids );
1171      $id_column = ( 'user' === $meta_type ) ? 'umeta_id' : 'meta_id';
1172  
1173      $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 );
1174  
1175      if ( ! empty( $meta_list ) ) {
1176          foreach ( $meta_list as $metarow ) {
1177              $mpid = (int) $metarow[ $column ];
1178              $mkey = $metarow['meta_key'];
1179              $mval = $metarow['meta_value'];
1180  
1181              // Force subkeys to be array type.
1182              if ( ! isset( $cache[ $mpid ] ) || ! is_array( $cache[ $mpid ] ) ) {
1183                  $cache[ $mpid ] = array();
1184              }
1185              if ( ! isset( $cache[ $mpid ][ $mkey ] ) || ! is_array( $cache[ $mpid ][ $mkey ] ) ) {
1186                  $cache[ $mpid ][ $mkey ] = array();
1187              }
1188  
1189              // Add a value to the current pid/key.
1190              $cache[ $mpid ][ $mkey ][] = $mval;
1191          }
1192      }
1193  
1194      foreach ( $non_cached_ids as $id ) {
1195          if ( ! isset( $cache[ $id ] ) ) {
1196              $cache[ $id ] = array();
1197          }
1198          wp_cache_add( $id, $cache[ $id ], $cache_key );
1199      }
1200  
1201      return $cache;
1202  }
1203  
1204  /**
1205   * Retrieves the queue for lazy-loading metadata.
1206   *
1207   * @since 4.5.0
1208   *
1209   * @return WP_Metadata_Lazyloader Metadata lazyloader queue.
1210   */
1211  function wp_metadata_lazyloader() {
1212      static $wp_metadata_lazyloader;
1213  
1214      if ( null === $wp_metadata_lazyloader ) {
1215          $wp_metadata_lazyloader = new WP_Metadata_Lazyloader();
1216      }
1217  
1218      return $wp_metadata_lazyloader;
1219  }
1220  
1221  /**
1222   * Given a meta query, generates SQL clauses to be appended to a main query.
1223   *
1224   * @since 3.2.0
1225   *
1226   * @see WP_Meta_Query
1227   *
1228   * @param array  $meta_query        A meta query.
1229   * @param string $type              Type of meta.
1230   * @param string $primary_table     Primary database table name.
1231   * @param string $primary_id_column Primary ID column name.
1232   * @param object $context           Optional. The main query object
1233   * @return array Associative array of `JOIN` and `WHERE` SQL.
1234   */
1235  function get_meta_sql( $meta_query, $type, $primary_table, $primary_id_column, $context = null ) {
1236      $meta_query_obj = new WP_Meta_Query( $meta_query );
1237      return $meta_query_obj->get_sql( $type, $primary_table, $primary_id_column, $context );
1238  }
1239  
1240  /**
1241   * Retrieves the name of the metadata table for the specified object type.
1242   *
1243   * @since 2.9.0
1244   *
1245   * @global wpdb $wpdb WordPress database abstraction object.
1246   *
1247   * @param string $type Type of object metadata is for. Accepts 'post', 'comment', 'term', 'user',
1248   *                     or any other object type with an associated meta table.
1249   * @return string|false Metadata table name, or false if no metadata table exists
1250   */
1251  function _get_meta_table( $type ) {
1252      global $wpdb;
1253  
1254      $table_name = $type . 'meta';
1255  
1256      if ( empty( $wpdb->$table_name ) ) {
1257          return false;
1258      }
1259  
1260      return $wpdb->$table_name;
1261  }
1262  
1263  /**
1264   * Determines whether a meta key is considered protected.
1265   *
1266   * @since 3.1.3
1267   *
1268   * @param string $meta_key  Metadata key.
1269   * @param string $meta_type Optional. Type of object metadata is for. Accepts 'post', 'comment', 'term', 'user',
1270   *                          or any other object type with an associated meta table. Default empty.
1271   * @return bool Whether the meta key is considered protected.
1272   */
1273  function is_protected_meta( $meta_key, $meta_type = '' ) {
1274      $sanitized_key = preg_replace( "/[^\x20-\x7E\p{L}]/", '', $meta_key );
1275      $protected     = strlen( $sanitized_key ) > 0 && ( '_' === $sanitized_key[0] );
1276  
1277      /**
1278       * Filters whether a meta key is considered protected.
1279       *
1280       * @since 3.2.0
1281       *
1282       * @param bool   $protected Whether the key is considered protected.
1283       * @param string $meta_key  Metadata key.
1284       * @param string $meta_type Type of object metadata is for. Accepts 'post', 'comment', 'term', 'user',
1285       *                          or any other object type with an associated meta table.
1286       */
1287      return apply_filters( 'is_protected_meta', $protected, $meta_key, $meta_type );
1288  }
1289  
1290  /**
1291   * Sanitizes meta value.
1292   *
1293   * @since 3.1.3
1294   * @since 4.9.8 The `$object_subtype` parameter was added.
1295   *
1296   * @param string $meta_key       Metadata key.
1297   * @param mixed  $meta_value     Metadata value to sanitize.
1298   * @param string $object_type    Type of object metadata is for. Accepts 'post', 'comment', 'term', 'user',
1299   *                               or any other object type with an associated meta table.
1300   * @param string $object_subtype Optional. The subtype of the object type.
1301   * @return mixed Sanitized $meta_value.
1302   */
1303  function sanitize_meta( $meta_key, $meta_value, $object_type, $object_subtype = '' ) {
1304      if ( ! empty( $object_subtype ) && has_filter( "sanitize_{$object_type}_meta_{$meta_key}_for_{$object_subtype}" ) ) {
1305  
1306          /**
1307           * Filters the sanitization of a specific meta key of a specific meta type and subtype.
1308           *
1309           * The dynamic portions of the hook name, `$object_type`, `$meta_key`,
1310           * and `$object_subtype`, refer to the metadata object type (comment, post, term, or user),
1311           * the meta key value, and the object subtype respectively.
1312           *
1313           * @since 4.9.8
1314           *
1315           * @param mixed  $meta_value     Metadata value to sanitize.
1316           * @param string $meta_key       Metadata key.
1317           * @param string $object_type    Type of object metadata is for. Accepts 'post', 'comment', 'term', 'user',
1318           *                               or any other object type with an associated meta table.
1319           * @param string $object_subtype Object subtype.
1320           */
1321          return apply_filters( "sanitize_{$object_type}_meta_{$meta_key}_for_{$object_subtype}", $meta_value, $meta_key, $object_type, $object_subtype );
1322      }
1323  
1324      /**
1325       * Filters the sanitization of a specific meta key of a specific meta type.
1326       *
1327       * The dynamic portions of the hook name, `$meta_type`, and `$meta_key`,
1328       * refer to the metadata object type (comment, post, term, or user) and the meta
1329       * key value, respectively.
1330       *
1331       * @since 3.3.0
1332       *
1333       * @param mixed  $meta_value  Metadata value to sanitize.
1334       * @param string $meta_key    Metadata key.
1335       * @param string $object_type Type of object metadata is for. Accepts 'post', 'comment', 'term', 'user',
1336       *                            or any other object type with an associated meta table.
1337       */
1338      return apply_filters( "sanitize_{$object_type}_meta_{$meta_key}", $meta_value, $meta_key, $object_type );
1339  }
1340  
1341  /**
1342   * Registers a meta key.
1343   *
1344   * It is recommended to register meta keys for a specific combination of object type and object subtype. If passing
1345   * an object subtype is omitted, the meta key will be registered for the entire object type, however it can be partly
1346   * overridden in case a more specific meta key of the same name exists for the same object type and a subtype.
1347   *
1348   * If an object type does not support any subtypes, such as users or comments, you should commonly call this function
1349   * without passing a subtype.
1350   *
1351   * @since 3.3.0
1352   * @since 4.6.0 {@link https://core.trac.wordpress.org/ticket/35658 Modified
1353   *              to support an array of data to attach to registered meta keys}. Previous arguments for
1354   *              `$sanitize_callback` and `$auth_callback` have been folded into this array.
1355   * @since 4.9.8 The `$object_subtype` argument was added to the arguments array.
1356   * @since 5.3.0 Valid meta types expanded to include "array" and "object".
1357   * @since 5.5.0 The `$default` argument was added to the arguments array.
1358   *
1359   * @param string       $object_type Type of object metadata is for. Accepts 'post', 'comment', 'term', 'user',
1360   *                                  or any other object type with an associated meta table.
1361   * @param string       $meta_key    Meta key to register.
1362   * @param array        $args {
1363   *     Data used to describe the meta key when registered.
1364   *
1365   *     @type string     $object_subtype    A subtype; e.g. if the object type is "post", the post type. If left empty,
1366   *                                         the meta key will be registered on the entire object type. Default empty.
1367   *     @type string     $type              The type of data associated with this meta key.
1368   *                                         Valid values are 'string', 'boolean', 'integer', 'number', 'array', and 'object'.
1369   *     @type string     $description       A description of the data attached to this meta key.
1370   *     @type bool       $single            Whether the meta key has one value per object, or an array of values per object.
1371   *     @type mixed      $default           The default value returned from get_metadata() if no value has been set yet.
1372   *                                         When using a non-single meta key, the default value is for the first entry.
1373   *                                         In other words, when calling get_metadata() with `$single` set to `false`,
1374   *                                         the default value given here will be wrapped in an array.
1375   *     @type callable   $sanitize_callback A function or method to call when sanitizing `$meta_key` data.
1376   *     @type callable   $auth_callback     Optional. A function or method to call when performing edit_post_meta,
1377   *                                         add_post_meta, and delete_post_meta capability checks.
1378   *     @type bool|array $show_in_rest      Whether data associated with this meta key can be considered public and
1379   *                                         should be accessible via the REST API. A custom post type must also declare
1380   *                                         support for custom fields for registered meta to be accessible via REST.
1381   *                                         When registering complex meta values this argument may optionally be an
1382   *                                         array with 'schema' or 'prepare_callback' keys instead of a boolean.
1383   * }
1384   * @param string|array $deprecated Deprecated. Use `$args` instead.
1385   * @return bool True if the meta key was successfully registered in the global array, false if not.
1386   *              Registering a meta key with distinct sanitize and auth callbacks will fire those callbacks,
1387   *              but will not add to the global registry.
1388   */
1389  function register_meta( $object_type, $meta_key, $args, $deprecated = null ) {
1390      global $wp_meta_keys;
1391  
1392      if ( ! is_array( $wp_meta_keys ) ) {
1393          $wp_meta_keys = array();
1394      }
1395  
1396      $defaults = array(
1397          'object_subtype'    => '',
1398          'type'              => 'string',
1399          'description'       => '',
1400          'default'           => '',
1401          'single'            => false,
1402          'sanitize_callback' => null,
1403          'auth_callback'     => null,
1404          'show_in_rest'      => false,
1405      );
1406  
1407      // There used to be individual args for sanitize and auth callbacks.
1408      $has_old_sanitize_cb = false;
1409      $has_old_auth_cb     = false;
1410  
1411      if ( is_callable( $args ) ) {
1412          $args = array(
1413              'sanitize_callback' => $args,
1414          );
1415  
1416          $has_old_sanitize_cb = true;
1417      } else {
1418          $args = (array) $args;
1419      }
1420  
1421      if ( is_callable( $deprecated ) ) {
1422          $args['auth_callback'] = $deprecated;
1423          $has_old_auth_cb       = true;
1424      }
1425  
1426      /**
1427       * Filters the registration arguments when registering meta.
1428       *
1429       * @since 4.6.0
1430       *
1431       * @param array  $args        Array of meta registration arguments.
1432       * @param array  $defaults    Array of default arguments.
1433       * @param string $object_type Type of object metadata is for. Accepts 'post', 'comment', 'term', 'user',
1434       *                            or any other object type with an associated meta table.
1435       * @param string $meta_key    Meta key.
1436       */
1437      $args = apply_filters( 'register_meta_args', $args, $defaults, $object_type, $meta_key );
1438      unset( $defaults['default'] );
1439      $args = wp_parse_args( $args, $defaults );
1440  
1441      // Require an item schema when registering array meta.
1442      if ( false !== $args['show_in_rest'] && 'array' === $args['type'] ) {
1443          if ( ! is_array( $args['show_in_rest'] ) || ! isset( $args['show_in_rest']['schema']['items'] ) ) {
1444              _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' );
1445  
1446              return false;
1447          }
1448      }
1449  
1450      $object_subtype = ! empty( $args['object_subtype'] ) ? $args['object_subtype'] : '';
1451  
1452      // If `auth_callback` is not provided, fall back to `is_protected_meta()`.
1453      if ( empty( $args['auth_callback'] ) ) {
1454          if ( is_protected_meta( $meta_key, $object_type ) ) {
1455              $args['auth_callback'] = '__return_false';
1456          } else {
1457              $args['auth_callback'] = '__return_true';
1458          }
1459      }
1460  
1461      // Back-compat: old sanitize and auth callbacks are applied to all of an object type.
1462      if ( is_callable( $args['sanitize_callback'] ) ) {
1463          if ( ! empty( $object_subtype ) ) {
1464              add_filter( "sanitize_{$object_type}_meta_{$meta_key}_for_{$object_subtype}", $args['sanitize_callback'], 10, 4 );
1465          } else {
1466              add_filter( "sanitize_{$object_type}_meta_{$meta_key}", $args['sanitize_callback'], 10, 3 );
1467          }
1468      }
1469  
1470      if ( is_callable( $args['auth_callback'] ) ) {
1471          if ( ! empty( $object_subtype ) ) {
1472              add_filter( "auth_{$object_type}_meta_{$meta_key}_for_{$object_subtype}", $args['auth_callback'], 10, 6 );
1473          } else {
1474              add_filter( "auth_{$object_type}_meta_{$meta_key}", $args['auth_callback'], 10, 6 );
1475          }
1476      }
1477  
1478      if ( array_key_exists( 'default', $args ) ) {
1479          $schema = $args;
1480          if ( is_array( $args['show_in_rest'] ) && isset( $args['show_in_rest']['schema'] ) ) {
1481              $schema = array_merge( $schema, $args['show_in_rest']['schema'] );
1482          }
1483  
1484          $check = rest_validate_value_from_schema( $args['default'], $schema );
1485          if ( is_wp_error( $check ) ) {
1486              _doing_it_wrong( __FUNCTION__, __( 'When registering a default meta value the data must match the type provided.' ), '5.5.0' );
1487  
1488              return false;
1489          }
1490  
1491          if ( ! has_filter( "default_{$object_type}_metadata", 'filter_default_metadata' ) ) {
1492              add_filter( "default_{$object_type}_metadata", 'filter_default_metadata', 10, 5 );
1493          }
1494      }
1495  
1496      // Global registry only contains meta keys registered with the array of arguments added in 4.6.0.
1497      if ( ! $has_old_auth_cb && ! $has_old_sanitize_cb ) {
1498          unset( $args['object_subtype'] );
1499  
1500          $wp_meta_keys[ $object_type ][ $object_subtype ][ $meta_key ] = $args;
1501  
1502          return true;
1503      }
1504  
1505      return false;
1506  }
1507  
1508  /**
1509   * Filters into default_{$object_type}_metadata and adds in default value.
1510   *
1511   * @since 5.5.0
1512   *
1513   * @param mixed  $value     Current value passed to filter.
1514   * @param int    $object_id ID of the object metadata is for.
1515   * @param string $meta_key  Metadata key.
1516   * @param bool   $single    If true, return only the first value of the specified `$meta_key`.
1517   *                          This parameter has no effect if `$meta_key` is not specified.
1518   * @param string $meta_type Type of object metadata is for. Accepts 'post', 'comment', 'term', 'user',
1519   *                          or any other object type with an associated meta table.
1520   * @return mixed An array of default values if `$single` is false.
1521   *               The default value of the meta field if `$single` is true.
1522   */
1523  function filter_default_metadata( $value, $object_id, $meta_key, $single, $meta_type ) {
1524      global $wp_meta_keys;
1525  
1526      if ( wp_installing() ) {
1527          return $value;
1528      }
1529  
1530      if ( ! is_array( $wp_meta_keys ) || ! isset( $wp_meta_keys[ $meta_type ] ) ) {
1531          return $value;
1532      }
1533  
1534      $defaults = array();
1535      foreach ( $wp_meta_keys[ $meta_type ] as $sub_type => $meta_data ) {
1536          foreach ( $meta_data as $_meta_key => $args ) {
1537              if ( $_meta_key === $meta_key && array_key_exists( 'default', $args ) ) {
1538                  $defaults[ $sub_type ] = $args;
1539              }
1540          }
1541      }
1542  
1543      if ( ! $defaults ) {
1544          return $value;
1545      }
1546  
1547      // If this meta type does not have subtypes, then the default is keyed as an empty string.
1548      if ( isset( $defaults[''] ) ) {
1549          $metadata = $defaults[''];
1550      } else {
1551          $sub_type = get_object_subtype( $meta_type, $object_id );
1552          if ( ! isset( $defaults[ $sub_type ] ) ) {
1553              return $value;
1554          }
1555          $metadata = $defaults[ $sub_type ];
1556      }
1557  
1558      if ( $single ) {
1559          $value = $metadata['default'];
1560      } else {
1561          $value = array( $metadata['default'] );
1562      }
1563  
1564      return $value;
1565  }
1566  
1567  /**
1568   * Checks if a meta key is registered.
1569   *
1570   * @since 4.6.0
1571   * @since 4.9.8 The `$object_subtype` parameter was added.
1572   *
1573   * @param string $object_type    Type of object metadata is for. Accepts 'post', 'comment', 'term', 'user',
1574   *                               or any other object type with an associated meta table.
1575   * @param string $meta_key       Metadata key.
1576   * @param string $object_subtype Optional. The subtype of the object type.
1577   * @return bool True if the meta key is registered to the object type and, if provided,
1578   *              the object subtype. False if not.
1579   */
1580  function registered_meta_key_exists( $object_type, $meta_key, $object_subtype = '' ) {
1581      $meta_keys = get_registered_meta_keys( $object_type, $object_subtype );
1582  
1583      return isset( $meta_keys[ $meta_key ] );
1584  }
1585  
1586  /**
1587   * Unregisters a meta key from the list of registered keys.
1588   *
1589   * @since 4.6.0
1590   * @since 4.9.8 The `$object_subtype` parameter was added.
1591   *
1592   * @param string $object_type    Type of object metadata is for. Accepts 'post', 'comment', 'term', 'user',
1593   *                               or any other object type with an associated meta table.
1594   * @param string $meta_key       Metadata key.
1595   * @param string $object_subtype Optional. The subtype of the object type.
1596   * @return bool True if successful. False if the meta key was not registered.
1597   */
1598  function unregister_meta_key( $object_type, $meta_key, $object_subtype = '' ) {
1599      global $wp_meta_keys;
1600  
1601      if ( ! registered_meta_key_exists( $object_type, $meta_key, $object_subtype ) ) {
1602          return false;
1603      }
1604  
1605      $args = $wp_meta_keys[ $object_type ][ $object_subtype ][ $meta_key ];
1606  
1607      if ( isset( $args['sanitize_callback'] ) && is_callable( $args['sanitize_callback'] ) ) {
1608          if ( ! empty( $object_subtype ) ) {
1609              remove_filter( "sanitize_{$object_type}_meta_{$meta_key}_for_{$object_subtype}", $args['sanitize_callback'] );
1610          } else {
1611              remove_filter( "sanitize_{$object_type}_meta_{$meta_key}", $args['sanitize_callback'] );
1612          }
1613      }
1614  
1615      if ( isset( $args['auth_callback'] ) && is_callable( $args['auth_callback'] ) ) {
1616          if ( ! empty( $object_subtype ) ) {
1617              remove_filter( "auth_{$object_type}_meta_{$meta_key}_for_{$object_subtype}", $args['auth_callback'] );
1618          } else {
1619              remove_filter( "auth_{$object_type}_meta_{$meta_key}", $args['auth_callback'] );
1620          }
1621      }
1622  
1623      unset( $wp_meta_keys[ $object_type ][ $object_subtype ][ $meta_key ] );
1624  
1625      // Do some clean up.
1626      if ( empty( $wp_meta_keys[ $object_type ][ $object_subtype ] ) ) {
1627          unset( $wp_meta_keys[ $object_type ][ $object_subtype ] );
1628      }
1629      if ( empty( $wp_meta_keys[ $object_type ] ) ) {
1630          unset( $wp_meta_keys[ $object_type ] );
1631      }
1632  
1633      return true;
1634  }
1635  
1636  /**
1637   * Retrieves a list of registered meta keys for an object type.
1638   *
1639   * @since 4.6.0
1640   * @since 4.9.8 The `$object_subtype` parameter was added.
1641   *
1642   * @param string $object_type    Type of object metadata is for. Accepts 'post', 'comment', 'term', 'user',
1643   *                               or any other object type with an associated meta table.
1644   * @param string $object_subtype Optional. The subtype of the object type.
1645   * @return string[] List of registered meta keys.
1646   */
1647  function get_registered_meta_keys( $object_type, $object_subtype = '' ) {
1648      global $wp_meta_keys;
1649  
1650      if ( ! is_array( $wp_meta_keys ) || ! isset( $wp_meta_keys[ $object_type ] ) || ! isset( $wp_meta_keys[ $object_type ][ $object_subtype ] ) ) {
1651          return array();
1652      }
1653  
1654      return $wp_meta_keys[ $object_type ][ $object_subtype ];
1655  }
1656  
1657  /**
1658   * Retrieves registered metadata for a specified object.
1659   *
1660   * The results include both meta that is registered specifically for the
1661   * object's subtype and meta that is registered for the entire object type.
1662   *
1663   * @since 4.6.0
1664   *
1665   * @param string $object_type Type of object metadata is for. Accepts 'post', 'comment', 'term', 'user',
1666   *                            or any other object type with an associated meta table.
1667   * @param int    $object_id   ID of the object the metadata is for.
1668   * @param string $meta_key    Optional. Registered metadata key. If not specified, retrieve all registered
1669   *                            metadata for the specified object.
1670   * @return mixed A single value or array of values for a key if specified. An array of all registered keys
1671   *               and values for an object ID if not. False if a given $meta_key is not registered.
1672   */
1673  function get_registered_metadata( $object_type, $object_id, $meta_key = '' ) {
1674      $object_subtype = get_object_subtype( $object_type, $object_id );
1675  
1676      if ( ! empty( $meta_key ) ) {
1677          if ( ! empty( $object_subtype ) && ! registered_meta_key_exists( $object_type, $meta_key, $object_subtype ) ) {
1678              $object_subtype = '';
1679          }
1680  
1681          if ( ! registered_meta_key_exists( $object_type, $meta_key, $object_subtype ) ) {
1682              return false;
1683          }
1684  
1685          $meta_keys     = get_registered_meta_keys( $object_type, $object_subtype );
1686          $meta_key_data = $meta_keys[ $meta_key ];
1687  
1688          $data = get_metadata( $object_type, $object_id, $meta_key, $meta_key_data['single'] );
1689  
1690          return $data;
1691      }
1692  
1693      $data = get_metadata( $object_type, $object_id );
1694      if ( ! $data ) {
1695          return array();
1696      }
1697  
1698      $meta_keys = get_registered_meta_keys( $object_type );
1699      if ( ! empty( $object_subtype ) ) {
1700          $meta_keys = array_merge( $meta_keys, get_registered_meta_keys( $object_type, $object_subtype ) );
1701      }
1702  
1703      return array_intersect_key( $data, $meta_keys );
1704  }
1705  
1706  /**
1707   * Filters out `register_meta()` args based on an allowed list.
1708   *
1709   * `register_meta()` args may change over time, so requiring the allowed list
1710   * to be explicitly turned off is a warranty seal of sorts.
1711   *
1712   * @access private
1713   * @since 5.5.0
1714   *
1715   * @param array $args         Arguments from `register_meta()`.
1716   * @param array $default_args Default arguments for `register_meta()`.
1717   * @return array Filtered arguments.
1718   */
1719  function _wp_register_meta_args_allowed_list( $args, $default_args ) {
1720      return array_intersect_key( $args, $default_args );
1721  }
1722  
1723  /**
1724   * Returns the object subtype for a given object ID of a specific type.
1725   *
1726   * @since 4.9.8
1727   *
1728   * @param string $object_type Type of object metadata is for. Accepts 'post', 'comment', 'term', 'user',
1729   *                            or any other object type with an associated meta table.
1730   * @param int    $object_id   ID of the object to retrieve its subtype.
1731   * @return string The object subtype or an empty string if unspecified subtype.
1732   */
1733  function get_object_subtype( $object_type, $object_id ) {
1734      $object_id      = (int) $object_id;
1735      $object_subtype = '';
1736  
1737      switch ( $object_type ) {
1738          case 'post':
1739              $post_type = get_post_type( $object_id );
1740  
1741              if ( ! empty( $post_type ) ) {
1742                  $object_subtype = $post_type;
1743              }
1744              break;
1745  
1746          case 'term':
1747              $term = get_term( $object_id );
1748              if ( ! $term instanceof WP_Term ) {
1749                  break;
1750              }
1751  
1752              $object_subtype = $term->taxonomy;
1753              break;
1754  
1755          case 'comment':
1756              $comment = get_comment( $object_id );
1757              if ( ! $comment ) {
1758                  break;
1759              }
1760  
1761              $object_subtype = 'comment';
1762              break;
1763  
1764          case 'user':
1765              $user = get_user_by( 'id', $object_id );
1766              if ( ! $user ) {
1767                  break;
1768              }
1769  
1770              $object_subtype = 'user';
1771              break;
1772      }
1773  
1774      /**
1775       * Filters the object subtype identifier for a non-standard object type.
1776       *
1777       * The dynamic portion of the hook name, `$object_type`, refers to the meta object type
1778       * (post, comment, term, user, or any other type with an associated meta table).
1779       *
1780       * Possible hook names include:
1781       *
1782       *  - `get_object_subtype_post`
1783       *  - `get_object_subtype_comment`
1784       *  - `get_object_subtype_term`
1785       *  - `get_object_subtype_user`
1786       *
1787       * @since 4.9.8
1788       *
1789       * @param string $object_subtype Empty string to override.
1790       * @param int    $object_id      ID of the object to get the subtype for.
1791       */
1792      return apply_filters( "get_object_subtype_{$object_type}", $object_subtype, $object_id );
1793  }


Generated: Wed Sep 22 01:00:04 2021 Cross-referenced by PHPXref 0.7.1