home *** CD-ROM | disk | FTP | other *** search
/ HTML Examples / WP.iso / wordpress / wp-includes / meta.php < prev    next >
Encoding:
PHP Script  |  2017-10-31  |  36.6 KB  |  1,212 lines

  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.  * Add 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 (e.g., comment, post, or user)
  21.  * @param int    $object_id  ID of the object metadata is for
  22.  * @param string $meta_key   Metadata key
  23.  * @param mixed  $meta_value Metadata value. Must be serializable if non-scalar.
  24.  * @param bool   $unique     Optional, default is false.
  25.  *                           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.
  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.     $column = sanitize_key($meta_type . '_id');
  48.  
  49.     // expected_slashed ($meta_key)
  50.     $meta_key = wp_unslash($meta_key);
  51.     $meta_value = wp_unslash($meta_value);
  52.     $meta_value = sanitize_meta( $meta_key, $meta_value, $meta_type );
  53.  
  54.     /**
  55.      * Filters whether to add metadata of a specific type.
  56.      *
  57.      * The dynamic portion of the hook, `$meta_type`, refers to the meta
  58.      * object type (comment, post, or user). Returning a non-null value
  59.      * will effectively short-circuit the function.
  60.      *
  61.      * @since 3.1.0
  62.      *
  63.      * @param null|bool $check      Whether to allow adding metadata for the given type.
  64.      * @param int       $object_id  Object ID.
  65.      * @param string    $meta_key   Meta key.
  66.      * @param mixed     $meta_value Meta value. Must be serializable if non-scalar.
  67.      * @param bool      $unique     Whether the specified meta key should be unique
  68.      *                              for the object. Optional. Default false.
  69.      */
  70.     $check = apply_filters( "add_{$meta_type}_metadata", null, $object_id, $meta_key, $meta_value, $unique );
  71.     if ( null !== $check )
  72.         return $check;
  73.  
  74.     if ( $unique && $wpdb->get_var( $wpdb->prepare(
  75.         "SELECT COUNT(*) FROM $table WHERE meta_key = %s AND $column = %d",
  76.         $meta_key, $object_id ) ) )
  77.         return false;
  78.  
  79.     $_meta_value = $meta_value;
  80.     $meta_value = maybe_serialize( $meta_value );
  81.  
  82.     /**
  83.      * Fires immediately before meta of a specific type is added.
  84.      *
  85.      * The dynamic portion of the hook, `$meta_type`, refers to the meta
  86.      * object type (comment, post, or user).
  87.      *
  88.      * @since 3.1.0
  89.      *
  90.      * @param int    $object_id  Object ID.
  91.      * @param string $meta_key   Meta key.
  92.      * @param mixed  $meta_value Meta value.
  93.      */
  94.     do_action( "add_{$meta_type}_meta", $object_id, $meta_key, $_meta_value );
  95.  
  96.     $result = $wpdb->insert( $table, array(
  97.         $column => $object_id,
  98.         'meta_key' => $meta_key,
  99.         'meta_value' => $meta_value
  100.     ) );
  101.  
  102.     if ( ! $result )
  103.         return false;
  104.  
  105.     $mid = (int) $wpdb->insert_id;
  106.  
  107.     wp_cache_delete($object_id, $meta_type . '_meta');
  108.  
  109.     /**
  110.      * Fires immediately after meta of a specific type is added.
  111.      *
  112.      * The dynamic portion of the hook, `$meta_type`, refers to the meta
  113.      * object type (comment, post, or user).
  114.      *
  115.      * @since 2.9.0
  116.      *
  117.      * @param int    $mid        The meta ID after successful update.
  118.      * @param int    $object_id  Object ID.
  119.      * @param string $meta_key   Meta key.
  120.      * @param mixed  $meta_value Meta value.
  121.      */
  122.     do_action( "added_{$meta_type}_meta", $mid, $object_id, $meta_key, $_meta_value );
  123.  
  124.     return $mid;
  125. }
  126.  
  127. /**
  128.  * Update metadata for the specified object. If no value already exists for the specified object
  129.  * ID and metadata key, the metadata will be added.
  130.  *
  131.  * @since 2.9.0
  132.  *
  133.  * @global wpdb $wpdb WordPress database abstraction object.
  134.  *
  135.  * @param string $meta_type  Type of object metadata is for (e.g., comment, post, or user)
  136.  * @param int    $object_id  ID of the object metadata is for
  137.  * @param string $meta_key   Metadata key
  138.  * @param mixed  $meta_value Metadata value. Must be serializable if non-scalar.
  139.  * @param mixed  $prev_value Optional. If specified, only update existing metadata entries with
  140.  *                              the specified value. Otherwise, update all entries.
  141.  * @return int|bool Meta ID if the key didn't exist, true on successful update, false on failure.
  142.  */
  143. function update_metadata($meta_type, $object_id, $meta_key, $meta_value, $prev_value = '') {
  144.     global $wpdb;
  145.  
  146.     if ( ! $meta_type || ! $meta_key || ! is_numeric( $object_id ) ) {
  147.         return false;
  148.     }
  149.  
  150.     $object_id = absint( $object_id );
  151.     if ( ! $object_id ) {
  152.         return false;
  153.     }
  154.  
  155.     $table = _get_meta_table( $meta_type );
  156.     if ( ! $table ) {
  157.         return false;
  158.     }
  159.  
  160.     $column = sanitize_key($meta_type . '_id');
  161.     $id_column = 'user' == $meta_type ? 'umeta_id' : 'meta_id';
  162.  
  163.     // expected_slashed ($meta_key)
  164.     $raw_meta_key = $meta_key;
  165.     $meta_key = wp_unslash($meta_key);
  166.     $passed_value = $meta_value;
  167.     $meta_value = wp_unslash($meta_value);
  168.     $meta_value = sanitize_meta( $meta_key, $meta_value, $meta_type );
  169.  
  170.     /**
  171.      * Filters whether to update metadata of a specific type.
  172.      *
  173.      * The dynamic portion of the hook, `$meta_type`, refers to the meta
  174.      * object type (comment, post, or user). Returning a non-null value
  175.      * will effectively short-circuit the function.
  176.      *
  177.      * @since 3.1.0
  178.      *
  179.      * @param null|bool $check      Whether to allow updating metadata for the given type.
  180.      * @param int       $object_id  Object ID.
  181.      * @param string    $meta_key   Meta key.
  182.      * @param mixed     $meta_value Meta value. Must be serializable if non-scalar.
  183.      * @param mixed     $prev_value Optional. If specified, only update existing
  184.      *                              metadata entries with the specified value.
  185.      *                              Otherwise, update all entries.
  186.      */
  187.     $check = apply_filters( "update_{$meta_type}_metadata", null, $object_id, $meta_key, $meta_value, $prev_value );
  188.     if ( null !== $check )
  189.         return (bool) $check;
  190.  
  191.     // Compare existing value to new value if no prev value given and the key exists only once.
  192.     if ( empty($prev_value) ) {
  193.         $old_value = get_metadata($meta_type, $object_id, $meta_key);
  194.         if ( count($old_value) == 1 ) {
  195.             if ( $old_value[0] === $meta_value )
  196.                 return false;
  197.         }
  198.     }
  199.  
  200.     $meta_ids = $wpdb->get_col( $wpdb->prepare( "SELECT $id_column FROM $table WHERE meta_key = %s AND $column = %d", $meta_key, $object_id ) );
  201.     if ( empty( $meta_ids ) ) {
  202.         return add_metadata( $meta_type, $object_id, $raw_meta_key, $passed_value );
  203.     }
  204.  
  205.     $_meta_value = $meta_value;
  206.     $meta_value = maybe_serialize( $meta_value );
  207.  
  208.     $data  = compact( 'meta_value' );
  209.     $where = array( $column => $object_id, 'meta_key' => $meta_key );
  210.  
  211.     if ( !empty( $prev_value ) ) {
  212.         $prev_value = maybe_serialize($prev_value);
  213.         $where['meta_value'] = $prev_value;
  214.     }
  215.  
  216.     foreach ( $meta_ids as $meta_id ) {
  217.         /**
  218.          * Fires immediately before updating metadata of a specific type.
  219.          *
  220.          * The dynamic portion of the hook, `$meta_type`, refers to the meta
  221.          * object type (comment, post, or user).
  222.          *
  223.          * @since 2.9.0
  224.          *
  225.          * @param int    $meta_id    ID of the metadata entry to update.
  226.          * @param int    $object_id  Object ID.
  227.          * @param string $meta_key   Meta key.
  228.          * @param mixed  $meta_value Meta value.
  229.          */
  230.         do_action( "update_{$meta_type}_meta", $meta_id, $object_id, $meta_key, $_meta_value );
  231.  
  232.         if ( 'post' == $meta_type ) {
  233.             /**
  234.              * Fires immediately before updating a post's metadata.
  235.              *
  236.              * @since 2.9.0
  237.              *
  238.              * @param int    $meta_id    ID of metadata entry to update.
  239.              * @param int    $object_id  Object ID.
  240.              * @param string $meta_key   Meta key.
  241.              * @param mixed  $meta_value Meta value.
  242.              */
  243.             do_action( 'update_postmeta', $meta_id, $object_id, $meta_key, $meta_value );
  244.         }
  245.     }
  246.  
  247.     $result = $wpdb->update( $table, $data, $where );
  248.     if ( ! $result )
  249.         return false;
  250.  
  251.     wp_cache_delete($object_id, $meta_type . '_meta');
  252.  
  253.     foreach ( $meta_ids as $meta_id ) {
  254.         /**
  255.          * Fires immediately after updating metadata of a specific type.
  256.          *
  257.          * The dynamic portion of the hook, `$meta_type`, refers to the meta
  258.          * object type (comment, post, or user).
  259.          *
  260.          * @since 2.9.0
  261.          *
  262.          * @param int    $meta_id    ID of updated metadata entry.
  263.          * @param int    $object_id  Object ID.
  264.          * @param string $meta_key   Meta key.
  265.          * @param mixed  $meta_value Meta value.
  266.          */
  267.         do_action( "updated_{$meta_type}_meta", $meta_id, $object_id, $meta_key, $_meta_value );
  268.  
  269.         if ( 'post' == $meta_type ) {
  270.             /**
  271.              * Fires immediately after updating a post's metadata.
  272.              *
  273.              * @since 2.9.0
  274.              *
  275.              * @param int    $meta_id    ID of updated metadata entry.
  276.              * @param int    $object_id  Object ID.
  277.              * @param string $meta_key   Meta key.
  278.              * @param mixed  $meta_value Meta value.
  279.              */
  280.             do_action( 'updated_postmeta', $meta_id, $object_id, $meta_key, $meta_value );
  281.         }
  282.     }
  283.  
  284.     return true;
  285. }
  286.  
  287. /**
  288.  * Delete metadata for the specified object.
  289.  *
  290.  * @since 2.9.0
  291.  *
  292.  * @global wpdb $wpdb WordPress database abstraction object.
  293.  *
  294.  * @param string $meta_type  Type of object metadata is for (e.g., comment, post, or user)
  295.  * @param int    $object_id  ID of the object metadata is for
  296.  * @param string $meta_key   Metadata key
  297.  * @param mixed  $meta_value Optional. Metadata value. Must be serializable if non-scalar. If specified, only delete
  298.  *                           metadata entries with this value. Otherwise, delete all entries with the specified meta_key.
  299.  *                           Pass `null, `false`, or an empty string to skip this check. (For backward compatibility,
  300.  *                           it is not possible to pass an empty string to delete those entries with an empty string
  301.  *                           for a value.)
  302.  * @param bool   $delete_all Optional, default is false. If true, delete matching metadata entries for all objects,
  303.  *                           ignoring the specified object_id. Otherwise, only delete matching metadata entries for
  304.  *                           the specified object_id.
  305.  * @return bool True on successful delete, false on failure.
  306.  */
  307. function delete_metadata($meta_type, $object_id, $meta_key, $meta_value = '', $delete_all = false) {
  308.     global $wpdb;
  309.  
  310.     if ( ! $meta_type || ! $meta_key || ! is_numeric( $object_id ) && ! $delete_all ) {
  311.         return false;
  312.     }
  313.  
  314.     $object_id = absint( $object_id );
  315.     if ( ! $object_id && ! $delete_all ) {
  316.         return false;
  317.     }
  318.  
  319.     $table = _get_meta_table( $meta_type );
  320.     if ( ! $table ) {
  321.         return false;
  322.     }
  323.  
  324.     $type_column = sanitize_key($meta_type . '_id');
  325.     $id_column = 'user' == $meta_type ? 'umeta_id' : 'meta_id';
  326.     // expected_slashed ($meta_key)
  327.     $meta_key = wp_unslash($meta_key);
  328.     $meta_value = wp_unslash($meta_value);
  329.  
  330.     /**
  331.      * Filters whether to delete metadata of a specific type.
  332.      *
  333.      * The dynamic portion of the hook, `$meta_type`, refers to the meta
  334.      * object type (comment, post, or user). Returning a non-null value
  335.      * will effectively short-circuit the function.
  336.      *
  337.      * @since 3.1.0
  338.      *
  339.      * @param null|bool $delete     Whether to allow metadata deletion of the given type.
  340.      * @param int       $object_id  Object ID.
  341.      * @param string    $meta_key   Meta key.
  342.      * @param mixed     $meta_value Meta value. Must be serializable if non-scalar.
  343.      * @param bool      $delete_all Whether to delete the matching metadata entries
  344.      *                              for all objects, ignoring the specified $object_id.
  345.      *                              Default false.
  346.      */
  347.     $check = apply_filters( "delete_{$meta_type}_metadata", null, $object_id, $meta_key, $meta_value, $delete_all );
  348.     if ( null !== $check )
  349.         return (bool) $check;
  350.  
  351.     $_meta_value = $meta_value;
  352.     $meta_value = maybe_serialize( $meta_value );
  353.  
  354.     $query = $wpdb->prepare( "SELECT $id_column FROM $table WHERE meta_key = %s", $meta_key );
  355.  
  356.     if ( !$delete_all )
  357.         $query .= $wpdb->prepare(" AND $type_column = %d", $object_id );
  358.  
  359.     if ( '' !== $meta_value && null !== $meta_value && false !== $meta_value )
  360.         $query .= $wpdb->prepare(" AND meta_value = %s", $meta_value );
  361.  
  362.     $meta_ids = $wpdb->get_col( $query );
  363.     if ( !count( $meta_ids ) )
  364.         return false;
  365.  
  366.     if ( $delete_all ) {
  367.         if ( '' !== $meta_value && null !== $meta_value && false !== $meta_value ) {
  368.             $object_ids = $wpdb->get_col( $wpdb->prepare( "SELECT $type_column FROM $table WHERE meta_key = %s AND meta_value = %s", $meta_key, $meta_value ) );
  369.         } else {
  370.             $object_ids = $wpdb->get_col( $wpdb->prepare( "SELECT $type_column FROM $table WHERE meta_key = %s", $meta_key ) );
  371.         }
  372.     }
  373.  
  374.     /**
  375.      * Fires immediately before deleting metadata of a specific type.
  376.      *
  377.      * The dynamic portion of the hook, `$meta_type`, refers to the meta
  378.      * object type (comment, post, or user).
  379.      *
  380.      * @since 3.1.0
  381.      *
  382.      * @param array  $meta_ids   An array of metadata entry IDs to delete.
  383.      * @param int    $object_id  Object ID.
  384.      * @param string $meta_key   Meta key.
  385.      * @param mixed  $meta_value Meta value.
  386.      */
  387.     do_action( "delete_{$meta_type}_meta", $meta_ids, $object_id, $meta_key, $_meta_value );
  388.  
  389.     // Old-style action.
  390.     if ( 'post' == $meta_type ) {
  391.         /**
  392.          * Fires immediately before deleting metadata for a post.
  393.          *
  394.          * @since 2.9.0
  395.          *
  396.          * @param array $meta_ids An array of post metadata entry IDs to delete.
  397.          */
  398.         do_action( 'delete_postmeta', $meta_ids );
  399.     }
  400.  
  401.     $query = "DELETE FROM $table WHERE $id_column IN( " . implode( ',', $meta_ids ) . " )";
  402.  
  403.     $count = $wpdb->query($query);
  404.  
  405.     if ( !$count )
  406.         return false;
  407.  
  408.     if ( $delete_all ) {
  409.         foreach ( (array) $object_ids as $o_id ) {
  410.             wp_cache_delete($o_id, $meta_type . '_meta');
  411.         }
  412.     } else {
  413.         wp_cache_delete($object_id, $meta_type . '_meta');
  414.     }
  415.  
  416.     /**
  417.      * Fires immediately after deleting metadata of a specific type.
  418.      *
  419.      * The dynamic portion of the hook name, `$meta_type`, refers to the meta
  420.      * object type (comment, post, or user).
  421.      *
  422.      * @since 2.9.0
  423.      *
  424.      * @param array  $meta_ids   An array of deleted metadata entry IDs.
  425.      * @param int    $object_id  Object ID.
  426.      * @param string $meta_key   Meta key.
  427.      * @param mixed  $meta_value Meta value.
  428.      */
  429.     do_action( "deleted_{$meta_type}_meta", $meta_ids, $object_id, $meta_key, $_meta_value );
  430.  
  431.     // Old-style action.
  432.     if ( 'post' == $meta_type ) {
  433.         /**
  434.          * Fires immediately after deleting metadata for a post.
  435.          *
  436.          * @since 2.9.0
  437.          *
  438.          * @param array $meta_ids An array of deleted post metadata entry IDs.
  439.          */
  440.         do_action( 'deleted_postmeta', $meta_ids );
  441.     }
  442.  
  443.     return true;
  444. }
  445.  
  446. /**
  447.  * Retrieve metadata for the specified object.
  448.  *
  449.  * @since 2.9.0
  450.  *
  451.  * @param string $meta_type Type of object metadata is for (e.g., comment, post, or user)
  452.  * @param int    $object_id ID of the object metadata is for
  453.  * @param string $meta_key  Optional. Metadata key. If not specified, retrieve all metadata for
  454.  *                             the specified object.
  455.  * @param bool   $single    Optional, default is false.
  456.  *                          If true, return only the first value of the specified meta_key.
  457.  *                          This parameter has no effect if meta_key is not specified.
  458.  * @return mixed Single metadata value, or array of values
  459.  */
  460. function get_metadata($meta_type, $object_id, $meta_key = '', $single = false) {
  461.     if ( ! $meta_type || ! is_numeric( $object_id ) ) {
  462.         return false;
  463.     }
  464.  
  465.     $object_id = absint( $object_id );
  466.     if ( ! $object_id ) {
  467.         return false;
  468.     }
  469.  
  470.     /**
  471.      * Filters whether to retrieve metadata of a specific type.
  472.      *
  473.      * The dynamic portion of the hook, `$meta_type`, refers to the meta
  474.      * object type (comment, post, or user). Returning a non-null value
  475.      * will effectively short-circuit the function.
  476.      *
  477.      * @since 3.1.0
  478.      *
  479.      * @param null|array|string $value     The value get_metadata() should return - a single metadata value,
  480.      *                                     or an array of values.
  481.      * @param int               $object_id Object ID.
  482.      * @param string            $meta_key  Meta key.
  483.      * @param bool              $single    Whether to return only the first value of the specified $meta_key.
  484.      */
  485.     $check = apply_filters( "get_{$meta_type}_metadata", null, $object_id, $meta_key, $single );
  486.     if ( null !== $check ) {
  487.         if ( $single && is_array( $check ) )
  488.             return $check[0];
  489.         else
  490.             return $check;
  491.     }
  492.  
  493.     $meta_cache = wp_cache_get($object_id, $meta_type . '_meta');
  494.  
  495.     if ( !$meta_cache ) {
  496.         $meta_cache = update_meta_cache( $meta_type, array( $object_id ) );
  497.         $meta_cache = $meta_cache[$object_id];
  498.     }
  499.  
  500.     if ( ! $meta_key ) {
  501.         return $meta_cache;
  502.     }
  503.  
  504.     if ( isset($meta_cache[$meta_key]) ) {
  505.         if ( $single )
  506.             return maybe_unserialize( $meta_cache[$meta_key][0] );
  507.         else
  508.             return array_map('maybe_unserialize', $meta_cache[$meta_key]);
  509.     }
  510.  
  511.     if ($single)
  512.         return '';
  513.     else
  514.         return array();
  515. }
  516.  
  517. /**
  518.  * Determine if a meta key is set for a given object
  519.  *
  520.  * @since 3.3.0
  521.  *
  522.  * @param string $meta_type Type of object metadata is for (e.g., comment, post, or user)
  523.  * @param int    $object_id ID of the object metadata is for
  524.  * @param string $meta_key  Metadata key.
  525.  * @return bool True of the key is set, false if not.
  526.  */
  527. function metadata_exists( $meta_type, $object_id, $meta_key ) {
  528.     if ( ! $meta_type || ! is_numeric( $object_id ) ) {
  529.         return false;
  530.     }
  531.  
  532.     $object_id = absint( $object_id );
  533.     if ( ! $object_id ) {
  534.         return false;
  535.     }
  536.  
  537.     /** This filter is documented in wp-includes/meta.php */
  538.     $check = apply_filters( "get_{$meta_type}_metadata", null, $object_id, $meta_key, true );
  539.     if ( null !== $check )
  540.         return (bool) $check;
  541.  
  542.     $meta_cache = wp_cache_get( $object_id, $meta_type . '_meta' );
  543.  
  544.     if ( !$meta_cache ) {
  545.         $meta_cache = update_meta_cache( $meta_type, array( $object_id ) );
  546.         $meta_cache = $meta_cache[$object_id];
  547.     }
  548.  
  549.     if ( isset( $meta_cache[ $meta_key ] ) )
  550.         return true;
  551.  
  552.     return false;
  553. }
  554.  
  555. /**
  556.  * Get meta data by meta ID
  557.  *
  558.  * @since 3.3.0
  559.  *
  560.  * @global wpdb $wpdb WordPress database abstraction object.
  561.  *
  562.  * @param string $meta_type Type of object metadata is for (e.g., comment, post, term, or user).
  563.  * @param int    $meta_id   ID for a specific meta row
  564.  * @return object|false Meta object or false.
  565.  */
  566. function get_metadata_by_mid( $meta_type, $meta_id ) {
  567.     global $wpdb;
  568.  
  569.     if ( ! $meta_type || ! is_numeric( $meta_id ) || floor( $meta_id ) != $meta_id ) {
  570.         return false;
  571.     }
  572.  
  573.     $meta_id = intval( $meta_id );
  574.     if ( $meta_id <= 0 ) {
  575.         return false;
  576.     }
  577.  
  578.     $table = _get_meta_table( $meta_type );
  579.     if ( ! $table ) {
  580.         return false;
  581.     }
  582.  
  583.     $id_column = ( 'user' == $meta_type ) ? 'umeta_id' : 'meta_id';
  584.  
  585.     $meta = $wpdb->get_row( $wpdb->prepare( "SELECT * FROM $table WHERE $id_column = %d", $meta_id ) );
  586.  
  587.     if ( empty( $meta ) )
  588.         return false;
  589.  
  590.     if ( isset( $meta->meta_value ) )
  591.         $meta->meta_value = maybe_unserialize( $meta->meta_value );
  592.  
  593.     return $meta;
  594. }
  595.  
  596. /**
  597.  * Update meta data by meta ID
  598.  *
  599.  * @since 3.3.0
  600.  *
  601.  * @global wpdb $wpdb WordPress database abstraction object.
  602.  *
  603.  * @param string $meta_type  Type of object metadata is for (e.g., comment, post, or user)
  604.  * @param int    $meta_id    ID for a specific meta row
  605.  * @param string $meta_value Metadata value
  606.  * @param string $meta_key   Optional, you can provide a meta key to update it
  607.  * @return bool True on successful update, false on failure.
  608.  */
  609. function update_metadata_by_mid( $meta_type, $meta_id, $meta_value, $meta_key = false ) {
  610.     global $wpdb;
  611.  
  612.     // Make sure everything is valid.
  613.     if ( ! $meta_type || ! is_numeric( $meta_id ) || floor( $meta_id ) != $meta_id ) {
  614.         return false;
  615.     }
  616.  
  617.     $meta_id = intval( $meta_id );
  618.     if ( $meta_id <= 0 ) {
  619.         return false;
  620.     }
  621.  
  622.     $table = _get_meta_table( $meta_type );
  623.     if ( ! $table ) {
  624.         return false;
  625.     }
  626.  
  627.     $column = sanitize_key($meta_type . '_id');
  628.     $id_column = 'user' == $meta_type ? 'umeta_id' : 'meta_id';
  629.  
  630.     // Fetch the meta and go on if it's found.
  631.     if ( $meta = get_metadata_by_mid( $meta_type, $meta_id ) ) {
  632.         $original_key = $meta->meta_key;
  633.         $object_id = $meta->{$column};
  634.  
  635.         // If a new meta_key (last parameter) was specified, change the meta key,
  636.         // otherwise use the original key in the update statement.
  637.         if ( false === $meta_key ) {
  638.             $meta_key = $original_key;
  639.         } elseif ( ! is_string( $meta_key ) ) {
  640.             return false;
  641.         }
  642.  
  643.         // Sanitize the meta
  644.         $_meta_value = $meta_value;
  645.         $meta_value = sanitize_meta( $meta_key, $meta_value, $meta_type );
  646.         $meta_value = maybe_serialize( $meta_value );
  647.  
  648.         // Format the data query arguments.
  649.         $data = array(
  650.             'meta_key' => $meta_key,
  651.             'meta_value' => $meta_value
  652.         );
  653.  
  654.         // Format the where query arguments.
  655.         $where = array();
  656.         $where[$id_column] = $meta_id;
  657.  
  658.         /** This action is documented in wp-includes/meta.php */
  659.         do_action( "update_{$meta_type}_meta", $meta_id, $object_id, $meta_key, $_meta_value );
  660.  
  661.         if ( 'post' == $meta_type ) {
  662.             /** This action is documented in wp-includes/meta.php */
  663.             do_action( 'update_postmeta', $meta_id, $object_id, $meta_key, $meta_value );
  664.         }
  665.  
  666.         // Run the update query, all fields in $data are %s, $where is a %d.
  667.         $result = $wpdb->update( $table, $data, $where, '%s', '%d' );
  668.         if ( ! $result )
  669.             return false;
  670.  
  671.         // Clear the caches.
  672.         wp_cache_delete($object_id, $meta_type . '_meta');
  673.  
  674.         /** This action is documented in wp-includes/meta.php */
  675.         do_action( "updated_{$meta_type}_meta", $meta_id, $object_id, $meta_key, $_meta_value );
  676.  
  677.         if ( 'post' == $meta_type ) {
  678.             /** This action is documented in wp-includes/meta.php */
  679.             do_action( 'updated_postmeta', $meta_id, $object_id, $meta_key, $meta_value );
  680.         }
  681.  
  682.         return true;
  683.     }
  684.  
  685.     // And if the meta was not found.
  686.     return false;
  687. }
  688.  
  689. /**
  690.  * Delete meta data by meta ID
  691.  *
  692.  * @since 3.3.0
  693.  *
  694.  * @global wpdb $wpdb WordPress database abstraction object.
  695.  *
  696.  * @param string $meta_type Type of object metadata is for (e.g., comment, post, term, or user).
  697.  * @param int    $meta_id   ID for a specific meta row
  698.  * @return bool True on successful delete, false on failure.
  699.  */
  700. function delete_metadata_by_mid( $meta_type, $meta_id ) {
  701.     global $wpdb;
  702.  
  703.     // Make sure everything is valid.
  704.     if ( ! $meta_type || ! is_numeric( $meta_id ) || floor( $meta_id ) != $meta_id ) {
  705.         return false;
  706.     }
  707.  
  708.     $meta_id = intval( $meta_id );
  709.     if ( $meta_id <= 0 ) {
  710.         return false;
  711.     }
  712.  
  713.     $table = _get_meta_table( $meta_type );
  714.     if ( ! $table ) {
  715.         return false;
  716.     }
  717.  
  718.     // object and id columns
  719.     $column = sanitize_key($meta_type . '_id');
  720.     $id_column = 'user' == $meta_type ? 'umeta_id' : 'meta_id';
  721.  
  722.     // Fetch the meta and go on if it's found.
  723.     if ( $meta = get_metadata_by_mid( $meta_type, $meta_id ) ) {
  724.         $object_id = $meta->{$column};
  725.  
  726.         /** This action is documented in wp-includes/meta.php */
  727.         do_action( "delete_{$meta_type}_meta", (array) $meta_id, $object_id, $meta->meta_key, $meta->meta_value );
  728.  
  729.         // Old-style action.
  730.         if ( 'post' == $meta_type || 'comment' == $meta_type ) {
  731.             /**
  732.              * Fires immediately before deleting post or comment metadata of a specific type.
  733.              *
  734.              * The dynamic portion of the hook, `$meta_type`, refers to the meta
  735.              * object type (post or comment).
  736.              *
  737.              * @since 3.4.0
  738.              *
  739.              * @param int $meta_id ID of the metadata entry to delete.
  740.              */
  741.             do_action( "delete_{$meta_type}meta", $meta_id );
  742.         }
  743.  
  744.         // Run the query, will return true if deleted, false otherwise
  745.         $result = (bool) $wpdb->delete( $table, array( $id_column => $meta_id ) );
  746.  
  747.         // Clear the caches.
  748.         wp_cache_delete($object_id, $meta_type . '_meta');
  749.  
  750.         /** This action is documented in wp-includes/meta.php */
  751.         do_action( "deleted_{$meta_type}_meta", (array) $meta_id, $object_id, $meta->meta_key, $meta->meta_value );
  752.  
  753.         // Old-style action.
  754.         if ( 'post' == $meta_type || 'comment' == $meta_type ) {
  755.             /**
  756.              * Fires immediately after deleting post or comment metadata of a specific type.
  757.              *
  758.              * The dynamic portion of the hook, `$meta_type`, refers to the meta
  759.              * object type (post or comment).
  760.              *
  761.              * @since 3.4.0
  762.              *
  763.              * @param int $meta_ids Deleted metadata entry ID.
  764.              */
  765.             do_action( "deleted_{$meta_type}meta", $meta_id );
  766.         }
  767.  
  768.         return $result;
  769.  
  770.     }
  771.  
  772.     // Meta id was not found.
  773.     return false;
  774. }
  775.  
  776. /**
  777.  * Update the metadata cache for the specified objects.
  778.  *
  779.  * @since 2.9.0
  780.  *
  781.  * @global wpdb $wpdb WordPress database abstraction object.
  782.  *
  783.  * @param string    $meta_type  Type of object metadata is for (e.g., comment, post, or user)
  784.  * @param int|array $object_ids Array or comma delimited list of object IDs to update cache for
  785.  * @return array|false Metadata cache for the specified objects, or false on failure.
  786.  */
  787. function update_meta_cache($meta_type, $object_ids) {
  788.     global $wpdb;
  789.  
  790.     if ( ! $meta_type || ! $object_ids ) {
  791.         return false;
  792.     }
  793.  
  794.     $table = _get_meta_table( $meta_type );
  795.     if ( ! $table ) {
  796.         return false;
  797.     }
  798.  
  799.     $column = sanitize_key($meta_type . '_id');
  800.  
  801.     if ( !is_array($object_ids) ) {
  802.         $object_ids = preg_replace('|[^0-9,]|', '', $object_ids);
  803.         $object_ids = explode(',', $object_ids);
  804.     }
  805.  
  806.     $object_ids = array_map('intval', $object_ids);
  807.  
  808.     $cache_key = $meta_type . '_meta';
  809.     $ids = array();
  810.     $cache = array();
  811.     foreach ( $object_ids as $id ) {
  812.         $cached_object = wp_cache_get( $id, $cache_key );
  813.         if ( false === $cached_object )
  814.             $ids[] = $id;
  815.         else
  816.             $cache[$id] = $cached_object;
  817.     }
  818.  
  819.     if ( empty( $ids ) )
  820.         return $cache;
  821.  
  822.     // Get meta info
  823.     $id_list = join( ',', $ids );
  824.     $id_column = 'user' == $meta_type ? 'umeta_id' : 'meta_id';
  825.     $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 );
  826.  
  827.     if ( !empty($meta_list) ) {
  828.         foreach ( $meta_list as $metarow) {
  829.             $mpid = intval($metarow[$column]);
  830.             $mkey = $metarow['meta_key'];
  831.             $mval = $metarow['meta_value'];
  832.  
  833.             // Force subkeys to be array type:
  834.             if ( !isset($cache[$mpid]) || !is_array($cache[$mpid]) )
  835.                 $cache[$mpid] = array();
  836.             if ( !isset($cache[$mpid][$mkey]) || !is_array($cache[$mpid][$mkey]) )
  837.                 $cache[$mpid][$mkey] = array();
  838.  
  839.             // Add a value to the current pid/key:
  840.             $cache[$mpid][$mkey][] = $mval;
  841.         }
  842.     }
  843.  
  844.     foreach ( $ids as $id ) {
  845.         if ( ! isset($cache[$id]) )
  846.             $cache[$id] = array();
  847.         wp_cache_add( $id, $cache[$id], $cache_key );
  848.     }
  849.  
  850.     return $cache;
  851. }
  852.  
  853. /**
  854.  * Retrieves the queue for lazy-loading metadata.
  855.  *
  856.  * @since 4.5.0
  857.  *
  858.  * @return WP_Metadata_Lazyloader $lazyloader Metadata lazyloader queue.
  859.  */
  860. function wp_metadata_lazyloader() {
  861.     static $wp_metadata_lazyloader;
  862.  
  863.     if ( null === $wp_metadata_lazyloader ) {
  864.         $wp_metadata_lazyloader = new WP_Metadata_Lazyloader();
  865.     }
  866.  
  867.     return $wp_metadata_lazyloader;
  868. }
  869.  
  870. /**
  871.  * Given a meta query, generates SQL clauses to be appended to a main query.
  872.  *
  873.  * @since 3.2.0
  874.  *
  875.  * @see WP_Meta_Query
  876.  *
  877.  * @param array $meta_query         A meta query.
  878.  * @param string $type              Type of meta.
  879.  * @param string $primary_table     Primary database table name.
  880.  * @param string $primary_id_column Primary ID column name.
  881.  * @param object $context           Optional. The main query object
  882.  * @return array Associative array of `JOIN` and `WHERE` SQL.
  883.  */
  884. function get_meta_sql( $meta_query, $type, $primary_table, $primary_id_column, $context = null ) {
  885.     $meta_query_obj = new WP_Meta_Query( $meta_query );
  886.     return $meta_query_obj->get_sql( $type, $primary_table, $primary_id_column, $context );
  887. }
  888.  
  889. /**
  890.  * Retrieve the name of the metadata table for the specified object type.
  891.  *
  892.  * @since 2.9.0
  893.  *
  894.  * @global wpdb $wpdb WordPress database abstraction object.
  895.  *
  896.  * @param string $type Type of object to get metadata table for (e.g., comment, post, or user)
  897.  * @return string|false Metadata table name, or false if no metadata table exists
  898.  */
  899. function _get_meta_table($type) {
  900.     global $wpdb;
  901.  
  902.     $table_name = $type . 'meta';
  903.  
  904.     if ( empty($wpdb->$table_name) )
  905.         return false;
  906.  
  907.     return $wpdb->$table_name;
  908. }
  909.  
  910. /**
  911.  * Determine whether a meta key is protected.
  912.  *
  913.  * @since 3.1.3
  914.  *
  915.  * @param string      $meta_key Meta key
  916.  * @param string|null $meta_type
  917.  * @return bool True if the key is protected, false otherwise.
  918.  */
  919. function is_protected_meta( $meta_key, $meta_type = null ) {
  920.     $protected = ( '_' == $meta_key[0] );
  921.  
  922.     /**
  923.      * Filters whether a meta key is protected.
  924.      *
  925.      * @since 3.2.0
  926.      *
  927.      * @param bool   $protected Whether the key is protected. Default false.
  928.      * @param string $meta_key  Meta key.
  929.      * @param string $meta_type Meta type.
  930.      */
  931.     return apply_filters( 'is_protected_meta', $protected, $meta_key, $meta_type );
  932. }
  933.  
  934. /**
  935.  * Sanitize meta value.
  936.  *
  937.  * @since 3.1.3
  938.  *
  939.  * @param string $meta_key       Meta key.
  940.  * @param mixed  $meta_value     Meta value to sanitize.
  941.  * @param string $object_type    Type of object the meta is registered to.
  942.  *
  943.  * @return mixed Sanitized $meta_value.
  944.  */
  945. function sanitize_meta( $meta_key, $meta_value, $object_type ) {
  946.     /**
  947.      * Filters the sanitization of a specific meta key of a specific meta type.
  948.      *
  949.      * The dynamic portions of the hook name, `$meta_type`, and `$meta_key`,
  950.      * refer to the metadata object type (comment, post, or user) and the meta
  951.      * key value, respectively.
  952.      *
  953.      * @since 3.3.0
  954.      *
  955.      * @param mixed  $meta_value      Meta value to sanitize.
  956.      * @param string $meta_key        Meta key.
  957.      * @param string $object_type     Object type.
  958.      */
  959.     return apply_filters( "sanitize_{$object_type}_meta_{$meta_key}", $meta_value, $meta_key, $object_type );
  960. }
  961.  
  962. /**
  963.  * Registers a meta key.
  964.  *
  965.  * @since 3.3.0
  966.  * @since 4.6.0 {@link https://core.trac.wordpress.org/ticket/35658 Modified
  967.  *              to support an array of data to attach to registered meta keys}. Previous arguments for
  968.  *              `$sanitize_callback` and `$auth_callback` have been folded into this array.
  969.  *
  970.  * @param string $object_type    Type of object this meta is registered to.
  971.  * @param string $meta_key       Meta key to register.
  972.  * @param array  $args {
  973.  *     Data used to describe the meta key when registered.
  974.  *
  975.  *     @type string $type              The type of data associated with this meta key.
  976.  *                                     Valid values are 'string', 'boolean', 'integer', and 'number'.
  977.  *     @type string $description       A description of the data attached to this meta key.
  978.  *     @type bool   $single            Whether the meta key has one value per object, or an array of values per object.
  979.  *     @type string $sanitize_callback A function or method to call when sanitizing `$meta_key` data.
  980.  *     @type string $auth_callback     Optional. A function or method to call when performing edit_post_meta, add_post_meta, and delete_post_meta capability checks.
  981.  *     @type bool   $show_in_rest      Whether data associated with this meta key can be considered public.
  982.  * }
  983.  * @param string|array $deprecated Deprecated. Use `$args` instead.
  984.  *
  985.  * @return bool True if the meta key was successfully registered in the global array, false if not.
  986.  *                       Registering a meta key with distinct sanitize and auth callbacks will fire those
  987.  *                       callbacks, but will not add to the global registry.
  988.  */
  989. function register_meta( $object_type, $meta_key, $args, $deprecated = null ) {
  990.     global $wp_meta_keys;
  991.  
  992.     if ( ! is_array( $wp_meta_keys ) ) {
  993.         $wp_meta_keys = array();
  994.     }
  995.  
  996.     $defaults = array(
  997.         'type'              => 'string',
  998.         'description'       => '',
  999.         'single'            => false,
  1000.         'sanitize_callback' => null,
  1001.         'auth_callback'     => null,
  1002.         'show_in_rest'      => false,
  1003.     );
  1004.  
  1005.     // There used to be individual args for sanitize and auth callbacks
  1006.     $has_old_sanitize_cb = false;
  1007.     $has_old_auth_cb = false;
  1008.  
  1009.     if ( is_callable( $args ) ) {
  1010.         $args = array(
  1011.             'sanitize_callback' => $args,
  1012.         );
  1013.  
  1014.         $has_old_sanitize_cb = true;
  1015.     } else {
  1016.         $args = (array) $args;
  1017.     }
  1018.  
  1019.     if ( is_callable( $deprecated ) ) {
  1020.         $args['auth_callback'] = $deprecated;
  1021.         $has_old_auth_cb = true;
  1022.     }
  1023.  
  1024.     /**
  1025.      * Filters the registration arguments when registering meta.
  1026.      *
  1027.      * @since 4.6.0
  1028.      *
  1029.      * @param array  $args        Array of meta registration arguments.
  1030.      * @param array  $defaults    Array of default arguments.
  1031.      * @param string $object_type Object type.
  1032.      * @param string $meta_key    Meta key.
  1033.      */
  1034.     $args = apply_filters( 'register_meta_args', $args, $defaults, $object_type, $meta_key );
  1035.     $args = wp_parse_args( $args, $defaults );
  1036.  
  1037.     // If `auth_callback` is not provided, fall back to `is_protected_meta()`.
  1038.     if ( empty( $args['auth_callback'] ) ) {
  1039.         if ( is_protected_meta( $meta_key, $object_type ) ) {
  1040.             $args['auth_callback'] = '__return_false';
  1041.         } else {
  1042.             $args['auth_callback'] = '__return_true';
  1043.         }
  1044.     }
  1045.  
  1046.     // Back-compat: old sanitize and auth callbacks are applied to all of an object type.
  1047.     if ( is_callable( $args['sanitize_callback'] ) ) {
  1048.         add_filter( "sanitize_{$object_type}_meta_{$meta_key}", $args['sanitize_callback'], 10, 3 );
  1049.     }
  1050.  
  1051.     if ( is_callable( $args['auth_callback'] ) ) {
  1052.         add_filter( "auth_{$object_type}_meta_{$meta_key}", $args['auth_callback'], 10, 6 );
  1053.     }
  1054.  
  1055.     // Global registry only contains meta keys registered with the array of arguments added in 4.6.0.
  1056.     if ( ! $has_old_auth_cb && ! $has_old_sanitize_cb ) {
  1057.         $wp_meta_keys[ $object_type ][ $meta_key ] = $args;
  1058.  
  1059.         return true;
  1060.     }
  1061.  
  1062.     return false;
  1063. }
  1064.  
  1065. /**
  1066.  * Checks if a meta key is registered.
  1067.  *
  1068.  * @since 4.6.0
  1069.  *
  1070.  * @param string $object_type    The type of object.
  1071.  * @param string $meta_key       The meta key.
  1072.  *
  1073.  * @return bool True if the meta key is registered to the object type. False if not.
  1074.  */
  1075. function registered_meta_key_exists( $object_type, $meta_key ) {
  1076.     global $wp_meta_keys;
  1077.  
  1078.     if ( ! is_array( $wp_meta_keys ) ) {
  1079.         return false;
  1080.     }
  1081.  
  1082.     if ( ! isset( $wp_meta_keys[ $object_type ] ) ) {
  1083.         return false;
  1084.     }
  1085.  
  1086.     if ( isset( $wp_meta_keys[ $object_type ][ $meta_key ] ) ) {
  1087.         return true;
  1088.     }
  1089.  
  1090.     return false;
  1091. }
  1092.  
  1093. /**
  1094.  * Unregisters a meta key from the list of registered keys.
  1095.  *
  1096.  * @since 4.6.0
  1097.  *
  1098.  * @param string $object_type The type of object.
  1099.  * @param string $meta_key    The meta key.
  1100.  * @return bool True if successful. False if the meta key was not registered.
  1101.  */
  1102. function unregister_meta_key( $object_type, $meta_key ) {
  1103.     global $wp_meta_keys;
  1104.  
  1105.     if ( ! registered_meta_key_exists( $object_type, $meta_key ) ) {
  1106.         return false;
  1107.     }
  1108.  
  1109.     $args = $wp_meta_keys[ $object_type ][ $meta_key ];
  1110.  
  1111.     if ( isset( $args['sanitize_callback'] ) && is_callable( $args['sanitize_callback'] ) ) {
  1112.         remove_filter( "sanitize_{$object_type}_meta_{$meta_key}", $args['sanitize_callback'] );
  1113.     }
  1114.  
  1115.     if ( isset( $args['auth_callback'] ) && is_callable( $args['auth_callback'] ) ) {
  1116.         remove_filter( "auth_{$object_type}_meta_{$meta_key}", $args['auth_callback'] );
  1117.     }
  1118.  
  1119.     unset( $wp_meta_keys[ $object_type ][ $meta_key ] );
  1120.  
  1121.     // Do some clean up
  1122.     if ( empty( $wp_meta_keys[ $object_type ] ) ) {
  1123.         unset( $wp_meta_keys[ $object_type ] );
  1124.     }
  1125.  
  1126.     return true;
  1127. }
  1128.  
  1129. /**
  1130.  * Retrieves a list of registered meta keys for an object type.
  1131.  *
  1132.  * @since 4.6.0
  1133.  *
  1134.  * @param string $object_type The type of object. Post, comment, user, term.
  1135.  * @return array List of registered meta keys.
  1136.  */
  1137. function get_registered_meta_keys( $object_type ) {
  1138.     global $wp_meta_keys;
  1139.  
  1140.     if ( ! is_array( $wp_meta_keys ) || ! isset( $wp_meta_keys[ $object_type ] ) ) {
  1141.         return array();
  1142.     }
  1143.  
  1144.     return $wp_meta_keys[ $object_type ];
  1145. }
  1146.  
  1147. /**
  1148.  * Retrieves registered metadata for a specified object.
  1149.  *
  1150.  * @since 4.6.0
  1151.  *
  1152.  * @param string $object_type Type of object to request metadata for. (e.g. comment, post, term, user)
  1153.  * @param int    $object_id   ID of the object the metadata is for.
  1154.  * @param string $meta_key    Optional. Registered metadata key. If not specified, retrieve all registered
  1155.  *                            metadata for the specified object.
  1156.  * @return mixed A single value or array of values for a key if specified. An array of all registered keys
  1157.  *               and values for an object ID if not.
  1158.  */
  1159. function get_registered_metadata( $object_type, $object_id, $meta_key = '' ) {
  1160.     if ( ! empty( $meta_key ) ) {
  1161.         if ( ! registered_meta_key_exists( $object_type, $meta_key ) ) {
  1162.             return false;
  1163.         }
  1164.         $meta_keys = get_registered_meta_keys( $object_type );
  1165.         $meta_key_data = $meta_keys[ $meta_key ];
  1166.  
  1167.         $data = get_metadata( $object_type, $object_id, $meta_key, $meta_key_data['single'] );
  1168.  
  1169.         return $data;
  1170.     }
  1171.  
  1172.     $data = get_metadata( $object_type, $object_id );
  1173.  
  1174.     $meta_keys = get_registered_meta_keys( $object_type );
  1175.     $registered_data = array();
  1176.  
  1177.     // Someday, array_filter()
  1178.     foreach ( $meta_keys as $k => $v ) {
  1179.         if ( isset( $data[ $k ] ) ) {
  1180.             $registered_data[ $k ] = $data[ $k ];
  1181.         }
  1182.     }
  1183.  
  1184.     return $registered_data;
  1185. }
  1186.  
  1187. /**
  1188.  * Filter out `register_meta()` args based on a whitelist.
  1189.  * `register_meta()` args may change over time, so requiring the whitelist
  1190.  * to be explicitly turned off is a warranty seal of sorts.
  1191.  *
  1192.  * @access private
  1193.  * @since  4.6.0
  1194.  *
  1195.  * @param  array $args         Arguments from `register_meta()`.
  1196.  * @param  array $default_args Default arguments for `register_meta()`.
  1197.  *
  1198.  * @return array Filtered arguments.
  1199.  */
  1200. function _wp_register_meta_args_whitelist( $args, $default_args ) {
  1201.     $whitelist = array_keys( $default_args );
  1202.  
  1203.     // In an anonymous function world, this would be better as an array_filter()
  1204.     foreach ( $args as $key => $value ) {
  1205.         if ( ! in_array( $key, $whitelist ) ) {
  1206.             unset( $args[ $key ] );
  1207.         }
  1208.     }
  1209.  
  1210.     return $args;
  1211. }
  1212.