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);
49 $check = apply_filters( "add_{$meta_type}_metadata", null, $object_id, $meta_key, $meta_value, $unique );
50 if ( null !== $check )
53 if ( $unique && $wpdb->get_var( $wpdb->prepare(
54 "SELECT COUNT(*) FROM $table WHERE meta_key = %s AND $column = %d",
55 $meta_key, $object_id ) ) )
58 $_meta_value = $meta_value;
59 $meta_value = maybe_serialize( $meta_value );
61 do_action( "add_{$meta_type}_meta", $object_id, $meta_key, $_meta_value );
63 $wpdb->insert( $table, array(
64 $column => $object_id,
65 'meta_key' => $meta_key,
66 'meta_value' => $meta_value
69 wp_cache_delete($object_id, $meta_type . '_meta');
70 // users cache stores usermeta that must be cleared.
71 if ( 'user' == $meta_type )
72 clean_user_cache($object_id);
74 do_action( "added_{$meta_type}_meta", $wpdb->insert_id, $object_id, $meta_key, $_meta_value );
80 * Update metadata for the specified object. If no value already exists for the specified object
81 * ID and metadata key, the metadata will be added.
84 * @uses $wpdb WordPress database object for queries.
85 * @uses do_action() Calls 'update_{$meta_type}_meta' before updating metadata with meta_id of
86 * metadata entry to update, object ID, meta key, and meta value
87 * @uses do_action() Calls 'updated_{$meta_type}_meta' after updating metadata with meta_id of
88 * updated metadata entry, object ID, meta key, and meta value
90 * @param string $meta_type Type of object metadata is for (e.g., comment, post, or user)
91 * @param int $object_id ID of the object metadata is for
92 * @param string $meta_key Metadata key
93 * @param string $meta_value Metadata value
94 * @param string $prev_value Optional. If specified, only update existing metadata entries with
95 * the specified value. Otherwise, update all entries.
96 * @return bool True on successful update, false on failure.
98 function update_metadata($meta_type, $object_id, $meta_key, $meta_value, $prev_value = '') {
99 if ( !$meta_type || !$meta_key )
102 if ( !$object_id = absint($object_id) )
105 if ( ! $table = _get_meta_table($meta_type) )
110 $column = esc_sql($meta_type . '_id');
111 $id_column = 'user' == $meta_type ? 'umeta_id' : 'meta_id';
113 // expected_slashed ($meta_key)
114 $meta_key = stripslashes($meta_key);
115 $meta_value = stripslashes_deep($meta_value);
117 $check = apply_filters( "update_{$meta_type}_metadata", null, $object_id, $meta_key, $meta_value, $prev_value );
118 if ( null !== $check )
119 return (bool) $check;
121 if ( ! $meta_id = $wpdb->get_var( $wpdb->prepare( "SELECT $id_column FROM $table WHERE meta_key = %s AND $column = %d", $meta_key, $object_id ) ) )
122 return add_metadata($meta_type, $object_id, $meta_key, $meta_value);
124 // Compare existing value to new value if no prev value given and the key exists only once.
125 if ( empty($prev_value) ) {
126 $old_value = get_metadata($meta_type, $object_id, $meta_key);
127 if ( count($old_value) == 1 ) {
128 if ( $old_value[0] === $meta_value )
133 $_meta_value = $meta_value;
134 $meta_value = maybe_serialize( $meta_value );
136 $data = compact( 'meta_value' );
137 $where = array( $column => $object_id, 'meta_key' => $meta_key );
139 if ( !empty( $prev_value ) ) {
140 $prev_value = maybe_serialize($prev_value);
141 $where['meta_value'] = $prev_value;
144 do_action( "update_{$meta_type}_meta", $meta_id, $object_id, $meta_key, $_meta_value );
146 $wpdb->update( $table, $data, $where );
147 wp_cache_delete($object_id, $meta_type . '_meta');
148 // users cache stores usermeta that must be cleared.
149 if ( 'user' == $meta_type )
150 clean_user_cache($object_id);
152 do_action( "updated_{$meta_type}_meta", $meta_id, $object_id, $meta_key, $_meta_value );
158 * Delete metadata for the specified object.
161 * @uses $wpdb WordPress database object for queries.
162 * @uses do_action() Calls 'deleted_{$meta_type}_meta' after deleting with meta_id of
163 * deleted metadata entries, object ID, meta key, and meta value
165 * @param string $meta_type Type of object metadata is for (e.g., comment, post, or user)
166 * @param int $object_id ID of the object metadata is for
167 * @param string $meta_key Metadata key
168 * @param string $meta_value Optional. Metadata value. If specified, only delete metadata entries
169 * with this value. Otherwise, delete all entries with the specified meta_key.
170 * @param bool $delete_all Optional, default is false. If true, delete matching metadata entries
171 * for all objects, ignoring the specified object_id. Otherwise, only delete matching
172 * metadata entries for the specified object_id.
173 * @return bool True on successful delete, false on failure.
175 function delete_metadata($meta_type, $object_id, $meta_key, $meta_value = '', $delete_all = false) {
176 if ( !$meta_type || !$meta_key )
179 if ( (!$object_id = absint($object_id)) && !$delete_all )
182 if ( ! $table = _get_meta_table($meta_type) )
187 $type_column = esc_sql($meta_type . '_id');
188 $id_column = 'user' == $meta_type ? 'umeta_id' : 'meta_id';
189 // expected_slashed ($meta_key)
190 $meta_key = stripslashes($meta_key);
191 $meta_value = stripslashes_deep($meta_value);
193 $check = apply_filters( "delete_{$meta_type}_metadata", null, $object_id, $meta_key, $meta_value, $delete_all );
194 if ( null !== $check )
195 return (bool) $check;
197 $_meta_value = $meta_value;
198 $meta_value = maybe_serialize( $meta_value );
200 $query = $wpdb->prepare( "SELECT $id_column FROM $table WHERE meta_key = %s", $meta_key );
203 $query .= $wpdb->prepare(" AND $type_column = %d", $object_id );
206 $query .= $wpdb->prepare(" AND meta_value = %s", $meta_value );
208 $meta_ids = $wpdb->get_col( $query );
209 if ( !count( $meta_ids ) )
212 do_action( "delete_{$meta_type}_meta", $meta_ids, $object_id, $meta_key, $_meta_value );
214 $query = "DELETE FROM $table WHERE $id_column IN( " . implode( ',', $meta_ids ) . " )";
216 $count = $wpdb->query($query);
221 wp_cache_delete($object_id, $meta_type . '_meta');
222 // users cache stores usermeta that must be cleared.
223 if ( 'user' == $meta_type )
224 clean_user_cache($object_id);
226 do_action( "deleted_{$meta_type}_meta", $meta_ids, $object_id, $meta_key, $_meta_value );
232 * Retrieve metadata for the specified object.
236 * @param string $meta_type Type of object metadata is for (e.g., comment, post, or user)
237 * @param int $object_id ID of the object metadata is for
238 * @param string $meta_key Optional. Metadata key. If not specified, retrieve all metadata for
239 * the specified object.
240 * @param bool $single Optional, default is false. If true, return only the first value of the
241 * specified meta_key. This parameter has no effect if meta_key is not specified.
242 * @return string|array Single metadata value, or array of values
244 function get_metadata($meta_type, $object_id, $meta_key = '', $single = false) {
248 if ( !$object_id = absint($object_id) )
251 $check = apply_filters( "get_{$meta_type}_metadata", null, $object_id, $meta_key, $single );
252 if ( null !== $check ) {
253 if ( $single && is_array( $check ) )
259 $meta_cache = wp_cache_get($object_id, $meta_type . '_meta');
261 if ( !$meta_cache ) {
262 $meta_cache = update_meta_cache( $meta_type, array( $object_id ) );
263 $meta_cache = $meta_cache[$object_id];
269 if ( isset($meta_cache[$meta_key]) ) {
271 return maybe_unserialize( $meta_cache[$meta_key][0] );
273 return array_map('maybe_unserialize', $meta_cache[$meta_key]);
283 * Update the metadata cache for the specified objects.
286 * @uses $wpdb WordPress database object for queries.
288 * @param string $meta_type Type of object metadata is for (e.g., comment, post, or user)
289 * @param int|array $object_ids array or comma delimited list of object IDs to update cache for
290 * @return mixed Metadata cache for the specified objects, or false on failure.
292 function update_meta_cache($meta_type, $object_ids) {
293 if ( empty( $meta_type ) || empty( $object_ids ) )
296 if ( ! $table = _get_meta_table($meta_type) )
299 $column = esc_sql($meta_type . '_id');
303 if ( !is_array($object_ids) ) {
304 $object_ids = preg_replace('|[^0-9,]|', '', $object_ids);
305 $object_ids = explode(',', $object_ids);
308 $object_ids = array_map('intval', $object_ids);
310 $cache_key = $meta_type . '_meta';
313 foreach ( $object_ids as $id ) {
314 $cached_object = wp_cache_get( $id, $cache_key );
315 if ( false === $cached_object )
318 $cache[$id] = $cached_object;
325 $id_list = join(',', $ids);
326 $meta_list = $wpdb->get_results( $wpdb->prepare("SELECT $column, meta_key, meta_value FROM $table WHERE $column IN ($id_list)",
327 $meta_type), ARRAY_A );
329 if ( !empty($meta_list) ) {
330 foreach ( $meta_list as $metarow) {
331 $mpid = intval($metarow[$column]);
332 $mkey = $metarow['meta_key'];
333 $mval = $metarow['meta_value'];
335 // Force subkeys to be array type:
336 if ( !isset($cache[$mpid]) || !is_array($cache[$mpid]) )
337 $cache[$mpid] = array();
338 if ( !isset($cache[$mpid][$mkey]) || !is_array($cache[$mpid][$mkey]) )
339 $cache[$mpid][$mkey] = array();
341 // Add a value to the current pid/key:
342 $cache[$mpid][$mkey][] = $mval;
346 foreach ( $ids as $id ) {
347 if ( ! isset($cache[$id]) )
348 $cache[$id] = array();
349 wp_cache_add( $id, $cache[$id], $cache_key );
356 * Given a meta query, generates SQL clauses to be appended to a main query
361 * @param array $meta_query List of metadata queries. A single query is an associative array:
362 * - 'key' string The meta key
363 * - 'value' string|array The meta value
364 * - 'compare' (optional) string How to compare the key to the value.
365 * Possible values: '=', '!=', '>', '>=', '<', '<=', 'LIKE', 'NOT LIKE', 'IN', 'NOT IN', 'BETWEEN', 'NOT BETWEEN'.
367 * - 'type' string (optional) The type of the value.
368 * Possible values: 'NUMERIC', 'BINARY', 'CHAR', 'DATE', 'DATETIME', 'DECIMAL', 'SIGNED', 'TIME', 'UNSIGNED'.
371 * @param string $type Type of meta
372 * @param string $primary_table
373 * @param string $primary_id_column
374 * @param object $context (optional) The main query object
375 * @return array( 'join' => $join_sql, 'where' => $where_sql )
377 function _get_meta_sql( $meta_query, $type, $primary_table, $primary_id_column, $context = null ) {
380 if ( ! $meta_table = _get_meta_table( $type ) )
383 $meta_id_column = esc_sql( $type . '_id' );
388 foreach ( $meta_query as $q ) {
389 $meta_key = isset( $q['key'] ) ? trim( $q['key'] ) : '';
390 $meta_value = isset( $q['value'] ) ? $q['value'] : '';
391 $meta_compare = isset( $q['compare'] ) ? strtoupper( $q['compare'] ) : '=';
392 $meta_type = isset( $q['type'] ) ? strtoupper( $q['type'] ) : 'CHAR';
394 if ( ! in_array( $meta_compare, array( '=', '!=', '>', '>=', '<', '<=', 'LIKE', 'NOT LIKE', 'IN', 'NOT IN', 'BETWEEN', 'NOT BETWEEN' ) ) )
397 if ( 'NUMERIC' == $meta_type )
398 $meta_type = 'SIGNED';
399 elseif ( ! in_array( $meta_type, array( 'BINARY', 'CHAR', 'DATE', 'DATETIME', 'DECIMAL', 'SIGNED', 'TIME', 'UNSIGNED' ) ) )
402 if ( empty( $meta_key ) && empty( $meta_value ) )
405 $alias = $i ? 'mt' . $i : $meta_table;
407 $join .= "\nINNER JOIN $meta_table";
408 $join .= $i ? " AS $alias" : '';
409 $join .= " ON ($primary_table.$primary_id_column = $alias.$meta_id_column)";
413 if ( !empty( $meta_key ) )
414 $where .= $wpdb->prepare( " AND $alias.meta_key = %s", $meta_key );
416 if ( in_array( $meta_compare, array( 'IN', 'NOT IN', 'BETWEEN', 'NOT BETWEEN' ) ) ) {
417 if ( ! is_array( $meta_value ) )
418 $meta_value = preg_split( '/[,\s]+/', $meta_value );
420 $meta_value = trim( $meta_value );
423 if ( empty( $meta_value ) )
426 if ( 'IN' == substr( $meta_compare, -2) ) {
427 $meta_compare_string = '(' . substr( str_repeat( ',%s', count( $meta_value ) ), 1 ) . ')';
428 } elseif ( 'BETWEEN' == substr( $meta_compare, -7) ) {
429 $meta_value = array_slice( $meta_value, 0, 2 );
430 $meta_compare_string = '%s AND %s';
431 } elseif ( 'LIKE' == substr( $meta_compare, -4 ) ) {
432 $meta_value = '%' . like_escape( $meta_value ) . '%';
433 $meta_compare_string = '%s';
435 $meta_compare_string = '%s';
438 // @todo Temporary hack to support empty values. Do not use outside of core.
439 if ( '_wp_zero_value' == $meta_value )
442 $where .= $wpdb->prepare( " AND CAST($alias.meta_value AS {$meta_type}) {$meta_compare} {$meta_compare_string}", $meta_value );
445 return apply_filters_ref_array( 'get_meta_sql', array( compact( 'join', 'where' ), $meta_query, $type, $primary_table, $primary_id_column, &$context ) );
449 * Populates the $meta_query property
454 * @param array $qv The query variables
456 function _parse_meta_query( &$qv ) {
457 $meta_query = array();
459 // Simple query needs to be first for orderby=meta_value to work correctly
460 foreach ( array( 'key', 'value', 'compare', 'type' ) as $key ) {
461 if ( !empty( $qv[ "meta_$key" ] ) )
462 $meta_query[0][ $key ] = $qv[ "meta_$key" ];
465 if ( !empty( $qv['meta_query'] ) && is_array( $qv['meta_query'] ) ) {
466 $meta_query = array_merge( $meta_query, $qv['meta_query'] );
469 $qv['meta_query'] = $meta_query;
473 * Retrieve the name of the metadata table for the specified object type.
476 * @uses $wpdb WordPress database object for queries.
478 * @param string $type Type of object to get metadata table for (e.g., comment, post, or user)
479 * @return mixed Metadata table name, or false if no metadata table exists
481 function _get_meta_table($type) {
484 $table_name = $type . 'meta';
486 if ( empty($wpdb->$table_name) )
489 return $wpdb->$table_name;