+ /**
+ * Sanitize a 'relation' operator.
+ *
+ * @since 4.1.0
+ * @access public
+ *
+ * @param string $relation Raw relation key from the query argument.
+ * @return string Sanitized relation ('AND' or 'OR').
+ */
+ public function sanitize_relation( $relation ) {
+ if ( 'OR' === strtoupper( $relation ) ) {
+ return 'OR';
+ } else {
+ return 'AND';
+ }
+ }
+
+ /**
+ * Determine whether a clause is first-order.
+ *
+ * A "first-order" clause is one that contains any of the first-order
+ * clause keys ('terms', 'taxonomy', 'include_children', 'field',
+ * 'operator'). An empty clause also counts as a first-order clause,
+ * for backward compatibility. Any clause that doesn't meet this is
+ * determined, by process of elimination, to be a higher-order query.
+ *
+ * @since 4.1.0
+ * @access protected
+ *
+ * @param array $query Tax query arguments.
+ * @return bool Whether the query clause is a first-order clause.
+ */
+ protected static function is_first_order_clause( $query ) {
+ 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 ) );
+ }
+
+ /**
+ * Generates SQL clauses to be appended to a main query.
+ *
+ * @since 3.1.0
+ * @access public
+ *
+ * @param string $primary_table Database table where the object being filtered is stored (eg wp_users).
+ * @param string $primary_id_column ID column for the filtered object in $primary_table.
+ * @return array {
+ * Array containing JOIN and WHERE SQL clauses to append to the main query.
+ *
+ * @type string $join SQL fragment to append to the main JOIN clause.
+ * @type string $where SQL fragment to append to the main WHERE clause.
+ * }
+ */
+ public function get_sql( $primary_table, $primary_id_column ) {
+ $this->primary_table = $primary_table;
+ $this->primary_id_column = $primary_id_column;
+
+ return $this->get_sql_clauses();
+ }
+
+ /**
+ * Generate SQL clauses to be appended to a main query.
+ *
+ * Called by the public {@see WP_Tax_Query::get_sql()}, this method
+ * is abstracted out to maintain parity with the other Query classes.
+ *
+ * @since 4.1.0
+ * @access protected
+ *
+ * @return array {
+ * Array containing JOIN and WHERE SQL clauses to append to the main query.
+ *
+ * @type string $join SQL fragment to append to the main JOIN clause.
+ * @type string $where SQL fragment to append to the main WHERE clause.
+ * }
+ */
+ protected function get_sql_clauses() {
+ /*
+ * $queries are passed by reference to get_sql_for_query() for recursion.
+ * To keep $this->queries unaltered, pass a copy.
+ */
+ $queries = $this->queries;
+ $sql = $this->get_sql_for_query( $queries );
+
+ if ( ! empty( $sql['where'] ) ) {
+ $sql['where'] = ' AND ' . $sql['where'];
+ }
+
+ return $sql;
+ }
+
+ /**
+ * Generate SQL clauses for a single query array.
+ *
+ * If nested subqueries are found, this method recurses the tree to
+ * produce the properly nested SQL.
+ *
+ * @since 4.1.0
+ * @access protected
+ *
+ * @param array $query Query to parse, passed by reference.
+ * @param int $depth Optional. Number of tree levels deep we currently are.
+ * Used to calculate indentation. Default 0.
+ * @return array {
+ * Array containing JOIN and WHERE SQL clauses to append to a single query array.
+ *
+ * @type string $join SQL fragment to append to the main JOIN clause.
+ * @type string $where SQL fragment to append to the main WHERE clause.
+ * }
+ */
+ protected function get_sql_for_query( &$query, $depth = 0 ) {
+ $sql_chunks = array(
+ 'join' => array(),
+ 'where' => array(),
+ );
+
+ $sql = array(
+ 'join' => '',
+ 'where' => '',
+ );
+
+ $indent = '';
+ for ( $i = 0; $i < $depth; $i++ ) {
+ $indent .= " ";
+ }
+
+ foreach ( $query as $key => &$clause ) {
+ if ( 'relation' === $key ) {
+ $relation = $query['relation'];
+ } elseif ( is_array( $clause ) ) {
+
+ // This is a first-order clause.
+ if ( $this->is_first_order_clause( $clause ) ) {
+ $clause_sql = $this->get_sql_for_clause( $clause, $query );
+
+ $where_count = count( $clause_sql['where'] );
+ if ( ! $where_count ) {
+ $sql_chunks['where'][] = '';
+ } elseif ( 1 === $where_count ) {
+ $sql_chunks['where'][] = $clause_sql['where'][0];
+ } else {
+ $sql_chunks['where'][] = '( ' . implode( ' AND ', $clause_sql['where'] ) . ' )';
+ }
+
+ $sql_chunks['join'] = array_merge( $sql_chunks['join'], $clause_sql['join'] );
+ // This is a subquery, so we recurse.
+ } else {
+ $clause_sql = $this->get_sql_for_query( $clause, $depth + 1 );
+
+ $sql_chunks['where'][] = $clause_sql['where'];
+ $sql_chunks['join'][] = $clause_sql['join'];
+ }
+ }
+ }
+
+ // Filter to remove empties.
+ $sql_chunks['join'] = array_filter( $sql_chunks['join'] );
+ $sql_chunks['where'] = array_filter( $sql_chunks['where'] );
+
+ if ( empty( $relation ) ) {
+ $relation = 'AND';
+ }
+
+ // Filter duplicate JOIN clauses and combine into a single string.
+ if ( ! empty( $sql_chunks['join'] ) ) {
+ $sql['join'] = implode( ' ', array_unique( $sql_chunks['join'] ) );
+ }
+
+ // Generate a single WHERE clause with proper brackets and indentation.
+ if ( ! empty( $sql_chunks['where'] ) ) {
+ $sql['where'] = '( ' . "\n " . $indent . implode( ' ' . "\n " . $indent . $relation . ' ' . "\n " . $indent, $sql_chunks['where'] ) . "\n" . $indent . ')';
+ }
+
+ return $sql;
+ }
+
+ /**
+ * Generate SQL JOIN and WHERE clauses for a "first-order" query clause.
+ *
+ * @since 4.1.0
+ * @access public
+ *
+ * @param array $clause Query clause, passed by reference
+ * @param array $parent_query Parent query array.
+ * @return array {
+ * Array containing JOIN and WHERE SQL clauses to append to a first-order query.
+ *
+ * @type string $join SQL fragment to append to the main JOIN clause.
+ * @type string $where SQL fragment to append to the main WHERE clause.
+ * }
+ */
+ public function get_sql_for_clause( &$clause, $parent_query ) {
+ global $wpdb;
+
+ $sql = array(
+ 'where' => array(),
+ 'join' => array(),
+ );
+
+ $join = '';
+
+ $this->clean_query( $clause );
+
+ if ( is_wp_error( $clause ) ) {
+ return self::$no_results;
+ }
+
+ $terms = $clause['terms'];
+ $operator = strtoupper( $clause['operator'] );
+
+ if ( 'IN' == $operator ) {
+
+ if ( empty( $terms ) ) {
+ return self::$no_results;
+ }
+
+ $terms = implode( ',', $terms );
+
+ /*
+ * Before creating another table join, see if this clause has a
+ * sibling with an existing join that can be shared.
+ */
+ $alias = $this->find_compatible_table_alias( $clause, $parent_query );
+ if ( false === $alias ) {
+ $i = count( $this->table_aliases );
+ $alias = $i ? 'tt' . $i : $wpdb->term_relationships;
+
+ // Store the alias as part of a flat array to build future iterators.
+ $this->table_aliases[] = $alias;
+
+ // Store the alias with this clause, so later siblings can use it.
+ $clause['alias'] = $alias;
+
+ $join .= " INNER JOIN $wpdb->term_relationships";
+ $join .= $i ? " AS $alias" : '';
+ $join .= " ON ($this->primary_table.$this->primary_id_column = $alias.object_id)";
+ }
+
+
+ $where = "$alias.term_taxonomy_id $operator ($terms)";
+
+ } elseif ( 'NOT IN' == $operator ) {
+
+ if ( empty( $terms ) ) {
+ return $sql;
+ }
+
+ $terms = implode( ',', $terms );
+
+ $where = "$this->primary_table.$this->primary_id_column NOT IN (
+ SELECT object_id
+ FROM $wpdb->term_relationships
+ WHERE term_taxonomy_id IN ($terms)
+ )";
+
+ } elseif ( 'AND' == $operator ) {
+
+ if ( empty( $terms ) ) {
+ return $sql;
+ }
+
+ $num_terms = count( $terms );
+
+ $terms = implode( ',', $terms );
+
+ $where = "(
+ SELECT COUNT(1)
+ FROM $wpdb->term_relationships
+ WHERE term_taxonomy_id IN ($terms)
+ AND object_id = $this->primary_table.$this->primary_id_column
+ ) = $num_terms";
+
+ } elseif ( 'NOT EXISTS' === $operator || 'EXISTS' === $operator ) {
+
+ $where = $wpdb->prepare( "$operator (
+ SELECT 1
+ FROM $wpdb->term_relationships
+ INNER JOIN $wpdb->term_taxonomy
+ ON $wpdb->term_taxonomy.term_taxonomy_id = $wpdb->term_relationships.term_taxonomy_id
+ WHERE $wpdb->term_taxonomy.taxonomy = %s
+ AND $wpdb->term_relationships.object_id = $this->primary_table.$this->primary_id_column
+ )", $clause['taxonomy'] );
+
+ }
+
+ $sql['join'][] = $join;
+ $sql['where'][] = $where;
+ return $sql;
+ }
+
+ /**
+ * Identify an existing table alias that is compatible with the current query clause.
+ *
+ * We avoid unnecessary table joins by allowing each clause to look for
+ * an existing table alias that is compatible with the query that it
+ * needs to perform.
+ *
+ * An existing alias is compatible if (a) it is a sibling of `$clause`
+ * (ie, it's under the scope of the same relation), and (b) the combination
+ * of operator and relation between the clauses allows for a shared table
+ * join. In the case of {@see WP_Tax_Query}, this only applies to 'IN'
+ * clauses that are connected by the relation 'OR'.
+ *
+ * @since 4.1.0
+ * @access protected
+ *
+ * @param array $clause Query clause.
+ * @param array $parent_query Parent query of $clause.
+ * @return string|bool Table alias if found, otherwise false.
+ */
+ protected function find_compatible_table_alias( $clause, $parent_query ) {
+ $alias = false;
+
+ // Sanity check. Only IN queries use the JOIN syntax .
+ if ( ! isset( $clause['operator'] ) || 'IN' !== $clause['operator'] ) {
+ return $alias;
+ }
+
+ // Since we're only checking IN queries, we're only concerned with OR relations.
+ if ( ! isset( $parent_query['relation'] ) || 'OR' !== $parent_query['relation'] ) {
+ return $alias;
+ }
+
+ $compatible_operators = array( 'IN' );
+
+ foreach ( $parent_query as $sibling ) {
+ if ( ! is_array( $sibling ) || ! $this->is_first_order_clause( $sibling ) ) {
+ continue;
+ }
+
+ if ( empty( $sibling['alias'] ) || empty( $sibling['operator'] ) ) {
+ continue;
+ }
+
+ // The sibling must both have compatible operator to share its alias.
+ if ( in_array( strtoupper( $sibling['operator'] ), $compatible_operators ) ) {
+ $alias = $sibling['alias'];
+ break;
+ }
+ }
+
+ return $alias;
+ }
+
+ /**
+ * Validates a single query.
+ *
+ * @since 3.2.0
+ * @access private
+ *
+ * @param array &$query The single query.
+ */
+ private function clean_query( &$query ) {
+ if ( empty( $query['taxonomy'] ) ) {
+ if ( 'term_taxonomy_id' !== $query['field'] ) {
+ $query = new WP_Error( 'Invalid taxonomy' );
+ return;
+ }
+
+ // so long as there are shared terms, include_children requires that a taxonomy is set
+ $query['include_children'] = false;
+ } elseif ( ! taxonomy_exists( $query['taxonomy'] ) ) {
+ $query = new WP_Error( 'Invalid taxonomy' );
+ return;
+ }
+
+ $query['terms'] = array_unique( (array) $query['terms'] );
+
+ if ( is_taxonomy_hierarchical( $query['taxonomy'] ) && $query['include_children'] ) {
+ $this->transform_query( $query, 'term_id' );
+
+ if ( is_wp_error( $query ) )
+ return;
+
+ $children = array();
+ foreach ( $query['terms'] as $term ) {
+ $children = array_merge( $children, get_term_children( $term, $query['taxonomy'] ) );
+ $children[] = $term;
+ }
+ $query['terms'] = $children;
+ }
+
+ $this->transform_query( $query, 'term_taxonomy_id' );
+ }
+
+ /**
+ * Transforms a single query, from one field to another.
+ *
+ * @since 3.2.0
+ *
+ * @param array &$query The single query.
+ * @param string $resulting_field The resulting field. Accepts 'slug', 'name', 'term_taxonomy_id',
+ * or 'term_id'. Default: 'term_id'.
+ */
+ public function transform_query( &$query, $resulting_field ) {
+ global $wpdb;
+
+ if ( empty( $query['terms'] ) )
+ return;
+
+ if ( $query['field'] == $resulting_field )
+ return;
+
+ $resulting_field = sanitize_key( $resulting_field );
+
+ switch ( $query['field'] ) {
+ case 'slug':
+ case 'name':
+ foreach ( $query['terms'] as &$term ) {
+ /*
+ * 0 is the $term_id parameter. We don't have a term ID yet, but it doesn't
+ * matter because `sanitize_term_field()` ignores the $term_id param when the
+ * context is 'db'.
+ */
+ $term = "'" . esc_sql( sanitize_term_field( $query['field'], $term, 0, $query['taxonomy'], 'db' ) ) . "'";
+ }
+
+ $terms = implode( ",", $query['terms'] );
+
+ $terms = $wpdb->get_col( "
+ SELECT $wpdb->term_taxonomy.$resulting_field
+ FROM $wpdb->term_taxonomy
+ INNER JOIN $wpdb->terms USING (term_id)
+ WHERE taxonomy = '{$query['taxonomy']}'
+ AND $wpdb->terms.{$query['field']} IN ($terms)
+ " );
+ break;
+ case 'term_taxonomy_id':
+ $terms = implode( ',', array_map( 'intval', $query['terms'] ) );
+ $terms = $wpdb->get_col( "
+ SELECT $resulting_field
+ FROM $wpdb->term_taxonomy
+ WHERE term_taxonomy_id IN ($terms)
+ " );
+ break;
+ default:
+ $terms = implode( ',', array_map( 'intval', $query['terms'] ) );
+ $terms = $wpdb->get_col( "
+ SELECT $resulting_field
+ FROM $wpdb->term_taxonomy
+ WHERE taxonomy = '{$query['taxonomy']}'
+ AND term_id IN ($terms)
+ " );
+ }
+
+ if ( 'AND' == $query['operator'] && count( $terms ) < count( $query['terms'] ) ) {
+ $query = new WP_Error( 'Inexistent terms' );
+ return;
+ }
+
+ $query['terms'] = $terms;
+ $query['field'] = $resulting_field;
+ }
+}
+
+/**
+ * Get all Term data from database by Term ID.
+ *
+ * The usage of the get_term function is to apply filters to a term object. It
+ * is possible to get a term object from the database before applying the
+ * filters.
+ *
+ * $term ID must be part of $taxonomy, to get from the database. Failure, might
+ * be able to be captured by the hooks. Failure would be the same value as $wpdb
+ * returns for the get_row method.
+ *
+ * There are two hooks, one is specifically for each term, named 'get_term', and
+ * the second is for the taxonomy name, 'term_$taxonomy'. Both hooks gets the
+ * term object, and the taxonomy name as parameters. Both hooks are expected to
+ * return a Term object.
+ *
+ * 'get_term' hook - Takes two parameters the term Object and the taxonomy name.
+ * Must return term object. Used in get_term() as a catch-all filter for every
+ * $term.
+ *
+ * 'get_$taxonomy' hook - Takes two parameters the term Object and the taxonomy
+ * name. Must return term object. $taxonomy will be the taxonomy name, so for
+ * example, if 'category', it would be 'get_category' as the filter name. Useful
+ * for custom taxonomies or plugging into default taxonomies.
+ *
+ * @since 2.3.0
+ *
+ * @global wpdb $wpdb WordPress database abstraction object.
+ * @see sanitize_term_field() The $context param lists the available values for get_term_by() $filter param.
+ *
+ * @param int|object $term If integer, will get from database. If object will apply filters and return $term.
+ * @param string $taxonomy Taxonomy name that $term is part of.
+ * @param string $output Constant OBJECT, ARRAY_A, or ARRAY_N
+ * @param string $filter Optional, default is raw or no WordPress defined filter will applied.
+ * @return mixed|null|WP_Error Term Row from database. Will return null if $term is empty. If taxonomy does not
+ * exist then WP_Error will be returned.
+ */
+function get_term($term, $taxonomy, $output = OBJECT, $filter = 'raw') {
+ global $wpdb;
+
+ if ( empty($term) ) {
+ $error = new WP_Error('invalid_term', __('Empty Term'));
+ return $error;
+ }
+
+ if ( ! taxonomy_exists($taxonomy) ) {
+ $error = new WP_Error('invalid_taxonomy', __('Invalid taxonomy'));
+ return $error;
+ }
+
+ if ( is_object($term) && empty($term->filter) ) {
+ wp_cache_add( $term->term_id, $term, $taxonomy );
+ $_term = $term;
+ } else {
+ if ( is_object($term) )
+ $term = $term->term_id;
+ if ( !$term = (int) $term )
+ return null;
+ if ( ! $_term = wp_cache_get( $term, $taxonomy ) ) {
+ $_term = $wpdb->get_row( $wpdb->prepare( "SELECT t.*, tt.* FROM $wpdb->terms AS t INNER JOIN $wpdb->term_taxonomy AS tt ON t.term_id = tt.term_id WHERE tt.taxonomy = %s AND t.term_id = %d LIMIT 1", $taxonomy, $term) );
+ if ( ! $_term )
+ return null;
+ wp_cache_add( $term, $_term, $taxonomy );
+ }
+ }
+
+ /**
+ * Filter a term.
+ *
+ * @since 2.3.0
+ *
+ * @param int|object $_term Term object or ID.
+ * @param string $taxonomy The taxonomy slug.
+ */
+ $_term = apply_filters( 'get_term', $_term, $taxonomy );
+
+ /**
+ * Filter a taxonomy.
+ *
+ * The dynamic portion of the filter name, `$taxonomy`, refers
+ * to the taxonomy slug.
+ *
+ * @since 2.3.0
+ *
+ * @param int|object $_term Term object or ID.
+ * @param string $taxonomy The taxonomy slug.
+ */
+ $_term = apply_filters( "get_$taxonomy", $_term, $taxonomy );
+ $_term = sanitize_term($_term, $taxonomy, $filter);
+
+ if ( $output == OBJECT ) {
+ return $_term;
+ } elseif ( $output == ARRAY_A ) {
+ $__term = get_object_vars($_term);
+ return $__term;
+ } elseif ( $output == ARRAY_N ) {
+ $__term = array_values(get_object_vars($_term));
+ return $__term;
+ } else {
+ return $_term;
+ }
+}
+
+/**
+ * Get all Term data from database by Term field and data.
+ *
+ * Warning: $value is not escaped for 'name' $field. You must do it yourself, if
+ * required.
+ *
+ * The default $field is 'id', therefore it is possible to also use null for
+ * field, but not recommended that you do so.
+ *
+ * If $value does not exist, the return value will be false. If $taxonomy exists
+ * and $field and $value combinations exist, the Term will be returned.
+ *
+ * @since 2.3.0
+ *
+ * @global wpdb $wpdb WordPress database abstraction object.
+ * @see sanitize_term_field() The $context param lists the available values for get_term_by() $filter param.
+ *
+ * @param string $field Either 'slug', 'name', 'id' (term_id), or 'term_taxonomy_id'
+ * @param string|int $value Search for this term value
+ * @param string $taxonomy Taxonomy Name
+ * @param string $output Constant OBJECT, ARRAY_A, or ARRAY_N
+ * @param string $filter Optional, default is raw or no WordPress defined filter will applied.
+ * @return mixed Term Row from database. Will return false if $taxonomy does not exist or $term was not found.
+ */
+function get_term_by($field, $value, $taxonomy, $output = OBJECT, $filter = 'raw') {
+ global $wpdb;
+
+ if ( ! taxonomy_exists($taxonomy) )
+ return false;
+
+ if ( 'slug' == $field ) {
+ $field = 't.slug';
+ $value = sanitize_title($value);
+ if ( empty($value) )
+ return false;
+ } elseif ( 'name' == $field ) {
+ // Assume already escaped
+ $value = wp_unslash($value);
+ $field = 't.name';
+ } elseif ( 'term_taxonomy_id' == $field ) {
+ $value = (int) $value;
+ $field = 'tt.term_taxonomy_id';
+ } else {
+ $term = get_term( (int) $value, $taxonomy, $output, $filter );
+ if ( is_wp_error( $term ) )
+ $term = false;
+ return $term;
+ }
+
+ $term = $wpdb->get_row( $wpdb->prepare( "SELECT t.*, tt.* FROM $wpdb->terms AS t INNER JOIN $wpdb->term_taxonomy AS tt ON t.term_id = tt.term_id WHERE tt.taxonomy = %s AND $field = %s LIMIT 1", $taxonomy, $value ) );
+ if ( ! $term )
+ return false;
+
+ wp_cache_add( $term->term_id, $term, $taxonomy );
+
+ /** This filter is documented in wp-includes/taxonomy.php */
+ $term = apply_filters( 'get_term', $term, $taxonomy );
+
+ /** This filter is documented in wp-includes/taxonomy.php */
+ $term = apply_filters( "get_$taxonomy", $term, $taxonomy );
+
+ $term = sanitize_term($term, $taxonomy, $filter);
+
+ if ( $output == OBJECT ) {
+ return $term;
+ } elseif ( $output == ARRAY_A ) {
+ return get_object_vars($term);
+ } elseif ( $output == ARRAY_N ) {
+ return array_values(get_object_vars($term));
+ } else {
+ return $term;
+ }
+}
+
+/**
+ * Merge all term children into a single array of their IDs.
+ *
+ * This recursive function will merge all of the children of $term into the same
+ * array of term IDs. Only useful for taxonomies which are hierarchical.
+ *
+ * Will return an empty array if $term does not exist in $taxonomy.
+ *
+ * @since 2.3.0
+ *
+ * @global wpdb $wpdb WordPress database abstraction object.
+ *
+ * @param string $term_id ID of Term to get children
+ * @param string $taxonomy Taxonomy Name
+ * @return array|WP_Error List of Term IDs. WP_Error returned if $taxonomy does not exist
+ */
+function get_term_children( $term_id, $taxonomy ) {
+ if ( ! taxonomy_exists($taxonomy) )
+ return new WP_Error('invalid_taxonomy', __('Invalid taxonomy'));
+
+ $term_id = intval( $term_id );
+
+ $terms = _get_term_hierarchy($taxonomy);
+
+ if ( ! isset($terms[$term_id]) )
+ return array();
+
+ $children = $terms[$term_id];
+
+ foreach ( (array) $terms[$term_id] as $child ) {
+ if ( $term_id == $child ) {
+ continue;
+ }
+
+ if ( isset($terms[$child]) )
+ $children = array_merge($children, get_term_children($child, $taxonomy));
+ }
+
+ return $children;
+}
+
+/**
+ * Get sanitized Term field.
+ *
+ * Does checks for $term, based on the $taxonomy. The function is for contextual
+ * reasons and for simplicity of usage. See sanitize_term_field() for more
+ * information.
+ *
+ * @since 2.3.0
+ *
+ * @param string $field Term field to fetch
+ * @param int $term Term ID
+ * @param string $taxonomy Taxonomy Name
+ * @param string $context Optional, default is display. Look at sanitize_term_field() for available options.
+ * @return mixed Will return an empty string if $term is not an object or if $field is not set in $term.
+ */
+function get_term_field( $field, $term, $taxonomy, $context = 'display' ) {
+ $term = (int) $term;
+ $term = get_term( $term, $taxonomy );
+ if ( is_wp_error($term) )
+ return $term;
+
+ if ( !is_object($term) )
+ return '';
+
+ if ( !isset($term->$field) )
+ return '';
+
+ return sanitize_term_field($field, $term->$field, $term->term_id, $taxonomy, $context);
+}
+
+/**
+ * Sanitizes Term for editing.
+ *
+ * Return value is sanitize_term() and usage is for sanitizing the term for
+ * editing. Function is for contextual and simplicity.
+ *
+ * @since 2.3.0
+ *
+ * @param int|object $id Term ID or Object
+ * @param string $taxonomy Taxonomy Name
+ * @return mixed|null|WP_Error Will return empty string if $term is not an object.
+ */
+function get_term_to_edit( $id, $taxonomy ) {
+ $term = get_term( $id, $taxonomy );
+
+ if ( is_wp_error($term) )
+ return $term;
+
+ if ( !is_object($term) )
+ return '';
+
+ return sanitize_term($term, $taxonomy, 'edit');
+}
+
+/**
+ * Retrieve the terms in a given taxonomy or list of taxonomies.
+ *
+ * You can fully inject any customizations to the query before it is sent, as
+ * well as control the output with a filter.
+ *
+ * The 'get_terms' filter will be called when the cache has the term and will
+ * pass the found term along with the array of $taxonomies and array of $args.
+ * This filter is also called before the array of terms is passed and will pass
+ * the array of terms, along with the $taxonomies and $args.
+ *
+ * The 'list_terms_exclusions' filter passes the compiled exclusions along with
+ * the $args.
+ *
+ * The 'get_terms_orderby' filter passes the ORDER BY clause for the query
+ * along with the $args array.
+ *
+ * @since 2.3.0
+ * @since 4.2.0 Introduced 'name' and 'childless' parameters.
+ *
+ * @global wpdb $wpdb WordPress database abstraction object.
+ *
+ * @param string|array $taxonomies Taxonomy name or list of Taxonomy names.
+ * @param array|string $args {
+ * Optional. Array or string of arguments to get terms.
+ *
+ * @type string $orderby Field(s) to order terms by. Accepts term fields ('name', 'slug',
+ * 'term_group', 'term_id', 'id', 'description'), 'count' for term
+ * taxonomy count, 'include' to match the 'order' of the $include param,
+ * or 'none' to skip ORDER BY. Defaults to 'name'.
+ * @type string $order Whether to order terms in ascending or descending order.
+ * Accepts 'ASC' (ascending) or 'DESC' (descending).
+ * Default 'ASC'.
+ * @type bool|int $hide_empty Whether to hide terms not assigned to any posts. Accepts
+ * 1|true or 0|false. Default 1|true.
+ * @type array|string $include Array or comma/space-separated string of term ids to include.
+ * Default empty array.
+ * @type array|string $exclude Array or comma/space-separated string of term ids to exclude.
+ * If $include is non-empty, $exclude is ignored.
+ * Default empty array.
+ * @type array|string $exclude_tree Array or comma/space-separated string of term ids to exclude
+ * along with all of their descendant terms. If $include is
+ * non-empty, $exclude_tree is ignored. Default empty array.
+ * @type int|string $number Maximum number of terms to return. Accepts ''|0 (all) or any
+ * positive number. Default ''|0 (all).
+ * @type int $offset The number by which to offset the terms query. Default empty.
+ * @type string $fields Term fields to query for. Accepts 'all' (returns an array of
+ * term objects), 'ids' or 'names' (returns an array of integers
+ * or strings, respectively. Default 'all'.
+ * @type string|array $name Optional. Name or array of names to return term(s) for. Default empty.
+ * @type string|array $slug Optional. Slug or array of slugs to return term(s) for. Default empty.
+ * @type bool $hierarchical Whether to include terms that have non-empty descendants (even
+ * if $hide_empty is set to true). Default true.
+ * @type string $search Search criteria to match terms. Will be SQL-formatted with
+ * wildcards before and after. Default empty.
+ * @type string $name__like Retrieve terms with criteria by which a term is LIKE $name__like.
+ * Default empty.
+ * @type string $description__like Retrieve terms where the description is LIKE $description__like.
+ * Default empty.
+ * @type bool $pad_counts Whether to pad the quantity of a term's children in the quantity
+ * of each term's "count" object variable. Default false.
+ * @type string $get Whether to return terms regardless of ancestry or whether the terms
+ * are empty. Accepts 'all' or empty (disabled). Default empty.
+ * @type int $child_of Term ID to retrieve child terms of. If multiple taxonomies
+ * are passed, $child_of is ignored. Default 0.
+ * @type int|string $parent Parent term ID to retrieve direct-child terms of. Default empty.
+ * @type bool $childless True to limit results to terms that have no children. This parameter has
+ * no effect on non-hierarchical taxonomies. Default false.
+ * @type string $cache_domain Unique cache key to be produced when this query is stored in an
+ * object cache. Default is 'core'.
+ * }
+ * @return array|WP_Error List of Term Objects and their children. Will return WP_Error, if any of $taxonomies
+ * do not exist.
+ */
+function get_terms( $taxonomies, $args = '' ) {
+ global $wpdb;
+ $empty_array = array();
+
+ $single_taxonomy = ! is_array( $taxonomies ) || 1 === count( $taxonomies );
+ if ( ! is_array( $taxonomies ) ) {
+ $taxonomies = array( $taxonomies );
+ }
+
+ foreach ( $taxonomies as $taxonomy ) {
+ if ( ! taxonomy_exists($taxonomy) ) {
+ $error = new WP_Error('invalid_taxonomy', __('Invalid taxonomy'));
+ return $error;
+ }
+ }
+
+ $defaults = array('orderby' => 'name', 'order' => 'ASC',
+ 'hide_empty' => true, 'exclude' => array(), 'exclude_tree' => array(), 'include' => array(),
+ 'number' => '', 'fields' => 'all', 'name' => '', 'slug' => '', 'parent' => '', 'childless' => false,
+ 'hierarchical' => true, 'child_of' => 0, 'get' => '', 'name__like' => '', 'description__like' => '',
+ 'pad_counts' => false, 'offset' => '', 'search' => '', 'cache_domain' => 'core' );
+ $args = wp_parse_args( $args, $defaults );
+ $args['number'] = absint( $args['number'] );
+ $args['offset'] = absint( $args['offset'] );
+
+ // Save queries by not crawling the tree in the case of multiple taxes or a flat tax.
+ $has_hierarchical_tax = false;
+ foreach ( $taxonomies as $_tax ) {
+ if ( is_taxonomy_hierarchical( $_tax ) ) {
+ $has_hierarchical_tax = true;
+ }
+ }
+
+ if ( ! $has_hierarchical_tax ) {
+ $args['hierarchical'] = false;
+ $args['pad_counts'] = false;
+ }
+
+ // 'parent' overrides 'child_of'.
+ if ( 0 < intval( $args['parent'] ) ) {
+ $args['child_of'] = false;
+ }
+
+ if ( 'all' == $args['get'] ) {
+ $args['childless'] = false;
+ $args['child_of'] = 0;
+ $args['hide_empty'] = 0;
+ $args['hierarchical'] = false;
+ $args['pad_counts'] = false;
+ }
+
+ /**
+ * Filter the terms query arguments.
+ *
+ * @since 3.1.0
+ *
+ * @param array $args An array of arguments.
+ * @param array $taxonomies An array of taxonomies.
+ */
+ $args = apply_filters( 'get_terms_args', $args, $taxonomies );
+
+ // Avoid the query if the queried parent/child_of term has no descendants.
+ $child_of = $args['child_of'];
+ $parent = $args['parent'];
+
+ if ( $child_of ) {
+ $_parent = $child_of;
+ } elseif ( $parent ) {
+ $_parent = $parent;
+ } else {
+ $_parent = false;
+ }
+
+ if ( $_parent ) {
+ $in_hierarchy = false;
+ foreach ( $taxonomies as $_tax ) {
+ $hierarchy = _get_term_hierarchy( $_tax );
+
+ if ( isset( $hierarchy[ $_parent ] ) ) {
+ $in_hierarchy = true;
+ }
+ }
+
+ if ( ! $in_hierarchy ) {
+ return $empty_array;
+ }
+ }
+
+ // $args can be whatever, only use the args defined in defaults to compute the key
+ $filter_key = ( has_filter('list_terms_exclusions') ) ? serialize($GLOBALS['wp_filter']['list_terms_exclusions']) : '';
+ $key = md5( serialize( wp_array_slice_assoc( $args, array_keys( $defaults ) ) ) . serialize( $taxonomies ) . $filter_key );
+ $last_changed = wp_cache_get( 'last_changed', 'terms' );
+ if ( ! $last_changed ) {
+ $last_changed = microtime();
+ wp_cache_set( 'last_changed', $last_changed, 'terms' );
+ }
+ $cache_key = "get_terms:$key:$last_changed";
+ $cache = wp_cache_get( $cache_key, 'terms' );
+ if ( false !== $cache ) {
+
+ /**
+ * Filter the given taxonomy's terms cache.
+ *
+ * @since 2.3.0
+ *
+ * @param array $cache Cached array of terms for the given taxonomy.
+ * @param array $taxonomies An array of taxonomies.
+ * @param array $args An array of arguments to get terms.
+ */
+ $cache = apply_filters( 'get_terms', $cache, $taxonomies, $args );
+ return $cache;
+ }
+
+ $_orderby = strtolower( $args['orderby'] );
+ if ( 'count' == $_orderby ) {