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.
15 * Add metadata for the specified object.
18 * @uses $wpdb WordPress database object for queries.
19 * @uses do_action() Calls 'added_{$meta_type}_meta' with meta_id of added metadata entry,
20 * object ID, meta key, and meta value
22 * @param string $meta_type Type of object metadata is for (e.g., comment, post, or user)
23 * @param int $object_id ID of the object metadata is for
24 * @param string $meta_key Metadata key
25 * @param string $meta_value Metadata value
26 * @param bool $unique Optional, default is false. Whether the specified metadata key should be
27 * unique for the object. If true, and the object already has a value for the specified
28 * metadata key, no change will be made
29 * @return bool True on successful update, false on failure.
31 function add_metadata($meta_type, $object_id, $meta_key, $meta_value, $unique = false) {
32 if ( !$meta_type || !$meta_key )
35 if ( !$object_id = absint($object_id) )
38 if ( ! $table = _get_meta_table($meta_type) )
43 $column = esc_sql($meta_type . '_id');
45 // expected_slashed ($meta_key)
46 $meta_key = stripslashes($meta_key);
47 $meta_value = stripslashes_deep($meta_value);
48 $meta_value = sanitize_meta( $meta_key, $meta_value, $meta_type );
50 $check = apply_filters( "add_{$meta_type}_metadata", null, $object_id, $meta_key, $meta_value, $unique );
51 if ( null !== $check )
54 if ( $unique && $wpdb->get_var( $wpdb->prepare(
55 "SELECT COUNT(*) FROM $table WHERE meta_key = %s AND $column = %d",
56 $meta_key, $object_id ) ) )
59 $_meta_value = $meta_value;
60 $meta_value = maybe_serialize( $meta_value );
62 do_action( "add_{$meta_type}_meta", $object_id, $meta_key, $_meta_value );
64 $wpdb->insert( $table, array(
65 $column => $object_id,
66 'meta_key' => $meta_key,
67 'meta_value' => $meta_value
70 wp_cache_delete($object_id, $meta_type . '_meta');
71 // users cache stores usermeta that must be cleared.
72 if ( 'user' == $meta_type )
73 clean_user_cache($object_id);
75 do_action( "added_{$meta_type}_meta", $wpdb->insert_id, $object_id, $meta_key, $_meta_value );
81 * Update metadata for the specified object. If no value already exists for the specified object
82 * ID and metadata key, the metadata will be added.
85 * @uses $wpdb WordPress database object for queries.
86 * @uses do_action() Calls 'update_{$meta_type}_meta' before updating metadata with meta_id of
87 * metadata entry to update, object ID, meta key, and meta value
88 * @uses do_action() Calls 'updated_{$meta_type}_meta' after updating metadata with meta_id of
89 * updated metadata entry, object ID, meta key, and meta value
91 * @param string $meta_type Type of object metadata is for (e.g., comment, post, or user)
92 * @param int $object_id ID of the object metadata is for
93 * @param string $meta_key Metadata key
94 * @param string $meta_value Metadata value
95 * @param string $prev_value Optional. If specified, only update existing metadata entries with
96 * the specified value. Otherwise, update all entries.
97 * @return bool True on successful update, false on failure.
99 function update_metadata($meta_type, $object_id, $meta_key, $meta_value, $prev_value = '') {
100 if ( !$meta_type || !$meta_key )
103 if ( !$object_id = absint($object_id) )
106 if ( ! $table = _get_meta_table($meta_type) )
111 $column = esc_sql($meta_type . '_id');
112 $id_column = 'user' == $meta_type ? 'umeta_id' : 'meta_id';
114 // expected_slashed ($meta_key)
115 $meta_key = stripslashes($meta_key);
116 $meta_value = stripslashes_deep($meta_value);
117 $meta_value = sanitize_meta( $meta_key, $meta_value, $meta_type );
119 $check = apply_filters( "update_{$meta_type}_metadata", null, $object_id, $meta_key, $meta_value, $prev_value );
120 if ( null !== $check )
121 return (bool) $check;
123 if ( ! $meta_id = $wpdb->get_var( $wpdb->prepare( "SELECT $id_column FROM $table WHERE meta_key = %s AND $column = %d", $meta_key, $object_id ) ) )
124 return add_metadata($meta_type, $object_id, $meta_key, $meta_value);
126 // Compare existing value to new value if no prev value given and the key exists only once.
127 if ( empty($prev_value) ) {
128 $old_value = get_metadata($meta_type, $object_id, $meta_key);
129 if ( count($old_value) == 1 ) {
130 if ( $old_value[0] === $meta_value )
135 $_meta_value = $meta_value;
136 $meta_value = maybe_serialize( $meta_value );
138 $data = compact( 'meta_value' );
139 $where = array( $column => $object_id, 'meta_key' => $meta_key );
141 if ( !empty( $prev_value ) ) {
142 $prev_value = maybe_serialize($prev_value);
143 $where['meta_value'] = $prev_value;
146 do_action( "update_{$meta_type}_meta", $meta_id, $object_id, $meta_key, $_meta_value );
148 $wpdb->update( $table, $data, $where );
149 wp_cache_delete($object_id, $meta_type . '_meta');
150 // users cache stores usermeta that must be cleared.
151 if ( 'user' == $meta_type )
152 clean_user_cache($object_id);
154 do_action( "updated_{$meta_type}_meta", $meta_id, $object_id, $meta_key, $_meta_value );
160 * Delete metadata for the specified object.
163 * @uses $wpdb WordPress database object for queries.
164 * @uses do_action() Calls 'deleted_{$meta_type}_meta' after deleting with meta_id of
165 * deleted metadata entries, object ID, meta key, and meta value
167 * @param string $meta_type Type of object metadata is for (e.g., comment, post, or user)
168 * @param int $object_id ID of the object metadata is for
169 * @param string $meta_key Metadata key
170 * @param string $meta_value Optional. Metadata value. If specified, only delete metadata entries
171 * with this value. Otherwise, delete all entries with the specified meta_key.
172 * @param bool $delete_all Optional, default is false. If true, delete matching metadata entries
173 * for all objects, ignoring the specified object_id. Otherwise, only delete matching
174 * metadata entries for the specified object_id.
175 * @return bool True on successful delete, false on failure.
177 function delete_metadata($meta_type, $object_id, $meta_key, $meta_value = '', $delete_all = false) {
178 if ( !$meta_type || !$meta_key )
181 if ( (!$object_id = absint($object_id)) && !$delete_all )
184 if ( ! $table = _get_meta_table($meta_type) )
189 $type_column = esc_sql($meta_type . '_id');
190 $id_column = 'user' == $meta_type ? 'umeta_id' : 'meta_id';
191 // expected_slashed ($meta_key)
192 $meta_key = stripslashes($meta_key);
193 $meta_value = stripslashes_deep($meta_value);
195 $check = apply_filters( "delete_{$meta_type}_metadata", null, $object_id, $meta_key, $meta_value, $delete_all );
196 if ( null !== $check )
197 return (bool) $check;
199 $_meta_value = $meta_value;
200 $meta_value = maybe_serialize( $meta_value );
202 $query = $wpdb->prepare( "SELECT $id_column FROM $table WHERE meta_key = %s", $meta_key );
205 $query .= $wpdb->prepare(" AND $type_column = %d", $object_id );
208 $query .= $wpdb->prepare(" AND meta_value = %s", $meta_value );
210 $meta_ids = $wpdb->get_col( $query );
211 if ( !count( $meta_ids ) )
214 do_action( "delete_{$meta_type}_meta", $meta_ids, $object_id, $meta_key, $_meta_value );
216 $query = "DELETE FROM $table WHERE $id_column IN( " . implode( ',', $meta_ids ) . " )";
218 $count = $wpdb->query($query);
223 wp_cache_delete($object_id, $meta_type . '_meta');
224 // users cache stores usermeta that must be cleared.
225 if ( 'user' == $meta_type )
226 clean_user_cache($object_id);
228 do_action( "deleted_{$meta_type}_meta", $meta_ids, $object_id, $meta_key, $_meta_value );
234 * Retrieve metadata for the specified object.
238 * @param string $meta_type Type of object metadata is for (e.g., comment, post, or user)
239 * @param int $object_id ID of the object metadata is for
240 * @param string $meta_key Optional. Metadata key. If not specified, retrieve all metadata for
241 * the specified object.
242 * @param bool $single Optional, default is false. If true, return only the first value of the
243 * specified meta_key. This parameter has no effect if meta_key is not specified.
244 * @return string|array Single metadata value, or array of values
246 function get_metadata($meta_type, $object_id, $meta_key = '', $single = false) {
250 if ( !$object_id = absint($object_id) )
253 $check = apply_filters( "get_{$meta_type}_metadata", null, $object_id, $meta_key, $single );
254 if ( null !== $check ) {
255 if ( $single && is_array( $check ) )
261 $meta_cache = wp_cache_get($object_id, $meta_type . '_meta');
263 if ( !$meta_cache ) {
264 $meta_cache = update_meta_cache( $meta_type, array( $object_id ) );
265 $meta_cache = $meta_cache[$object_id];
271 if ( isset($meta_cache[$meta_key]) ) {
273 return maybe_unserialize( $meta_cache[$meta_key][0] );
275 return array_map('maybe_unserialize', $meta_cache[$meta_key]);
285 * Update the metadata cache for the specified objects.
288 * @uses $wpdb WordPress database object for queries.
290 * @param string $meta_type Type of object metadata is for (e.g., comment, post, or user)
291 * @param int|array $object_ids array or comma delimited list of object IDs to update cache for
292 * @return mixed Metadata cache for the specified objects, or false on failure.
294 function update_meta_cache($meta_type, $object_ids) {
295 if ( empty( $meta_type ) || empty( $object_ids ) )
298 if ( ! $table = _get_meta_table($meta_type) )
301 $column = esc_sql($meta_type . '_id');
305 if ( !is_array($object_ids) ) {
306 $object_ids = preg_replace('|[^0-9,]|', '', $object_ids);
307 $object_ids = explode(',', $object_ids);
310 $object_ids = array_map('intval', $object_ids);
312 $cache_key = $meta_type . '_meta';
315 foreach ( $object_ids as $id ) {
316 $cached_object = wp_cache_get( $id, $cache_key );
317 if ( false === $cached_object )
320 $cache[$id] = $cached_object;
327 $id_list = join(',', $ids);
328 $meta_list = $wpdb->get_results( $wpdb->prepare("SELECT $column, meta_key, meta_value FROM $table WHERE $column IN ($id_list)",
329 $meta_type), ARRAY_A );
331 if ( !empty($meta_list) ) {
332 foreach ( $meta_list as $metarow) {
333 $mpid = intval($metarow[$column]);
334 $mkey = $metarow['meta_key'];
335 $mval = $metarow['meta_value'];
337 // Force subkeys to be array type:
338 if ( !isset($cache[$mpid]) || !is_array($cache[$mpid]) )
339 $cache[$mpid] = array();
340 if ( !isset($cache[$mpid][$mkey]) || !is_array($cache[$mpid][$mkey]) )
341 $cache[$mpid][$mkey] = array();
343 // Add a value to the current pid/key:
344 $cache[$mpid][$mkey][] = $mval;
348 foreach ( $ids as $id ) {
349 if ( ! isset($cache[$id]) )
350 $cache[$id] = array();
351 wp_cache_add( $id, $cache[$id], $cache_key );
358 * Given a meta query, generates SQL clauses to be appended to a main query
363 * @param array $meta_query List of metadata queries. A single query is an associative array:
364 * - 'key' string The meta key
365 * - 'value' string|array The meta value
366 * - 'compare' (optional) string How to compare the key to the value.
367 * Possible values: '=', '!=', '>', '>=', '<', '<=', 'LIKE', 'NOT LIKE', 'IN', 'NOT IN', 'BETWEEN', 'NOT BETWEEN'.
369 * - 'type' string (optional) The type of the value.
370 * Possible values: 'NUMERIC', 'BINARY', 'CHAR', 'DATE', 'DATETIME', 'DECIMAL', 'SIGNED', 'TIME', 'UNSIGNED'.
373 * @param string $type Type of meta
374 * @param string $primary_table
375 * @param string $primary_id_column
376 * @param object $context (optional) The main query object
377 * @return array( 'join' => $join_sql, 'where' => $where_sql )
379 function _get_meta_sql( $meta_query, $type, $primary_table, $primary_id_column, $context = null ) {
382 if ( ! $meta_table = _get_meta_table( $type ) )
385 $meta_id_column = esc_sql( $type . '_id' );
390 foreach ( $meta_query as $q ) {
391 $meta_key = isset( $q['key'] ) ? trim( $q['key'] ) : '';
392 $meta_value = isset( $q['value'] ) ? $q['value'] : '';
393 $meta_compare = isset( $q['compare'] ) ? strtoupper( $q['compare'] ) : '=';
394 $meta_type = isset( $q['type'] ) ? strtoupper( $q['type'] ) : 'CHAR';
396 if ( ! in_array( $meta_compare, array( '=', '!=', '>', '>=', '<', '<=', 'LIKE', 'NOT LIKE', 'IN', 'NOT IN', 'BETWEEN', 'NOT BETWEEN' ) ) )
399 if ( 'NUMERIC' == $meta_type )
400 $meta_type = 'SIGNED';
401 elseif ( ! in_array( $meta_type, array( 'BINARY', 'CHAR', 'DATE', 'DATETIME', 'DECIMAL', 'SIGNED', 'TIME', 'UNSIGNED' ) ) )
404 if ( empty( $meta_key ) && empty( $meta_value ) )
407 $alias = $i ? 'mt' . $i : $meta_table;
409 $join .= "\nINNER JOIN $meta_table";
410 $join .= $i ? " AS $alias" : '';
411 $join .= " ON ($primary_table.$primary_id_column = $alias.$meta_id_column)";
415 if ( !empty( $meta_key ) )
416 $where .= $wpdb->prepare( " AND $alias.meta_key = %s", $meta_key );
418 if ( in_array( $meta_compare, array( 'IN', 'NOT IN', 'BETWEEN', 'NOT BETWEEN' ) ) ) {
419 if ( ! is_array( $meta_value ) )
420 $meta_value = preg_split( '/[,\s]+/', $meta_value );
422 $meta_value = trim( $meta_value );
425 if ( empty( $meta_value ) )
428 if ( 'IN' == substr( $meta_compare, -2) ) {
429 $meta_compare_string = '(' . substr( str_repeat( ',%s', count( $meta_value ) ), 1 ) . ')';
430 } elseif ( 'BETWEEN' == substr( $meta_compare, -7) ) {
431 $meta_value = array_slice( $meta_value, 0, 2 );
432 $meta_compare_string = '%s AND %s';
433 } elseif ( 'LIKE' == substr( $meta_compare, -4 ) ) {
434 $meta_value = '%' . like_escape( $meta_value ) . '%';
435 $meta_compare_string = '%s';
437 $meta_compare_string = '%s';
440 // @todo Temporary hack to support empty values. Do not use outside of core.
441 if ( '_wp_zero_value' == $meta_value )
444 $where .= $wpdb->prepare( " AND CAST($alias.meta_value AS {$meta_type}) {$meta_compare} {$meta_compare_string}", $meta_value );
447 return apply_filters_ref_array( 'get_meta_sql', array( compact( 'join', 'where' ), $meta_query, $type, $primary_table, $primary_id_column, &$context ) );
451 * Populates the $meta_query property
456 * @param array $qv The query variables
458 function _parse_meta_query( &$qv ) {
459 $meta_query = array();
461 // Simple query needs to be first for orderby=meta_value to work correctly
462 foreach ( array( 'key', 'value', 'compare', 'type' ) as $key ) {
463 if ( !empty( $qv[ "meta_$key" ] ) )
464 $meta_query[0][ $key ] = $qv[ "meta_$key" ];
467 if ( !empty( $qv['meta_query'] ) && is_array( $qv['meta_query'] ) ) {
468 $meta_query = array_merge( $meta_query, $qv['meta_query'] );
471 $qv['meta_query'] = $meta_query;
475 * Retrieve the name of the metadata table for the specified object type.
478 * @uses $wpdb WordPress database object for queries.
480 * @param string $type Type of object to get metadata table for (e.g., comment, post, or user)
481 * @return mixed Metadata table name, or false if no metadata table exists
483 function _get_meta_table($type) {
486 $table_name = $type . 'meta';
488 if ( empty($wpdb->$table_name) )
491 return $wpdb->$table_name;
495 * Determine whether a meta key is protected
499 * @param string $meta_key Meta key
500 * @return bool True if the key is protected, false otherwise.
502 function is_protected_meta( $meta_key, $meta_type = null ) {
503 $protected = ( '_' == $meta_key[0] );
505 return apply_filters( 'is_protected_meta', $protected, $meta_key, $meta_type );
509 * Sanitize meta value
513 * @param string $meta_key Meta key
514 * @param mixed $meta_value Meta value to sanitize
515 * @param string $meta_type Type of meta
516 * @return mixed Sanitized $meta_value
518 function sanitize_meta( $meta_key, $meta_value, $meta_type = null ) {
519 return apply_filters( 'sanitize_meta', $meta_value, $meta_key, $meta_type );