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.
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. Whether the specified metadata key should be
25 * unique for the object. If true, and the object already has a value for the specified
26 * metadata key, no change will be made
27 * @return int|bool The meta ID on success, false on failure.
29 function add_metadata($meta_type, $object_id, $meta_key, $meta_value, $unique = false) {
30 if ( !$meta_type || !$meta_key )
33 if ( !$object_id = absint($object_id) )
36 if ( ! $table = _get_meta_table($meta_type) )
41 $column = sanitize_key($meta_type . '_id');
43 // expected_slashed ($meta_key)
44 $meta_key = wp_unslash($meta_key);
45 $meta_value = wp_unslash($meta_value);
46 $meta_value = sanitize_meta( $meta_key, $meta_value, $meta_type );
49 * Filter whether to add metadata of a specific type.
51 * The dynamic portion of the hook, $meta_type, refers to the meta
52 * object type (comment, post, or user). Returning a non-null value
53 * will effectively short-circuit the function.
57 * @param null|bool $check Whether to allow adding metadata for the given type.
58 * @param int $object_id Object ID.
59 * @param string $meta_key Meta key.
60 * @param mixed $meta_value Meta value. Must be serializable if non-scalar.
61 * @param bool $unique Whether the specified meta key should be unique
62 * for the object. Optional. Default false.
64 $check = apply_filters( "add_{$meta_type}_metadata", null, $object_id, $meta_key, $meta_value, $unique );
65 if ( null !== $check )
68 if ( $unique && $wpdb->get_var( $wpdb->prepare(
69 "SELECT COUNT(*) FROM $table WHERE meta_key = %s AND $column = %d",
70 $meta_key, $object_id ) ) )
73 $_meta_value = $meta_value;
74 $meta_value = maybe_serialize( $meta_value );
77 * Fires immediately before meta of a specific type is added.
79 * The dynamic portion of the hook, $meta_type, refers to the meta
80 * object type (comment, post, or user).
84 * @param int $object_id Object ID.
85 * @param string $meta_key Meta key.
86 * @param mixed $meta_value Meta value.
88 do_action( "add_{$meta_type}_meta", $object_id, $meta_key, $_meta_value );
90 $result = $wpdb->insert( $table, array(
91 $column => $object_id,
92 'meta_key' => $meta_key,
93 'meta_value' => $meta_value
99 $mid = (int) $wpdb->insert_id;
101 wp_cache_delete($object_id, $meta_type . '_meta');
104 * Fires immediately after meta of a specific type is added.
106 * The dynamic portion of the hook, $meta_type, refers to the meta
107 * object type (comment, post, or user).
111 * @param int $mid The meta ID after successful update.
112 * @param int $object_id Object ID.
113 * @param string $meta_key Meta key.
114 * @param mixed $meta_value Meta value.
116 do_action( "added_{$meta_type}_meta", $mid, $object_id, $meta_key, $_meta_value );
122 * Update metadata for the specified object. If no value already exists for the specified object
123 * ID and metadata key, the metadata will be added.
126 * @uses $wpdb WordPress database object for queries.
128 * @param string $meta_type Type of object metadata is for (e.g., comment, post, or user)
129 * @param int $object_id ID of the object metadata is for
130 * @param string $meta_key Metadata key
131 * @param mixed $meta_value Metadata value. Must be serializable if non-scalar.
132 * @param mixed $prev_value Optional. If specified, only update existing metadata entries with
133 * the specified value. Otherwise, update all entries.
134 * @return int|bool Meta ID if the key didn't exist, true on successful update, false on failure.
136 function update_metadata($meta_type, $object_id, $meta_key, $meta_value, $prev_value = '') {
137 if ( !$meta_type || !$meta_key )
140 if ( !$object_id = absint($object_id) )
143 if ( ! $table = _get_meta_table($meta_type) )
148 $column = sanitize_key($meta_type . '_id');
149 $id_column = 'user' == $meta_type ? 'umeta_id' : 'meta_id';
151 // expected_slashed ($meta_key)
152 $meta_key = wp_unslash($meta_key);
153 $passed_value = $meta_value;
154 $meta_value = wp_unslash($meta_value);
155 $meta_value = sanitize_meta( $meta_key, $meta_value, $meta_type );
158 * Filter whether to update metadata of a specific type.
160 * The dynamic portion of the hook, $meta_type, refers to the meta
161 * object type (comment, post, or user). Returning a non-null value
162 * will effectively short-circuit the function.
166 * @param null|bool $check Whether to allow updating metadata for the given type.
167 * @param int $object_id Object ID.
168 * @param string $meta_key Meta key.
169 * @param mixed $meta_value Meta value. Must be serializable if non-scalar.
170 * @param mixed $prev_value Optional. If specified, only update existing
171 * metadata entries with the specified value.
172 * Otherwise, update all entries.
174 $check = apply_filters( "update_{$meta_type}_metadata", null, $object_id, $meta_key, $meta_value, $prev_value );
175 if ( null !== $check )
176 return (bool) $check;
178 // Compare existing value to new value if no prev value given and the key exists only once.
179 if ( empty($prev_value) ) {
180 $old_value = get_metadata($meta_type, $object_id, $meta_key);
181 if ( count($old_value) == 1 ) {
182 if ( $old_value[0] === $meta_value )
187 if ( ! $meta_id = $wpdb->get_var( $wpdb->prepare( "SELECT $id_column FROM $table WHERE meta_key = %s AND $column = %d", $meta_key, $object_id ) ) )
188 return add_metadata($meta_type, $object_id, $meta_key, $passed_value);
190 $_meta_value = $meta_value;
191 $meta_value = maybe_serialize( $meta_value );
193 $data = compact( 'meta_value' );
194 $where = array( $column => $object_id, 'meta_key' => $meta_key );
196 if ( !empty( $prev_value ) ) {
197 $prev_value = maybe_serialize($prev_value);
198 $where['meta_value'] = $prev_value;
202 * Fires immediately before updating metadata of a specific type.
204 * The dynamic portion of the hook, $meta_type, refers to the meta
205 * object type (comment, post, or user).
209 * @param int $meta_id ID of the metadata entry to update.
210 * @param int $object_id Object ID.
211 * @param string $meta_key Meta key.
212 * @param mixed $meta_value Meta value.
214 do_action( "update_{$meta_type}_meta", $meta_id, $object_id, $meta_key, $_meta_value );
216 if ( 'post' == $meta_type )
218 * Fires immediately before updating a post's metadata.
222 * @param int $meta_id ID of metadata entry to update.
223 * @param int $object_id Object ID.
224 * @param string $meta_key Meta key.
225 * @param mixed $meta_value Meta value.
227 do_action( 'update_postmeta', $meta_id, $object_id, $meta_key, $meta_value );
229 $result = $wpdb->update( $table, $data, $where );
233 wp_cache_delete($object_id, $meta_type . '_meta');
236 * Fires immediately after updating metadata of a specific type.
238 * The dynamic portion of the hook, $meta_type, refers to the meta
239 * object type (comment, post, or user).
243 * @param int $meta_id ID of updated metadata entry.
244 * @param int $object_id Object ID.
245 * @param string $meta_key Meta key.
246 * @param mixed $meta_value Meta value.
248 do_action( "updated_{$meta_type}_meta", $meta_id, $object_id, $meta_key, $_meta_value );
250 if ( 'post' == $meta_type ) {
252 * Fires immediately after updating a post's metadata.
256 * @param int $meta_id ID of updated metadata entry.
257 * @param int $object_id Object ID.
258 * @param string $meta_key Meta key.
259 * @param mixed $meta_value Meta value.
261 do_action( 'updated_postmeta', $meta_id, $object_id, $meta_key, $meta_value );
268 * Delete metadata for the specified object.
271 * @uses $wpdb WordPress database object for queries.
273 * @param string $meta_type Type of object metadata is for (e.g., comment, post, or user)
274 * @param int $object_id ID of the object metadata is for
275 * @param string $meta_key Metadata key
276 * @param mixed $meta_value Optional. Metadata value. Must be serializable if non-scalar. If specified, only delete metadata entries
277 * with this value. Otherwise, delete all entries with the specified meta_key.
278 * @param bool $delete_all Optional, default is false. If true, delete matching metadata entries
279 * for all objects, ignoring the specified object_id. Otherwise, only delete matching
280 * metadata entries for the specified object_id.
281 * @return bool True on successful delete, false on failure.
283 function delete_metadata($meta_type, $object_id, $meta_key, $meta_value = '', $delete_all = false) {
284 if ( !$meta_type || !$meta_key )
287 if ( (!$object_id = absint($object_id)) && !$delete_all )
290 if ( ! $table = _get_meta_table($meta_type) )
295 $type_column = sanitize_key($meta_type . '_id');
296 $id_column = 'user' == $meta_type ? 'umeta_id' : 'meta_id';
297 // expected_slashed ($meta_key)
298 $meta_key = wp_unslash($meta_key);
299 $meta_value = wp_unslash($meta_value);
302 * Filter whether to delete metadata of a specific type.
304 * The dynamic portion of the hook, $meta_type, refers to the meta
305 * object type (comment, post, or user). Returning a non-null value
306 * will effectively short-circuit the function.
310 * @param null|bool $delete Whether to allow metadata deletion of the given type.
311 * @param int $object_id Object ID.
312 * @param string $meta_key Meta key.
313 * @param mixed $meta_value Meta value. Must be serializable if non-scalar.
314 * @param bool $delete_all Whether to delete the matching metadata entries
315 * for all objects, ignoring the specified $object_id.
318 $check = apply_filters( "delete_{$meta_type}_metadata", null, $object_id, $meta_key, $meta_value, $delete_all );
319 if ( null !== $check )
320 return (bool) $check;
322 $_meta_value = $meta_value;
323 $meta_value = maybe_serialize( $meta_value );
325 $query = $wpdb->prepare( "SELECT $id_column FROM $table WHERE meta_key = %s", $meta_key );
328 $query .= $wpdb->prepare(" AND $type_column = %d", $object_id );
331 $query .= $wpdb->prepare(" AND meta_value = %s", $meta_value );
333 $meta_ids = $wpdb->get_col( $query );
334 if ( !count( $meta_ids ) )
338 $object_ids = $wpdb->get_col( $wpdb->prepare( "SELECT $type_column FROM $table WHERE meta_key = %s", $meta_key ) );
341 * Fires immediately before deleting metadata of a specific type.
343 * The dynamic portion of the hook, $meta_type, refers to the meta
344 * object type (comment, post, or user).
348 * @param array $meta_ids An array of metadata entry IDs to delete.
349 * @param int $object_id Object ID.
350 * @param string $meta_key Meta key.
351 * @param mixed $meta_value Meta value.
353 do_action( "delete_{$meta_type}_meta", $meta_ids, $object_id, $meta_key, $_meta_value );
356 if ( 'post' == $meta_type ) {
358 * Fires immediately before deleting metadata for a post.
362 * @param array $meta_ids An array of post metadata entry IDs to delete.
364 do_action( 'delete_postmeta', $meta_ids );
367 $query = "DELETE FROM $table WHERE $id_column IN( " . implode( ',', $meta_ids ) . " )";
369 $count = $wpdb->query($query);
375 foreach ( (array) $object_ids as $o_id ) {
376 wp_cache_delete($o_id, $meta_type . '_meta');
379 wp_cache_delete($object_id, $meta_type . '_meta');
383 * Fires immediately after deleting metadata of a specific type.
385 * The dynamic portion of the hook name, $meta_type, refers to the meta
386 * object type (comment, post, or user).
390 * @param array $meta_ids An array of deleted metadata entry IDs.
391 * @param int $object_id Object ID.
392 * @param string $meta_key Meta key.
393 * @param mixed $meta_value Meta value.
395 do_action( "deleted_{$meta_type}_meta", $meta_ids, $object_id, $meta_key, $_meta_value );
398 if ( 'post' == $meta_type ) {
400 * Fires immediately after deleting metadata for a post.
404 * @param array $meta_ids An array of deleted post metadata entry IDs.
406 do_action( 'deleted_postmeta', $meta_ids );
413 * Retrieve metadata for the specified object.
417 * @param string $meta_type Type of object metadata is for (e.g., comment, post, or user)
418 * @param int $object_id ID of the object metadata is for
419 * @param string $meta_key Optional. Metadata key. If not specified, retrieve all metadata for
420 * the specified object.
421 * @param bool $single Optional, default is false. If true, return only the first value of the
422 * specified meta_key. This parameter has no effect if meta_key is not specified.
423 * @return string|array Single metadata value, or array of values
425 function get_metadata($meta_type, $object_id, $meta_key = '', $single = false) {
429 if ( !$object_id = absint($object_id) )
433 * Filter whether to retrieve metadata of a specific type.
435 * The dynamic portion of the hook, $meta_type, refers to the meta
436 * object type (comment, post, or user). Returning a non-null value
437 * will effectively short-circuit the function.
441 * @param null|array|string $value The value get_metadata() should
442 * return - a single metadata value,
443 * or an array of values.
444 * @param int $object_id Object ID.
445 * @param string $meta_key Meta key.
446 * @param string|array $single Meta value, or an array of values.
448 $check = apply_filters( "get_{$meta_type}_metadata", null, $object_id, $meta_key, $single );
449 if ( null !== $check ) {
450 if ( $single && is_array( $check ) )
456 $meta_cache = wp_cache_get($object_id, $meta_type . '_meta');
458 if ( !$meta_cache ) {
459 $meta_cache = update_meta_cache( $meta_type, array( $object_id ) );
460 $meta_cache = $meta_cache[$object_id];
466 if ( isset($meta_cache[$meta_key]) ) {
468 return maybe_unserialize( $meta_cache[$meta_key][0] );
470 return array_map('maybe_unserialize', $meta_cache[$meta_key]);
480 * Determine if a meta key is set for a given object
484 * @param string $meta_type Type of object metadata is for (e.g., comment, post, or user)
485 * @param int $object_id ID of the object metadata is for
486 * @param string $meta_key Metadata key.
487 * @return boolean true of the key is set, false if not.
489 function metadata_exists( $meta_type, $object_id, $meta_key ) {
493 if ( ! $object_id = absint( $object_id ) )
496 /** This filter is documented in wp-includes/meta.php */
497 $check = apply_filters( "get_{$meta_type}_metadata", null, $object_id, $meta_key, true );
498 if ( null !== $check )
499 return (bool) $check;
501 $meta_cache = wp_cache_get( $object_id, $meta_type . '_meta' );
503 if ( !$meta_cache ) {
504 $meta_cache = update_meta_cache( $meta_type, array( $object_id ) );
505 $meta_cache = $meta_cache[$object_id];
508 if ( isset( $meta_cache[ $meta_key ] ) )
515 * Get meta data by meta ID
519 * @param string $meta_type Type of object metadata is for (e.g., comment, post, or user)
520 * @param int $meta_id ID for a specific meta row
521 * @return object Meta object or false.
523 function get_metadata_by_mid( $meta_type, $meta_id ) {
529 if ( !$meta_id = absint( $meta_id ) )
532 if ( ! $table = _get_meta_table($meta_type) )
535 $id_column = ( 'user' == $meta_type ) ? 'umeta_id' : 'meta_id';
537 $meta = $wpdb->get_row( $wpdb->prepare( "SELECT * FROM $table WHERE $id_column = %d", $meta_id ) );
539 if ( empty( $meta ) )
542 if ( isset( $meta->meta_value ) )
543 $meta->meta_value = maybe_unserialize( $meta->meta_value );
549 * Update meta data by meta ID
553 * @uses get_metadata_by_mid() Calls get_metadata_by_mid() to fetch the meta key, value
554 * and object_id of the given meta_id.
556 * @param string $meta_type Type of object metadata is for (e.g., comment, post, or user)
557 * @param int $meta_id ID for a specific meta row
558 * @param string $meta_value Metadata value
559 * @param string $meta_key Optional, you can provide a meta key to update it
560 * @return bool True on successful update, false on failure.
562 function update_metadata_by_mid( $meta_type, $meta_id, $meta_value, $meta_key = false ) {
565 // Make sure everything is valid.
569 if ( ! $meta_id = absint( $meta_id ) )
572 if ( ! $table = _get_meta_table( $meta_type ) )
575 $column = sanitize_key($meta_type . '_id');
576 $id_column = 'user' == $meta_type ? 'umeta_id' : 'meta_id';
578 // Fetch the meta and go on if it's found.
579 if ( $meta = get_metadata_by_mid( $meta_type, $meta_id ) ) {
580 $original_key = $meta->meta_key;
581 $original_value = $meta->meta_value;
582 $object_id = $meta->{$column};
584 // If a new meta_key (last parameter) was specified, change the meta key,
585 // otherwise use the original key in the update statement.
586 if ( false === $meta_key ) {
587 $meta_key = $original_key;
588 } elseif ( ! is_string( $meta_key ) ) {
593 $_meta_value = $meta_value;
594 $meta_value = sanitize_meta( $meta_key, $meta_value, $meta_type );
595 $meta_value = maybe_serialize( $meta_value );
597 // Format the data query arguments.
599 'meta_key' => $meta_key,
600 'meta_value' => $meta_value
603 // Format the where query arguments.
605 $where[$id_column] = $meta_id;
607 /** This action is documented in wp-includes/meta.php */
608 do_action( "update_{$meta_type}_meta", $meta_id, $object_id, $meta_key, $_meta_value );
610 if ( 'post' == $meta_type ) {
611 /** This action is documented in wp-includes/meta.php */
612 do_action( 'update_postmeta', $meta_id, $object_id, $meta_key, $meta_value );
615 // Run the update query, all fields in $data are %s, $where is a %d.
616 $result = $wpdb->update( $table, $data, $where, '%s', '%d' );
621 wp_cache_delete($object_id, $meta_type . '_meta');
623 /** This action is documented in wp-includes/meta.php */
624 do_action( "updated_{$meta_type}_meta", $meta_id, $object_id, $meta_key, $_meta_value );
626 if ( 'post' == $meta_type ) {
627 /** This action is documented in wp-includes/meta.php */
628 do_action( 'updated_postmeta', $meta_id, $object_id, $meta_key, $meta_value );
634 // And if the meta was not found.
639 * Delete meta data by meta ID
643 * @uses get_metadata_by_mid() Calls get_metadata_by_mid() to fetch the meta key, value
644 * and object_id of the given meta_id.
646 * @param string $meta_type Type of object metadata is for (e.g., comment, post, or user)
647 * @param int $meta_id ID for a specific meta row
648 * @return bool True on successful delete, false on failure.
650 function delete_metadata_by_mid( $meta_type, $meta_id ) {
653 // Make sure everything is valid.
657 if ( ! $meta_id = absint( $meta_id ) )
660 if ( ! $table = _get_meta_table( $meta_type ) )
663 // object and id columns
664 $column = sanitize_key($meta_type . '_id');
665 $id_column = 'user' == $meta_type ? 'umeta_id' : 'meta_id';
667 // Fetch the meta and go on if it's found.
668 if ( $meta = get_metadata_by_mid( $meta_type, $meta_id ) ) {
669 $object_id = $meta->{$column};
671 /** This action is documented in wp-includes/meta.php */
672 do_action( "delete_{$meta_type}_meta", (array) $meta_id, $object_id, $meta->meta_key, $meta->meta_value );
675 if ( 'post' == $meta_type || 'comment' == $meta_type ) {
677 * Fires immediately before deleting post or comment metadata of a specific type.
679 * The dynamic portion of the hook, $meta_type, refers to the meta
680 * object type (post or comment).
684 * @param int $meta_id ID of the metadata entry to delete.
686 do_action( "delete_{$meta_type}meta", $meta_id );
689 // Run the query, will return true if deleted, false otherwise
690 $result = (bool) $wpdb->delete( $table, array( $id_column => $meta_id ) );
693 wp_cache_delete($object_id, $meta_type . '_meta');
695 /** This action is documented in wp-includes/meta.php */
696 do_action( "deleted_{$meta_type}_meta", (array) $meta_id, $object_id, $meta->meta_key, $meta->meta_value );
699 if ( 'post' == $meta_type || 'comment' == $meta_type ) {
701 * Fires immediately after deleting post or comment metadata of a specific type.
703 * The dynamic portion of the hook, $meta_type, refers to the meta
704 * object type (post or comment).
708 * @param int $meta_ids Deleted metadata entry ID.
710 do_action( "deleted_{$meta_type}meta", $meta_id );
717 // Meta id was not found.
722 * Update the metadata cache for the specified objects.
725 * @uses $wpdb WordPress database object for queries.
727 * @param string $meta_type Type of object metadata is for (e.g., comment, post, or user)
728 * @param int|array $object_ids array or comma delimited list of object IDs to update cache for
729 * @return mixed Metadata cache for the specified objects, or false on failure.
731 function update_meta_cache($meta_type, $object_ids) {
732 if ( empty( $meta_type ) || empty( $object_ids ) )
735 if ( ! $table = _get_meta_table($meta_type) )
738 $column = sanitize_key($meta_type . '_id');
742 if ( !is_array($object_ids) ) {
743 $object_ids = preg_replace('|[^0-9,]|', '', $object_ids);
744 $object_ids = explode(',', $object_ids);
747 $object_ids = array_map('intval', $object_ids);
749 $cache_key = $meta_type . '_meta';
752 foreach ( $object_ids as $id ) {
753 $cached_object = wp_cache_get( $id, $cache_key );
754 if ( false === $cached_object )
757 $cache[$id] = $cached_object;
764 $id_list = join( ',', $ids );
765 $id_column = 'user' == $meta_type ? 'umeta_id' : 'meta_id';
766 $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 );
768 if ( !empty($meta_list) ) {
769 foreach ( $meta_list as $metarow) {
770 $mpid = intval($metarow[$column]);
771 $mkey = $metarow['meta_key'];
772 $mval = $metarow['meta_value'];
774 // Force subkeys to be array type:
775 if ( !isset($cache[$mpid]) || !is_array($cache[$mpid]) )
776 $cache[$mpid] = array();
777 if ( !isset($cache[$mpid][$mkey]) || !is_array($cache[$mpid][$mkey]) )
778 $cache[$mpid][$mkey] = array();
780 // Add a value to the current pid/key:
781 $cache[$mpid][$mkey][] = $mval;
785 foreach ( $ids as $id ) {
786 if ( ! isset($cache[$id]) )
787 $cache[$id] = array();
788 wp_cache_add( $id, $cache[$id], $cache_key );
795 * Given a meta query, generates SQL clauses to be appended to a main query
801 * @param array $meta_query A meta query
802 * @param string $type Type of meta
803 * @param string $primary_table
804 * @param string $primary_id_column
805 * @param object $context (optional) The main query object
806 * @return array( 'join' => $join_sql, 'where' => $where_sql )
808 function get_meta_sql( $meta_query, $type, $primary_table, $primary_id_column, $context = null ) {
809 $meta_query_obj = new WP_Meta_Query( $meta_query );
810 return $meta_query_obj->get_sql( $type, $primary_table, $primary_id_column, $context );
814 * Container class for a multiple metadata query
818 class WP_Meta_Query {
820 * List of metadata queries. A single query is an associative array:
821 * - 'key' string The meta key
822 * - 'value' string|array The meta value
823 * - 'compare' (optional) string How to compare the key to the value.
824 * Possible values: '=', '!=', '>', '>=', '<', '<=', 'LIKE', 'NOT LIKE', 'IN', 'NOT IN',
825 * 'BETWEEN', 'NOT BETWEEN', 'REGEXP', 'NOT REGEXP', 'RLIKE'.
827 * - 'type' string (optional) The type of the value.
828 * Possible values: 'NUMERIC', 'BINARY', 'CHAR', 'DATE', 'DATETIME', 'DECIMAL', 'SIGNED', 'TIME', 'UNSIGNED'.
835 public $queries = array();
838 * The relation between the queries. Can be one of 'AND' or 'OR'.
849 * @param array $meta_query (optional) A meta query
851 function __construct( $meta_query = false ) {
855 if ( isset( $meta_query['relation'] ) && strtoupper( $meta_query['relation'] ) == 'OR' ) {
856 $this->relation = 'OR';
858 $this->relation = 'AND';
861 $this->queries = array();
863 foreach ( $meta_query as $key => $query ) {
864 if ( ! is_array( $query ) )
867 $this->queries[] = $query;
872 * Constructs a meta query based on 'meta_*' query vars
877 * @param array $qv The query variables
879 function parse_query_vars( $qv ) {
880 $meta_query = array();
882 // Simple query needs to be first for orderby=meta_value to work correctly
883 foreach ( array( 'key', 'compare', 'type' ) as $key ) {
884 if ( !empty( $qv[ "meta_$key" ] ) )
885 $meta_query[0][ $key ] = $qv[ "meta_$key" ];
888 // WP_Query sets 'meta_value' = '' by default
889 if ( isset( $qv[ 'meta_value' ] ) && '' !== $qv[ 'meta_value' ] && ( ! is_array( $qv[ 'meta_value' ] ) || $qv[ 'meta_value' ] ) )
890 $meta_query[0]['value'] = $qv[ 'meta_value' ];
892 if ( !empty( $qv['meta_query'] ) && is_array( $qv['meta_query'] ) ) {
893 $meta_query = array_merge( $meta_query, $qv['meta_query'] );
896 $this->__construct( $meta_query );
900 * Given a meta type, return the appropriate alias if applicable
904 * @param string $type MySQL type to cast meta_value
905 * @return string MySQL type
907 function get_cast_for_type( $type = '' ) {
908 if ( empty( $type ) )
911 $meta_type = strtoupper( $type );
913 if ( ! preg_match( '/^(?:BINARY|CHAR|DATE|DATETIME|SIGNED|UNSIGNED|TIME|NUMERIC(?:\(\d+(?:,\s?\d+)?\))?|DECIMAL(?:\(\d+(?:,\s?\d+)?\))?)$/', $meta_type ) )
916 if ( 'NUMERIC' == $meta_type )
917 $meta_type = 'SIGNED';
923 * Generates SQL clauses to be appended to a main query.
928 * @param string $type Type of meta
929 * @param string $primary_table
930 * @param string $primary_id_column
931 * @param object $context (optional) The main query object
932 * @return array( 'join' => $join_sql, 'where' => $where_sql )
934 function get_sql( $type, $primary_table, $primary_id_column, $context = null ) {
937 if ( ! $meta_table = _get_meta_table( $type ) )
940 $meta_id_column = sanitize_key( $type . '_id' );
945 $key_only_queries = array();
948 // Split out the queries with empty arrays as value
949 foreach ( $this->queries as $k => $q ) {
950 if ( isset( $q['value'] ) && is_array( $q['value'] ) && empty( $q['value'] ) ) {
951 $key_only_queries[$k] = $q;
952 unset( $this->queries[$k] );
956 // Split out the meta_key only queries (we can only do this for OR)
957 if ( 'OR' == $this->relation ) {
958 foreach ( $this->queries as $k => $q ) {
959 if ( ( empty( $q['compare'] ) || 'NOT EXISTS' != $q['compare'] ) && ! array_key_exists( 'value', $q ) && ! empty( $q['key'] ) )
960 $key_only_queries[$k] = $q;
965 $queries = $this->queries;
968 // Specify all the meta_key only queries in one go
969 if ( $key_only_queries ) {
970 $join[] = "INNER JOIN $meta_table ON $primary_table.$primary_id_column = $meta_table.$meta_id_column";
972 foreach ( $key_only_queries as $key => $q )
973 $where["key-only-$key"] = $wpdb->prepare( "$meta_table.meta_key = %s", trim( $q['key'] ) );
976 foreach ( $queries as $k => $q ) {
977 $meta_key = isset( $q['key'] ) ? trim( $q['key'] ) : '';
978 $meta_type = $this->get_cast_for_type( isset( $q['type'] ) ? $q['type'] : '' );
980 if ( array_key_exists( 'value', $q ) && is_null( $q['value'] ) )
983 $meta_value = isset( $q['value'] ) ? $q['value'] : null;
985 if ( isset( $q['compare'] ) )
986 $meta_compare = strtoupper( $q['compare'] );
988 $meta_compare = is_array( $meta_value ) ? 'IN' : '=';
990 if ( ! in_array( $meta_compare, array(
991 '=', '!=', '>', '>=', '<', '<=',
994 'BETWEEN', 'NOT BETWEEN',
996 'REGEXP', 'NOT REGEXP', 'RLIKE'
1000 $i = count( $join );
1001 $alias = $i ? 'mt' . $i : $meta_table;
1003 if ( 'NOT EXISTS' == $meta_compare ) {
1004 $join[$i] = "LEFT JOIN $meta_table";
1005 $join[$i] .= $i ? " AS $alias" : '';
1006 $join[$i] .= " ON ($primary_table.$primary_id_column = $alias.$meta_id_column AND $alias.meta_key = '$meta_key')";
1008 $where[$k] = ' ' . $alias . '.' . $meta_id_column . ' IS NULL';
1013 $join[$i] = "INNER JOIN $meta_table";
1014 $join[$i] .= $i ? " AS $alias" : '';
1015 $join[$i] .= " ON ($primary_table.$primary_id_column = $alias.$meta_id_column)";
1018 if ( !empty( $meta_key ) )
1019 $where[$k] = $wpdb->prepare( "$alias.meta_key = %s", $meta_key );
1021 if ( is_null( $meta_value ) ) {
1022 if ( empty( $where[$k] ) )
1027 if ( in_array( $meta_compare, array( 'IN', 'NOT IN', 'BETWEEN', 'NOT BETWEEN' ) ) ) {
1028 if ( ! is_array( $meta_value ) )
1029 $meta_value = preg_split( '/[,\s]+/', $meta_value );
1031 if ( empty( $meta_value ) ) {
1036 $meta_value = trim( $meta_value );
1039 if ( 'IN' == substr( $meta_compare, -2) ) {
1040 $meta_compare_string = '(' . substr( str_repeat( ',%s', count( $meta_value ) ), 1 ) . ')';
1041 } elseif ( 'BETWEEN' == substr( $meta_compare, -7) ) {
1042 $meta_value = array_slice( $meta_value, 0, 2 );
1043 $meta_compare_string = '%s AND %s';
1044 } elseif ( 'LIKE' == substr( $meta_compare, -4 ) ) {
1045 $meta_value = '%' . like_escape( $meta_value ) . '%';
1046 $meta_compare_string = '%s';
1048 $meta_compare_string = '%s';
1051 if ( ! empty( $where[$k] ) )
1052 $where[$k] .= ' AND ';
1054 $where[$k] = ' (' . $where[$k] . $wpdb->prepare( "CAST($alias.meta_value AS {$meta_type}) {$meta_compare} {$meta_compare_string})", $meta_value );
1057 $where = array_filter( $where );
1059 if ( empty( $where ) )
1062 $where = ' AND (' . implode( "\n{$this->relation} ", $where ) . ' )';
1064 $join = implode( "\n", $join );
1065 if ( ! empty( $join ) )
1066 $join = ' ' . $join;
1069 * Filter the meta query's generated SQL.
1073 * @param array $args {
1074 * An array of arguments.
1076 * @type array $clauses Array containing the query's JOIN and WHERE clauses.
1077 * @type array $queries Array of meta queries.
1078 * @type string $type Type of meta.
1079 * @type string $primary_table Primary table.
1080 * @type string $primary_id_column Primary column ID.
1081 * @type object $context The main query object.
1084 return apply_filters_ref_array( 'get_meta_sql', array( compact( 'join', 'where' ), $this->queries, $type, $primary_table, $primary_id_column, $context ) );
1089 * Retrieve the name of the metadata table for the specified object type.
1092 * @uses $wpdb WordPress database object for queries.
1094 * @param string $type Type of object to get metadata table for (e.g., comment, post, or user)
1095 * @return mixed Metadata table name, or false if no metadata table exists
1097 function _get_meta_table($type) {
1100 $table_name = $type . 'meta';
1102 if ( empty($wpdb->$table_name) )
1105 return $wpdb->$table_name;
1109 * Determine whether a meta key is protected.
1113 * @param string $meta_key Meta key
1114 * @return bool True if the key is protected, false otherwise.
1116 function is_protected_meta( $meta_key, $meta_type = null ) {
1117 $protected = ( '_' == $meta_key[0] );
1120 * Filter whether a meta key is protected.
1124 * @param bool $protected Whether the key is protected. Default false.
1125 * @param string $meta_key Meta key.
1126 * @param string $meta_type Meta type.
1128 return apply_filters( 'is_protected_meta', $protected, $meta_key, $meta_type );
1132 * Sanitize meta value.
1136 * @param string $meta_key Meta key
1137 * @param mixed $meta_value Meta value to sanitize
1138 * @param string $meta_type Type of meta
1139 * @return mixed Sanitized $meta_value
1141 function sanitize_meta( $meta_key, $meta_value, $meta_type ) {
1144 * Filter the sanitization of a specific meta key of a specific meta type.
1146 * The dynamic portions of the hook name, $meta_type and $meta_key, refer to the
1147 * metadata object type (comment, post, or user) and the meta key value,
1152 * @param mixed $meta_value Meta value to sanitize.
1153 * @param string $meta_key Meta key.
1154 * @param string $meta_type Meta type.
1156 return apply_filters( "sanitize_{$meta_type}_meta_{$meta_key}", $meta_value, $meta_key, $meta_type );
1164 * @param string $meta_type Type of meta
1165 * @param string $meta_key Meta key
1166 * @param string|array $sanitize_callback A function or method to call when sanitizing the value of $meta_key.
1167 * @param string|array $auth_callback Optional. A function or method to call when performing edit_post_meta, add_post_meta, and delete_post_meta capability checks.
1168 * @param array $args Arguments
1170 function register_meta( $meta_type, $meta_key, $sanitize_callback, $auth_callback = null ) {
1171 if ( is_callable( $sanitize_callback ) )
1172 add_filter( "sanitize_{$meta_type}_meta_{$meta_key}", $sanitize_callback, 10, 3 );
1174 if ( empty( $auth_callback ) ) {
1175 if ( is_protected_meta( $meta_key, $meta_type ) )
1176 $auth_callback = '__return_false';
1178 $auth_callback = '__return_true';
1181 if ( is_callable( $auth_callback ) )
1182 add_filter( "auth_{$meta_type}_meta_{$meta_key}", $auth_callback, 10, 6 );