3 * Meta API: WP_Meta_Query class
11 * Core class used to implement meta queries for the Meta API.
13 * Used for generating SQL clauses that filter a primary query according to metadata keys and values.
15 * `WP_Meta_Query` is a helper that allows primary query classes, such as {@see WP_Query} and {@see WP_User_Query},
16 * to filter their results by object metadata, by generating `JOIN` and `WHERE` subclauses to be attached
17 * to the primary SQL query string.
25 * Array of metadata queries.
27 * See {@see WP_Meta_Query::__construct()} for information on meta query arguments.
33 public $queries = array();
36 * The relation between the queries. Can be one of 'AND' or 'OR'.
45 * Database table to query for the metadata.
54 * Column in meta_table that represents the ID of the object the metadata belongs to.
60 public $meta_id_column;
63 * Database table that where the metadata's objects are stored (eg $wpdb->users).
69 public $primary_table;
72 * Column in primary_table that represents the ID of the object.
78 public $primary_id_column;
81 * A flat list of table aliases used in JOIN clauses.
87 protected $table_aliases = array();
90 * A flat list of clauses, keyed by clause 'name'.
96 protected $clauses = array();
99 * Whether the query contains any OR relations.
105 protected $has_or_relation = false;
111 * @since 4.2.0 Introduced support for naming query clauses by associative array keys.
115 * @param array $meta_query {
116 * Array of meta query clauses. When first-order clauses use strings as their array keys, they may be
117 * referenced in the 'orderby' parameter of the parent query.
119 * @type string $relation Optional. The MySQL keyword used to join
120 * the clauses of the query. Accepts 'AND', or 'OR'. Default 'AND'.
122 * Optional. An array of first-order clause parameters, or another fully-formed meta query.
124 * @type string $key Meta key to filter by.
125 * @type string $value Meta value to filter by.
126 * @type string $compare MySQL operator used for comparing the $value. Accepts '=',
127 * '!=', '>', '>=', '<', '<=', 'LIKE', 'NOT LIKE',
128 * 'IN', 'NOT IN', 'BETWEEN', 'NOT BETWEEN', 'REGEXP',
129 * 'NOT REGEXP', 'RLIKE', 'EXISTS' or 'NOT EXISTS'.
130 * Default is 'IN' when `$value` is an array, '=' otherwise.
131 * @type string $type MySQL data type that the meta_value column will be CAST to for
132 * comparisons. Accepts 'NUMERIC', 'BINARY', 'CHAR', 'DATE',
133 * 'DATETIME', 'DECIMAL', 'SIGNED', 'TIME', or 'UNSIGNED'.
138 public function __construct( $meta_query = false ) {
142 if ( isset( $meta_query['relation'] ) && strtoupper( $meta_query['relation'] ) == 'OR' ) {
143 $this->relation = 'OR';
145 $this->relation = 'AND';
148 $this->queries = $this->sanitize_query( $meta_query );
152 * Ensure the 'meta_query' argument passed to the class constructor is well-formed.
154 * Eliminates empty items and ensures that a 'relation' is set.
159 * @param array $queries Array of query clauses.
160 * @return array Sanitized array of query clauses.
162 public function sanitize_query( $queries ) {
163 $clean_queries = array();
165 if ( ! is_array( $queries ) ) {
166 return $clean_queries;
169 foreach ( $queries as $key => $query ) {
170 if ( 'relation' === $key ) {
173 } elseif ( ! is_array( $query ) ) {
176 // First-order clause.
177 } elseif ( $this->is_first_order_clause( $query ) ) {
178 if ( isset( $query['value'] ) && array() === $query['value'] ) {
179 unset( $query['value'] );
182 $clean_queries[ $key ] = $query;
184 // Otherwise, it's a nested query, so we recurse.
186 $cleaned_query = $this->sanitize_query( $query );
188 if ( ! empty( $cleaned_query ) ) {
189 $clean_queries[ $key ] = $cleaned_query;
194 if ( empty( $clean_queries ) ) {
195 return $clean_queries;
198 // Sanitize the 'relation' key provided in the query.
199 if ( isset( $relation ) && 'OR' === strtoupper( $relation ) ) {
200 $clean_queries['relation'] = 'OR';
201 $this->has_or_relation = true;
204 * If there is only a single clause, call the relation 'OR'.
205 * This value will not actually be used to join clauses, but it
206 * simplifies the logic around combining key-only queries.
208 } elseif ( 1 === count( $clean_queries ) ) {
209 $clean_queries['relation'] = 'OR';
213 $clean_queries['relation'] = 'AND';
216 return $clean_queries;
220 * Determine whether a query clause is first-order.
222 * A first-order meta query clause is one that has either a 'key' or
223 * a 'value' array key.
228 * @param array $query Meta query arguments.
229 * @return bool Whether the query clause is a first-order clause.
231 protected function is_first_order_clause( $query ) {
232 return isset( $query['key'] ) || isset( $query['value'] );
236 * Constructs a meta query based on 'meta_*' query vars
241 * @param array $qv The query variables
243 public function parse_query_vars( $qv ) {
244 $meta_query = array();
247 * For orderby=meta_value to work correctly, simple query needs to be
248 * first (so that its table join is against an unaliased meta table) and
249 * needs to be its own clause (so it doesn't interfere with the logic of
250 * the rest of the meta_query).
252 $primary_meta_query = array();
253 foreach ( array( 'key', 'compare', 'type' ) as $key ) {
254 if ( ! empty( $qv[ "meta_$key" ] ) ) {
255 $primary_meta_query[ $key ] = $qv[ "meta_$key" ];
259 // WP_Query sets 'meta_value' = '' by default.
260 if ( isset( $qv['meta_value'] ) && '' !== $qv['meta_value'] && ( ! is_array( $qv['meta_value'] ) || $qv['meta_value'] ) ) {
261 $primary_meta_query['value'] = $qv['meta_value'];
264 $existing_meta_query = isset( $qv['meta_query'] ) && is_array( $qv['meta_query'] ) ? $qv['meta_query'] : array();
266 if ( ! empty( $primary_meta_query ) && ! empty( $existing_meta_query ) ) {
270 $existing_meta_query,
272 } elseif ( ! empty( $primary_meta_query ) ) {
276 } elseif ( ! empty( $existing_meta_query ) ) {
277 $meta_query = $existing_meta_query;
280 $this->__construct( $meta_query );
284 * Return the appropriate alias for the given meta type if applicable.
289 * @param string $type MySQL type to cast meta_value.
290 * @return string MySQL type.
292 public function get_cast_for_type( $type = '' ) {
293 if ( empty( $type ) )
296 $meta_type = strtoupper( $type );
298 if ( ! preg_match( '/^(?:BINARY|CHAR|DATE|DATETIME|SIGNED|UNSIGNED|TIME|NUMERIC(?:\(\d+(?:,\s?\d+)?\))?|DECIMAL(?:\(\d+(?:,\s?\d+)?\))?)$/', $meta_type ) )
301 if ( 'NUMERIC' == $meta_type )
302 $meta_type = 'SIGNED';
308 * Generates SQL clauses to be appended to a main query.
313 * @param string $type Type of meta, eg 'user', 'post'.
314 * @param string $primary_table Database table where the object being filtered is stored (eg wp_users).
315 * @param string $primary_id_column ID column for the filtered object in $primary_table.
316 * @param object $context Optional. The main query object.
317 * @return false|array {
318 * Array containing JOIN and WHERE SQL clauses to append to the main query.
320 * @type string $join SQL fragment to append to the main JOIN clause.
321 * @type string $where SQL fragment to append to the main WHERE clause.
324 public function get_sql( $type, $primary_table, $primary_id_column, $context = null ) {
325 if ( ! $meta_table = _get_meta_table( $type ) ) {
329 $this->meta_table = $meta_table;
330 $this->meta_id_column = sanitize_key( $type . '_id' );
332 $this->primary_table = $primary_table;
333 $this->primary_id_column = $primary_id_column;
335 $sql = $this->get_sql_clauses();
338 * If any JOINs are LEFT JOINs (as in the case of NOT EXISTS), then all JOINs should
339 * be LEFT. Otherwise posts with no metadata will be excluded from results.
341 if ( false !== strpos( $sql['join'], 'LEFT JOIN' ) ) {
342 $sql['join'] = str_replace( 'INNER JOIN', 'LEFT JOIN', $sql['join'] );
346 * Filter the meta query's generated SQL.
350 * @param array $clauses Array containing the query's JOIN and WHERE clauses.
351 * @param array $queries Array of meta queries.
352 * @param string $type Type of meta.
353 * @param string $primary_table Primary table.
354 * @param string $primary_id_column Primary column ID.
355 * @param object $context The main query object.
357 return apply_filters_ref_array( 'get_meta_sql', array( $sql, $this->queries, $type, $primary_table, $primary_id_column, $context ) );
361 * Generate SQL clauses to be appended to a main query.
363 * Called by the public {@see WP_Meta_Query::get_sql()}, this method
364 * is abstracted out to maintain parity with the other Query classes.
370 * Array containing JOIN and WHERE SQL clauses to append to the main query.
372 * @type string $join SQL fragment to append to the main JOIN clause.
373 * @type string $where SQL fragment to append to the main WHERE clause.
376 protected function get_sql_clauses() {
378 * $queries are passed by reference to get_sql_for_query() for recursion.
379 * To keep $this->queries unaltered, pass a copy.
381 $queries = $this->queries;
382 $sql = $this->get_sql_for_query( $queries );
384 if ( ! empty( $sql['where'] ) ) {
385 $sql['where'] = ' AND ' . $sql['where'];
392 * Generate SQL clauses for a single query array.
394 * If nested subqueries are found, this method recurses the tree to
395 * produce the properly nested SQL.
400 * @param array $query Query to parse, passed by reference.
401 * @param int $depth Optional. Number of tree levels deep we currently are.
402 * Used to calculate indentation. Default 0.
404 * Array containing JOIN and WHERE SQL clauses to append to a single query array.
406 * @type string $join SQL fragment to append to the main JOIN clause.
407 * @type string $where SQL fragment to append to the main WHERE clause.
410 protected function get_sql_for_query( &$query, $depth = 0 ) {
422 for ( $i = 0; $i < $depth; $i++ ) {
426 foreach ( $query as $key => &$clause ) {
427 if ( 'relation' === $key ) {
428 $relation = $query['relation'];
429 } elseif ( is_array( $clause ) ) {
431 // This is a first-order clause.
432 if ( $this->is_first_order_clause( $clause ) ) {
433 $clause_sql = $this->get_sql_for_clause( $clause, $query, $key );
435 $where_count = count( $clause_sql['where'] );
436 if ( ! $where_count ) {
437 $sql_chunks['where'][] = '';
438 } elseif ( 1 === $where_count ) {
439 $sql_chunks['where'][] = $clause_sql['where'][0];
441 $sql_chunks['where'][] = '( ' . implode( ' AND ', $clause_sql['where'] ) . ' )';
444 $sql_chunks['join'] = array_merge( $sql_chunks['join'], $clause_sql['join'] );
445 // This is a subquery, so we recurse.
447 $clause_sql = $this->get_sql_for_query( $clause, $depth + 1 );
449 $sql_chunks['where'][] = $clause_sql['where'];
450 $sql_chunks['join'][] = $clause_sql['join'];
455 // Filter to remove empties.
456 $sql_chunks['join'] = array_filter( $sql_chunks['join'] );
457 $sql_chunks['where'] = array_filter( $sql_chunks['where'] );
459 if ( empty( $relation ) ) {
463 // Filter duplicate JOIN clauses and combine into a single string.
464 if ( ! empty( $sql_chunks['join'] ) ) {
465 $sql['join'] = implode( ' ', array_unique( $sql_chunks['join'] ) );
468 // Generate a single WHERE clause with proper brackets and indentation.
469 if ( ! empty( $sql_chunks['where'] ) ) {
470 $sql['where'] = '( ' . "\n " . $indent . implode( ' ' . "\n " . $indent . $relation . ' ' . "\n " . $indent, $sql_chunks['where'] ) . "\n" . $indent . ')';
477 * Generate SQL JOIN and WHERE clauses for a first-order query clause.
479 * "First-order" means that it's an array with a 'key' or 'value'.
484 * @global wpdb $wpdb WordPress database abstraction object.
486 * @param array $clause Query clause, passed by reference.
487 * @param array $parent_query Parent query array.
488 * @param string $clause_key Optional. The array key used to name the clause in the original `$meta_query`
489 * parameters. If not provided, a key will be generated automatically.
491 * Array containing JOIN and WHERE SQL clauses to append to a first-order query.
493 * @type string $join SQL fragment to append to the main JOIN clause.
494 * @type string $where SQL fragment to append to the main WHERE clause.
497 public function get_sql_for_clause( &$clause, $parent_query, $clause_key = '' ) {
505 if ( isset( $clause['compare'] ) ) {
506 $clause['compare'] = strtoupper( $clause['compare'] );
508 $clause['compare'] = isset( $clause['value'] ) && is_array( $clause['value'] ) ? 'IN' : '=';
511 if ( ! in_array( $clause['compare'], array(
512 '=', '!=', '>', '>=', '<', '<=',
515 'BETWEEN', 'NOT BETWEEN',
516 'EXISTS', 'NOT EXISTS',
517 'REGEXP', 'NOT REGEXP', 'RLIKE'
519 $clause['compare'] = '=';
522 $meta_compare = $clause['compare'];
524 // First build the JOIN clause, if one is required.
527 // We prefer to avoid joins if possible. Look for an existing join compatible with this clause.
528 $alias = $this->find_compatible_table_alias( $clause, $parent_query );
529 if ( false === $alias ) {
530 $i = count( $this->table_aliases );
531 $alias = $i ? 'mt' . $i : $this->meta_table;
533 // JOIN clauses for NOT EXISTS have their own syntax.
534 if ( 'NOT EXISTS' === $meta_compare ) {
535 $join .= " LEFT JOIN $this->meta_table";
536 $join .= $i ? " AS $alias" : '';
537 $join .= $wpdb->prepare( " ON ($this->primary_table.$this->primary_id_column = $alias.$this->meta_id_column AND $alias.meta_key = %s )", $clause['key'] );
539 // All other JOIN clauses.
541 $join .= " INNER JOIN $this->meta_table";
542 $join .= $i ? " AS $alias" : '';
543 $join .= " ON ( $this->primary_table.$this->primary_id_column = $alias.$this->meta_id_column )";
546 $this->table_aliases[] = $alias;
547 $sql_chunks['join'][] = $join;
550 // Save the alias to this clause, for future siblings to find.
551 $clause['alias'] = $alias;
553 // Determine the data type.
554 $_meta_type = isset( $clause['type'] ) ? $clause['type'] : '';
555 $meta_type = $this->get_cast_for_type( $_meta_type );
556 $clause['cast'] = $meta_type;
558 // Fallback for clause keys is the table alias. Key must be a string.
559 if ( is_int( $clause_key ) || ! $clause_key ) {
560 $clause_key = $clause['alias'];
563 // Ensure unique clause keys, so none are overwritten.
565 $clause_key_base = $clause_key;
566 while ( isset( $this->clauses[ $clause_key ] ) ) {
567 $clause_key = $clause_key_base . '-' . $iterator;
571 // Store the clause in our flat array.
572 $this->clauses[ $clause_key ] =& $clause;
574 // Next, build the WHERE clause.
577 if ( array_key_exists( 'key', $clause ) ) {
578 if ( 'NOT EXISTS' === $meta_compare ) {
579 $sql_chunks['where'][] = $alias . '.' . $this->meta_id_column . ' IS NULL';
581 $sql_chunks['where'][] = $wpdb->prepare( "$alias.meta_key = %s", trim( $clause['key'] ) );
586 if ( array_key_exists( 'value', $clause ) ) {
587 $meta_value = $clause['value'];
589 if ( in_array( $meta_compare, array( 'IN', 'NOT IN', 'BETWEEN', 'NOT BETWEEN' ) ) ) {
590 if ( ! is_array( $meta_value ) ) {
591 $meta_value = preg_split( '/[,\s]+/', $meta_value );
594 $meta_value = trim( $meta_value );
597 switch ( $meta_compare ) {
600 $meta_compare_string = '(' . substr( str_repeat( ',%s', count( $meta_value ) ), 1 ) . ')';
601 $where = $wpdb->prepare( $meta_compare_string, $meta_value );
606 $meta_value = array_slice( $meta_value, 0, 2 );
607 $where = $wpdb->prepare( '%s AND %s', $meta_value );
612 $meta_value = '%' . $wpdb->esc_like( $meta_value ) . '%';
613 $where = $wpdb->prepare( '%s', $meta_value );
616 // EXISTS with a value is interpreted as '='.
619 $where = $wpdb->prepare( '%s', $meta_value );
622 // 'value' is ignored for NOT EXISTS.
628 $where = $wpdb->prepare( '%s', $meta_value );
634 $sql_chunks['where'][] = "CAST($alias.meta_value AS {$meta_type}) {$meta_compare} {$where}";
639 * Multiple WHERE clauses (for meta_key and meta_value) should
640 * be joined in parentheses.
642 if ( 1 < count( $sql_chunks['where'] ) ) {
643 $sql_chunks['where'] = array( '( ' . implode( ' AND ', $sql_chunks['where'] ) . ' )' );
650 * Get a flattened list of sanitized meta clauses.
652 * This array should be used for clause lookup, as when the table alias and CAST type must be determined for
653 * a value of 'orderby' corresponding to a meta clause.
658 * @return array Meta clauses.
660 public function get_clauses() {
661 return $this->clauses;
665 * Identify an existing table alias that is compatible with the current
668 * We avoid unnecessary table joins by allowing each clause to look for
669 * an existing table alias that is compatible with the query that it
672 * An existing alias is compatible if (a) it is a sibling of `$clause`
673 * (ie, it's under the scope of the same relation), and (b) the combination
674 * of operator and relation between the clauses allows for a shared table join.
675 * In the case of {@see WP_Meta_Query}, this only applies to 'IN' clauses that
676 * are connected by the relation 'OR'.
681 * @param array $clause Query clause.
682 * @param array $parent_query Parent query of $clause.
683 * @return string|bool Table alias if found, otherwise false.
685 protected function find_compatible_table_alias( $clause, $parent_query ) {
688 foreach ( $parent_query as $sibling ) {
689 // If the sibling has no alias yet, there's nothing to check.
690 if ( empty( $sibling['alias'] ) ) {
694 // We're only interested in siblings that are first-order clauses.
695 if ( ! is_array( $sibling ) || ! $this->is_first_order_clause( $sibling ) ) {
699 $compatible_compares = array();
701 // Clauses connected by OR can share joins as long as they have "positive" operators.
702 if ( 'OR' === $parent_query['relation'] ) {
703 $compatible_compares = array( '=', 'IN', 'BETWEEN', 'LIKE', 'REGEXP', 'RLIKE', '>', '>=', '<', '<=' );
705 // Clauses joined by AND with "negative" operators share a join only if they also share a key.
706 } elseif ( isset( $sibling['key'] ) && isset( $clause['key'] ) && $sibling['key'] === $clause['key'] ) {
707 $compatible_compares = array( '!=', 'NOT IN', 'NOT LIKE' );
710 $clause_compare = strtoupper( $clause['compare'] );
711 $sibling_compare = strtoupper( $sibling['compare'] );
712 if ( in_array( $clause_compare, $compatible_compares ) && in_array( $sibling_compare, $compatible_compares ) ) {
713 $alias = $sibling['alias'];
719 * Filter the table alias identified as compatible with the current clause.
723 * @param string|bool $alias Table alias, or false if none was found.
724 * @param array $clause First-order query clause.
725 * @param array $parent_query Parent of $clause.
726 * @param object $this WP_Meta_Query object.
728 return apply_filters( 'meta_query_find_compatible_table_alias', $alias, $clause, $parent_query, $this ) ;
732 * Checks whether the current query has any OR relations.
734 * In some cases, the presence of an OR relation somewhere in the query will require
735 * the use of a `DISTINCT` or `GROUP BY` keyword in the `SELECT` clause. The current
736 * method can be used in these cases to determine whether such a clause is necessary.
740 * @return bool True if the query contains any `OR` relations, otherwise false.
742 public function has_or_relation() {
743 return $this->has_or_relation;