wp/wp-includes/class-wp-tax-query.php
changeset 7 cf61fcea0001
child 9 177826044cd9
equal deleted inserted replaced
6:490d5cc509ed 7:cf61fcea0001
       
     1 <?php
       
     2 /**
       
     3  * Taxonomy API: WP_Tax_Query class
       
     4  *
       
     5  * @package WordPress
       
     6  * @subpackage Taxonomy
       
     7  * @since 4.4.0
       
     8  */
       
     9 
       
    10 /**
       
    11  * Core class used to implement taxonomy queries for the Taxonomy API.
       
    12  *
       
    13  * Used for generating SQL clauses that filter a primary query according to object
       
    14  * taxonomy terms.
       
    15  *
       
    16  * WP_Tax_Query is a helper that allows primary query classes, such as WP_Query, to filter
       
    17  * their results by object metadata, by generating `JOIN` and `WHERE` subclauses to be
       
    18  * attached to the primary SQL query string.
       
    19  *
       
    20  * @since 3.1.0
       
    21  */
       
    22 class WP_Tax_Query {
       
    23 
       
    24 	/**
       
    25 	 * Array of taxonomy queries.
       
    26 	 *
       
    27 	 * See WP_Tax_Query::__construct() for information on tax query arguments.
       
    28 	 *
       
    29 	 * @since 3.1.0
       
    30 	 * @var array
       
    31 	 */
       
    32 	public $queries = array();
       
    33 
       
    34 	/**
       
    35 	 * The relation between the queries. Can be one of 'AND' or 'OR'.
       
    36 	 *
       
    37 	 * @since 3.1.0
       
    38 	 * @var string
       
    39 	 */
       
    40 	public $relation;
       
    41 
       
    42 	/**
       
    43 	 * Standard response when the query should not return any rows.
       
    44 	 *
       
    45 	 * @since 3.2.0
       
    46 	 *
       
    47 	 * @static
       
    48 	 * @var string
       
    49 	 */
       
    50 	private static $no_results = array( 'join' => array( '' ), 'where' => array( '0 = 1' ) );
       
    51 
       
    52 	/**
       
    53 	 * A flat list of table aliases used in the JOIN clauses.
       
    54 	 *
       
    55 	 * @since 4.1.0
       
    56 	 * @var array
       
    57 	 */
       
    58 	protected $table_aliases = array();
       
    59 
       
    60 	/**
       
    61 	 * Terms and taxonomies fetched by this query.
       
    62 	 *
       
    63 	 * We store this data in a flat array because they are referenced in a
       
    64 	 * number of places by WP_Query.
       
    65 	 *
       
    66 	 * @since 4.1.0
       
    67 	 * @var array
       
    68 	 */
       
    69 	public $queried_terms = array();
       
    70 
       
    71 	/**
       
    72 	 * Database table that where the metadata's objects are stored (eg $wpdb->users).
       
    73 	 *
       
    74 	 * @since 4.1.0
       
    75 	 * @var string
       
    76 	 */
       
    77 	public $primary_table;
       
    78 
       
    79 	/**
       
    80 	 * Column in 'primary_table' that represents the ID of the object.
       
    81 	 *
       
    82 	 * @since 4.1.0
       
    83 	 * @var string
       
    84 	 */
       
    85 	public $primary_id_column;
       
    86 
       
    87 	/**
       
    88 	 * Constructor.
       
    89 	 *
       
    90 	 * @since 3.1.0
       
    91 	 * @since 4.1.0 Added support for `$operator` 'NOT EXISTS' and 'EXISTS' values.
       
    92 	 *
       
    93 	 * @param array $tax_query {
       
    94 	 *     Array of taxonomy query clauses.
       
    95 	 *
       
    96 	 *     @type string $relation Optional. The MySQL keyword used to join
       
    97 	 *                            the clauses of the query. Accepts 'AND', or 'OR'. Default 'AND'.
       
    98 	 *     @type array {
       
    99 	 *         Optional. An array of first-order clause parameters, or another fully-formed tax query.
       
   100 	 *
       
   101 	 *         @type string           $taxonomy         Taxonomy being queried. Optional when field=term_taxonomy_id.
       
   102 	 *         @type string|int|array $terms            Term or terms to filter by.
       
   103 	 *         @type string           $field            Field to match $terms against. Accepts 'term_id', 'slug',
       
   104 	 *                                                 'name', or 'term_taxonomy_id'. Default: 'term_id'.
       
   105 	 *         @type string           $operator         MySQL operator to be used with $terms in the WHERE clause.
       
   106 	 *                                                  Accepts 'AND', 'IN', 'NOT IN', 'EXISTS', 'NOT EXISTS'.
       
   107 	 *                                                  Default: 'IN'.
       
   108 	 *         @type bool             $include_children Optional. Whether to include child terms.
       
   109 	 *                                                  Requires a $taxonomy. Default: true.
       
   110 	 *     }
       
   111 	 * }
       
   112 	 */
       
   113 	public function __construct( $tax_query ) {
       
   114 		if ( isset( $tax_query['relation'] ) ) {
       
   115 			$this->relation = $this->sanitize_relation( $tax_query['relation'] );
       
   116 		} else {
       
   117 			$this->relation = 'AND';
       
   118 		}
       
   119 
       
   120 		$this->queries = $this->sanitize_query( $tax_query );
       
   121 	}
       
   122 
       
   123 	/**
       
   124 	 * Ensure the 'tax_query' argument passed to the class constructor is well-formed.
       
   125 	 *
       
   126 	 * Ensures that each query-level clause has a 'relation' key, and that
       
   127 	 * each first-order clause contains all the necessary keys from `$defaults`.
       
   128 	 *
       
   129 	 * @since 4.1.0
       
   130 	 *
       
   131 	 * @param array $queries Array of queries clauses.
       
   132 	 * @return array Sanitized array of query clauses.
       
   133 	 */
       
   134 	public function sanitize_query( $queries ) {
       
   135 		$cleaned_query = array();
       
   136 
       
   137 		$defaults = array(
       
   138 			'taxonomy' => '',
       
   139 			'terms' => array(),
       
   140 			'field' => 'term_id',
       
   141 			'operator' => 'IN',
       
   142 			'include_children' => true,
       
   143 		);
       
   144 
       
   145 		foreach ( $queries as $key => $query ) {
       
   146 			if ( 'relation' === $key ) {
       
   147 				$cleaned_query['relation'] = $this->sanitize_relation( $query );
       
   148 
       
   149 			// First-order clause.
       
   150 			} elseif ( self::is_first_order_clause( $query ) ) {
       
   151 
       
   152 				$cleaned_clause = array_merge( $defaults, $query );
       
   153 				$cleaned_clause['terms'] = (array) $cleaned_clause['terms'];
       
   154 				$cleaned_query[] = $cleaned_clause;
       
   155 
       
   156 				/*
       
   157 				 * Keep a copy of the clause in the flate
       
   158 				 * $queried_terms array, for use in WP_Query.
       
   159 				 */
       
   160 				if ( ! empty( $cleaned_clause['taxonomy'] ) && 'NOT IN' !== $cleaned_clause['operator'] ) {
       
   161 					$taxonomy = $cleaned_clause['taxonomy'];
       
   162 					if ( ! isset( $this->queried_terms[ $taxonomy ] ) ) {
       
   163 						$this->queried_terms[ $taxonomy ] = array();
       
   164 					}
       
   165 
       
   166 					/*
       
   167 					 * Backward compatibility: Only store the first
       
   168 					 * 'terms' and 'field' found for a given taxonomy.
       
   169 					 */
       
   170 					if ( ! empty( $cleaned_clause['terms'] ) && ! isset( $this->queried_terms[ $taxonomy ]['terms'] ) ) {
       
   171 						$this->queried_terms[ $taxonomy ]['terms'] = $cleaned_clause['terms'];
       
   172 					}
       
   173 
       
   174 					if ( ! empty( $cleaned_clause['field'] ) && ! isset( $this->queried_terms[ $taxonomy ]['field'] ) ) {
       
   175 						$this->queried_terms[ $taxonomy ]['field'] = $cleaned_clause['field'];
       
   176 					}
       
   177 				}
       
   178 
       
   179 			// Otherwise, it's a nested query, so we recurse.
       
   180 			} elseif ( is_array( $query ) ) {
       
   181 				$cleaned_subquery = $this->sanitize_query( $query );
       
   182 
       
   183 				if ( ! empty( $cleaned_subquery ) ) {
       
   184 					// All queries with children must have a relation.
       
   185 					if ( ! isset( $cleaned_subquery['relation'] ) ) {
       
   186 						$cleaned_subquery['relation'] = 'AND';
       
   187 					}
       
   188 
       
   189 					$cleaned_query[] = $cleaned_subquery;
       
   190 				}
       
   191 			}
       
   192 		}
       
   193 
       
   194 		return $cleaned_query;
       
   195 	}
       
   196 
       
   197 	/**
       
   198 	 * Sanitize a 'relation' operator.
       
   199 	 *
       
   200 	 * @since 4.1.0
       
   201 	 *
       
   202 	 * @param string $relation Raw relation key from the query argument.
       
   203 	 * @return string Sanitized relation ('AND' or 'OR').
       
   204 	 */
       
   205 	public function sanitize_relation( $relation ) {
       
   206 		if ( 'OR' === strtoupper( $relation ) ) {
       
   207 			return 'OR';
       
   208 		} else {
       
   209 			return 'AND';
       
   210 		}
       
   211 	}
       
   212 
       
   213 	/**
       
   214 	 * Determine whether a clause is first-order.
       
   215 	 *
       
   216 	 * A "first-order" clause is one that contains any of the first-order
       
   217 	 * clause keys ('terms', 'taxonomy', 'include_children', 'field',
       
   218 	 * 'operator'). An empty clause also counts as a first-order clause,
       
   219 	 * for backward compatibility. Any clause that doesn't meet this is
       
   220 	 * determined, by process of elimination, to be a higher-order query.
       
   221 	 *
       
   222 	 * @since 4.1.0
       
   223 	 *
       
   224 	 * @static
       
   225 	 *
       
   226 	 * @param array $query Tax query arguments.
       
   227 	 * @return bool Whether the query clause is a first-order clause.
       
   228 	 */
       
   229 	protected static function is_first_order_clause( $query ) {
       
   230 		return is_array( $query ) && ( empty( $query ) || array_key_exists( 'terms', $query ) || array_key_exists( 'taxonomy', $query ) || array_key_exists( 'include_children', $query ) || array_key_exists( 'field', $query ) || array_key_exists( 'operator', $query ) );
       
   231 	}
       
   232 
       
   233 	/**
       
   234 	 * Generates SQL clauses to be appended to a main query.
       
   235 	 *
       
   236 	 * @since 3.1.0
       
   237 	 *
       
   238 	 * @static
       
   239 	 *
       
   240 	 * @param string $primary_table     Database table where the object being filtered is stored (eg wp_users).
       
   241 	 * @param string $primary_id_column ID column for the filtered object in $primary_table.
       
   242 	 * @return array {
       
   243 	 *     Array containing JOIN and WHERE SQL clauses to append to the main query.
       
   244 	 *
       
   245 	 *     @type string $join  SQL fragment to append to the main JOIN clause.
       
   246 	 *     @type string $where SQL fragment to append to the main WHERE clause.
       
   247 	 * }
       
   248 	 */
       
   249 	public function get_sql( $primary_table, $primary_id_column ) {
       
   250 		$this->primary_table = $primary_table;
       
   251 		$this->primary_id_column = $primary_id_column;
       
   252 
       
   253 		return $this->get_sql_clauses();
       
   254 	}
       
   255 
       
   256 	/**
       
   257 	 * Generate SQL clauses to be appended to a main query.
       
   258 	 *
       
   259 	 * Called by the public WP_Tax_Query::get_sql(), this method
       
   260 	 * is abstracted out to maintain parity with the other Query classes.
       
   261 	 *
       
   262 	 * @since 4.1.0
       
   263 	 *
       
   264 	 * @return array {
       
   265 	 *     Array containing JOIN and WHERE SQL clauses to append to the main query.
       
   266 	 *
       
   267 	 *     @type string $join  SQL fragment to append to the main JOIN clause.
       
   268 	 *     @type string $where SQL fragment to append to the main WHERE clause.
       
   269 	 * }
       
   270 	 */
       
   271 	protected function get_sql_clauses() {
       
   272 		/*
       
   273 		 * $queries are passed by reference to get_sql_for_query() for recursion.
       
   274 		 * To keep $this->queries unaltered, pass a copy.
       
   275 		 */
       
   276 		$queries = $this->queries;
       
   277 		$sql = $this->get_sql_for_query( $queries );
       
   278 
       
   279 		if ( ! empty( $sql['where'] ) ) {
       
   280 			$sql['where'] = ' AND ' . $sql['where'];
       
   281 		}
       
   282 
       
   283 		return $sql;
       
   284 	}
       
   285 
       
   286 	/**
       
   287 	 * Generate SQL clauses for a single query array.
       
   288 	 *
       
   289 	 * If nested subqueries are found, this method recurses the tree to
       
   290 	 * produce the properly nested SQL.
       
   291 	 *
       
   292 	 * @since 4.1.0
       
   293 	 *
       
   294 	 * @param array $query Query to parse (passed by reference).
       
   295 	 * @param int   $depth Optional. Number of tree levels deep we currently are.
       
   296 	 *                     Used to calculate indentation. Default 0.
       
   297 	 * @return array {
       
   298 	 *     Array containing JOIN and WHERE SQL clauses to append to a single query array.
       
   299 	 *
       
   300 	 *     @type string $join  SQL fragment to append to the main JOIN clause.
       
   301 	 *     @type string $where SQL fragment to append to the main WHERE clause.
       
   302 	 * }
       
   303 	 */
       
   304 	protected function get_sql_for_query( &$query, $depth = 0 ) {
       
   305 		$sql_chunks = array(
       
   306 			'join'  => array(),
       
   307 			'where' => array(),
       
   308 		);
       
   309 
       
   310 		$sql = array(
       
   311 			'join'  => '',
       
   312 			'where' => '',
       
   313 		);
       
   314 
       
   315 		$indent = '';
       
   316 		for ( $i = 0; $i < $depth; $i++ ) {
       
   317 			$indent .= "  ";
       
   318 		}
       
   319 
       
   320 		foreach ( $query as $key => &$clause ) {
       
   321 			if ( 'relation' === $key ) {
       
   322 				$relation = $query['relation'];
       
   323 			} elseif ( is_array( $clause ) ) {
       
   324 
       
   325 				// This is a first-order clause.
       
   326 				if ( $this->is_first_order_clause( $clause ) ) {
       
   327 					$clause_sql = $this->get_sql_for_clause( $clause, $query );
       
   328 
       
   329 					$where_count = count( $clause_sql['where'] );
       
   330 					if ( ! $where_count ) {
       
   331 						$sql_chunks['where'][] = '';
       
   332 					} elseif ( 1 === $where_count ) {
       
   333 						$sql_chunks['where'][] = $clause_sql['where'][0];
       
   334 					} else {
       
   335 						$sql_chunks['where'][] = '( ' . implode( ' AND ', $clause_sql['where'] ) . ' )';
       
   336 					}
       
   337 
       
   338 					$sql_chunks['join'] = array_merge( $sql_chunks['join'], $clause_sql['join'] );
       
   339 				// This is a subquery, so we recurse.
       
   340 				} else {
       
   341 					$clause_sql = $this->get_sql_for_query( $clause, $depth + 1 );
       
   342 
       
   343 					$sql_chunks['where'][] = $clause_sql['where'];
       
   344 					$sql_chunks['join'][]  = $clause_sql['join'];
       
   345 				}
       
   346 			}
       
   347 		}
       
   348 
       
   349 		// Filter to remove empties.
       
   350 		$sql_chunks['join']  = array_filter( $sql_chunks['join'] );
       
   351 		$sql_chunks['where'] = array_filter( $sql_chunks['where'] );
       
   352 
       
   353 		if ( empty( $relation ) ) {
       
   354 			$relation = 'AND';
       
   355 		}
       
   356 
       
   357 		// Filter duplicate JOIN clauses and combine into a single string.
       
   358 		if ( ! empty( $sql_chunks['join'] ) ) {
       
   359 			$sql['join'] = implode( ' ', array_unique( $sql_chunks['join'] ) );
       
   360 		}
       
   361 
       
   362 		// Generate a single WHERE clause with proper brackets and indentation.
       
   363 		if ( ! empty( $sql_chunks['where'] ) ) {
       
   364 			$sql['where'] = '( ' . "\n  " . $indent . implode( ' ' . "\n  " . $indent . $relation . ' ' . "\n  " . $indent, $sql_chunks['where'] ) . "\n" . $indent . ')';
       
   365 		}
       
   366 
       
   367 		return $sql;
       
   368 	}
       
   369 
       
   370 	/**
       
   371 	 * Generate SQL JOIN and WHERE clauses for a "first-order" query clause.
       
   372 	 *
       
   373 	 * @since 4.1.0
       
   374 	 *
       
   375 	 * @global wpdb $wpdb The WordPress database abstraction object.
       
   376 	 *
       
   377 	 * @param array $clause       Query clause (passed by reference).
       
   378 	 * @param array $parent_query Parent query array.
       
   379 	 * @return array {
       
   380 	 *     Array containing JOIN and WHERE SQL clauses to append to a first-order query.
       
   381 	 *
       
   382 	 *     @type string $join  SQL fragment to append to the main JOIN clause.
       
   383 	 *     @type string $where SQL fragment to append to the main WHERE clause.
       
   384 	 * }
       
   385 	 */
       
   386 	public function get_sql_for_clause( &$clause, $parent_query ) {
       
   387 		global $wpdb;
       
   388 
       
   389 		$sql = array(
       
   390 			'where' => array(),
       
   391 			'join'  => array(),
       
   392 		);
       
   393 
       
   394 		$join = $where = '';
       
   395 
       
   396 		$this->clean_query( $clause );
       
   397 
       
   398 		if ( is_wp_error( $clause ) ) {
       
   399 			return self::$no_results;
       
   400 		}
       
   401 
       
   402 		$terms = $clause['terms'];
       
   403 		$operator = strtoupper( $clause['operator'] );
       
   404 
       
   405 		if ( 'IN' == $operator ) {
       
   406 
       
   407 			if ( empty( $terms ) ) {
       
   408 				return self::$no_results;
       
   409 			}
       
   410 
       
   411 			$terms = implode( ',', $terms );
       
   412 
       
   413 			/*
       
   414 			 * Before creating another table join, see if this clause has a
       
   415 			 * sibling with an existing join that can be shared.
       
   416 			 */
       
   417 			$alias = $this->find_compatible_table_alias( $clause, $parent_query );
       
   418 			if ( false === $alias ) {
       
   419 				$i = count( $this->table_aliases );
       
   420 				$alias = $i ? 'tt' . $i : $wpdb->term_relationships;
       
   421 
       
   422 				// Store the alias as part of a flat array to build future iterators.
       
   423 				$this->table_aliases[] = $alias;
       
   424 
       
   425 				// Store the alias with this clause, so later siblings can use it.
       
   426 				$clause['alias'] = $alias;
       
   427 
       
   428 				$join .= " LEFT JOIN $wpdb->term_relationships";
       
   429 				$join .= $i ? " AS $alias" : '';
       
   430 				$join .= " ON ($this->primary_table.$this->primary_id_column = $alias.object_id)";
       
   431 			}
       
   432 
       
   433 
       
   434 			$where = "$alias.term_taxonomy_id $operator ($terms)";
       
   435 
       
   436 		} elseif ( 'NOT IN' == $operator ) {
       
   437 
       
   438 			if ( empty( $terms ) ) {
       
   439 				return $sql;
       
   440 			}
       
   441 
       
   442 			$terms = implode( ',', $terms );
       
   443 
       
   444 			$where = "$this->primary_table.$this->primary_id_column NOT IN (
       
   445 				SELECT object_id
       
   446 				FROM $wpdb->term_relationships
       
   447 				WHERE term_taxonomy_id IN ($terms)
       
   448 			)";
       
   449 
       
   450 		} elseif ( 'AND' == $operator ) {
       
   451 
       
   452 			if ( empty( $terms ) ) {
       
   453 				return $sql;
       
   454 			}
       
   455 
       
   456 			$num_terms = count( $terms );
       
   457 
       
   458 			$terms = implode( ',', $terms );
       
   459 
       
   460 			$where = "(
       
   461 				SELECT COUNT(1)
       
   462 				FROM $wpdb->term_relationships
       
   463 				WHERE term_taxonomy_id IN ($terms)
       
   464 				AND object_id = $this->primary_table.$this->primary_id_column
       
   465 			) = $num_terms";
       
   466 
       
   467 		} elseif ( 'NOT EXISTS' === $operator || 'EXISTS' === $operator ) {
       
   468 
       
   469 			$where = $wpdb->prepare( "$operator (
       
   470 				SELECT 1
       
   471 				FROM $wpdb->term_relationships
       
   472 				INNER JOIN $wpdb->term_taxonomy
       
   473 				ON $wpdb->term_taxonomy.term_taxonomy_id = $wpdb->term_relationships.term_taxonomy_id
       
   474 				WHERE $wpdb->term_taxonomy.taxonomy = %s
       
   475 				AND $wpdb->term_relationships.object_id = $this->primary_table.$this->primary_id_column
       
   476 			)", $clause['taxonomy'] );
       
   477 
       
   478 		}
       
   479 
       
   480 		$sql['join'][]  = $join;
       
   481 		$sql['where'][] = $where;
       
   482 		return $sql;
       
   483 	}
       
   484 
       
   485 	/**
       
   486 	 * Identify an existing table alias that is compatible with the current query clause.
       
   487 	 *
       
   488 	 * We avoid unnecessary table joins by allowing each clause to look for
       
   489 	 * an existing table alias that is compatible with the query that it
       
   490 	 * needs to perform.
       
   491 	 *
       
   492 	 * An existing alias is compatible if (a) it is a sibling of `$clause`
       
   493 	 * (ie, it's under the scope of the same relation), and (b) the combination
       
   494 	 * of operator and relation between the clauses allows for a shared table
       
   495 	 * join. In the case of WP_Tax_Query, this only applies to 'IN'
       
   496 	 * clauses that are connected by the relation 'OR'.
       
   497 	 *
       
   498 	 * @since 4.1.0
       
   499 	 *
       
   500 	 * @param array       $clause       Query clause.
       
   501 	 * @param array       $parent_query Parent query of $clause.
       
   502 	 * @return string|false Table alias if found, otherwise false.
       
   503 	 */
       
   504 	protected function find_compatible_table_alias( $clause, $parent_query ) {
       
   505 		$alias = false;
       
   506 
       
   507 		// Sanity check. Only IN queries use the JOIN syntax .
       
   508 		if ( ! isset( $clause['operator'] ) || 'IN' !== $clause['operator'] ) {
       
   509 			return $alias;
       
   510 		}
       
   511 
       
   512 		// Since we're only checking IN queries, we're only concerned with OR relations.
       
   513 		if ( ! isset( $parent_query['relation'] ) || 'OR' !== $parent_query['relation'] ) {
       
   514 			return $alias;
       
   515 		}
       
   516 
       
   517 		$compatible_operators = array( 'IN' );
       
   518 
       
   519 		foreach ( $parent_query as $sibling ) {
       
   520 			if ( ! is_array( $sibling ) || ! $this->is_first_order_clause( $sibling ) ) {
       
   521 				continue;
       
   522 			}
       
   523 
       
   524 			if ( empty( $sibling['alias'] ) || empty( $sibling['operator'] ) ) {
       
   525 				continue;
       
   526 			}
       
   527 
       
   528 			// The sibling must both have compatible operator to share its alias.
       
   529 			if ( in_array( strtoupper( $sibling['operator'] ), $compatible_operators ) ) {
       
   530 				$alias = $sibling['alias'];
       
   531 				break;
       
   532 			}
       
   533 		}
       
   534 
       
   535 		return $alias;
       
   536 	}
       
   537 
       
   538 	/**
       
   539 	 * Validates a single query.
       
   540 	 *
       
   541 	 * @since 3.2.0
       
   542 	 *
       
   543 	 * @param array $query The single query. Passed by reference.
       
   544 	 */
       
   545 	private function clean_query( &$query ) {
       
   546 		if ( empty( $query['taxonomy'] ) ) {
       
   547 			if ( 'term_taxonomy_id' !== $query['field'] ) {
       
   548 				$query = new WP_Error( 'invalid_taxonomy', __( 'Invalid taxonomy.' ) );
       
   549 				return;
       
   550 			}
       
   551 
       
   552 			// so long as there are shared terms, include_children requires that a taxonomy is set
       
   553 			$query['include_children'] = false;
       
   554 		} elseif ( ! taxonomy_exists( $query['taxonomy'] ) ) {
       
   555 			$query = new WP_Error( 'invalid_taxonomy', __( 'Invalid taxonomy.' ) );
       
   556 			return;
       
   557 		}
       
   558 
       
   559 		$query['terms'] = array_unique( (array) $query['terms'] );
       
   560 
       
   561 		if ( is_taxonomy_hierarchical( $query['taxonomy'] ) && $query['include_children'] ) {
       
   562 			$this->transform_query( $query, 'term_id' );
       
   563 
       
   564 			if ( is_wp_error( $query ) )
       
   565 				return;
       
   566 
       
   567 			$children = array();
       
   568 			foreach ( $query['terms'] as $term ) {
       
   569 				$children = array_merge( $children, get_term_children( $term, $query['taxonomy'] ) );
       
   570 				$children[] = $term;
       
   571 			}
       
   572 			$query['terms'] = $children;
       
   573 		}
       
   574 
       
   575 		$this->transform_query( $query, 'term_taxonomy_id' );
       
   576 	}
       
   577 
       
   578 	/**
       
   579 	 * Transforms a single query, from one field to another.
       
   580 	 *
       
   581 	 * Operates on the `$query` object by reference. In the case of error,
       
   582 	 * `$query` is converted to a WP_Error object.
       
   583 	 *
       
   584 	 * @since 3.2.0
       
   585 	 *
       
   586 	 * @global wpdb $wpdb The WordPress database abstraction object.
       
   587 	 *
       
   588 	 * @param array  $query           The single query. Passed by reference.
       
   589 	 * @param string $resulting_field The resulting field. Accepts 'slug', 'name', 'term_taxonomy_id',
       
   590 	 *                                or 'term_id'. Default 'term_id'.
       
   591 	 */
       
   592 	public function transform_query( &$query, $resulting_field ) {
       
   593 		if ( empty( $query['terms'] ) )
       
   594 			return;
       
   595 
       
   596 		if ( $query['field'] == $resulting_field )
       
   597 			return;
       
   598 
       
   599 		$resulting_field = sanitize_key( $resulting_field );
       
   600 
       
   601 		// Empty 'terms' always results in a null transformation.
       
   602 		$terms = array_filter( $query['terms'] );
       
   603 		if ( empty( $terms ) ) {
       
   604 			$query['terms'] = array();
       
   605 			$query['field'] = $resulting_field;
       
   606 			return;
       
   607 		}
       
   608 
       
   609 		$args = array(
       
   610 			'get'                    => 'all',
       
   611 			'number'                 => 0,
       
   612 			'taxonomy'               => $query['taxonomy'],
       
   613 			'update_term_meta_cache' => false,
       
   614 			'orderby'                => 'none',
       
   615 		);
       
   616 
       
   617 		// Term query parameter name depends on the 'field' being searched on.
       
   618 		switch ( $query['field'] ) {
       
   619 			case 'slug':
       
   620 				$args['slug'] = $terms;
       
   621 				break;
       
   622 			case 'name':
       
   623 				$args['name'] = $terms;
       
   624 				break;
       
   625 			case 'term_taxonomy_id':
       
   626 				$args['term_taxonomy_id'] = $terms;
       
   627 				break;
       
   628 			default:
       
   629 				$args['include'] = wp_parse_id_list( $terms );
       
   630 				break;
       
   631 		}
       
   632 
       
   633 		$term_query = new WP_Term_Query();
       
   634 		$term_list  = $term_query->query( $args );
       
   635 
       
   636 		if ( is_wp_error( $term_list ) ) {
       
   637 			$query = $term_list;
       
   638 			return;
       
   639 		}
       
   640 
       
   641 		if ( 'AND' == $query['operator'] && count( $term_list ) < count( $query['terms'] ) ) {
       
   642 			$query = new WP_Error( 'inexistent_terms', __( 'Inexistent terms.' ) );
       
   643 			return;
       
   644 		}
       
   645 
       
   646 		$query['terms'] = wp_list_pluck( $term_list, $resulting_field );
       
   647 		$query['field'] = $resulting_field;
       
   648 	}
       
   649 }