Taxonomy: Use `WP_Term_Query` when querying for object terms.

The new 'object_ids' parameter for `WP_Term_Query` allows queries for
terms that "belong to" a given object. This change makes it possible
to use `WP_Term_Query` inside of `wp_get_object_terms()`, rather than
assembling a SQL query.

The refactor has a couple of benefits:
* Less redundancy.
* Better consistency in accepted arguments between the term query functions. See #31105.
* Less redundancy.
* Object term queries are now cached. The `get_object_term_cache()` cache remains, and will be a somewhat less fragile secondary cache in front of the query cache (which is subject to frequent invalidation).
* Less redundancy.

A small breaking change: Previously, if a non-hierarchical taxonomy had
terms that had a non-zero 'parent' (perhaps because of a direct SQL
query), `wp_get_object_terms()` would respect the 'parent' argument.
This is in contrast to `WP_Term_Query` and `get_terms()`, which have
always rejected 'parent' queries for non-hierarchical taxonomies. For
consistency, the behavior of `get_terms()` is being applied across the
board: passing 'parent' for a non-hierarchical taxonomy will result in
an empty result set (since the cached taxonomy hierarchy will be empty).

Props flixos90, boonebgorges.
See #37198.
Built from https://develop.svn.wordpress.org/trunk@38667


git-svn-id: http://core.svn.wordpress.org/trunk@38610 1a063a9b-81f0-0310-95a4-ce76da25c4cd
This commit is contained in:
Boone Gorges 2016-09-28 03:55:33 +00:00
parent ee109482db
commit 3b6314e032
3 changed files with 103 additions and 209 deletions

View File

@ -100,6 +100,7 @@ class WP_Term_Query {
*
* @since 4.6.0
* @since 4.6.0 Introduced 'term_taxonomy_id' parameter.
* @since 4.7.0 Introduced 'object_ids' parameter.
* @access public
*
* @param string|array $query {
@ -107,6 +108,8 @@ class WP_Term_Query {
*
* @type string|array $taxonomy Taxonomy name, or array of taxonomies, to which results should
* be limited.
* @type int|array $object_ids Optional. Object ID, or array of object IDs. Results will be
* limited to terms associated with these objects.
* @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
@ -130,13 +133,17 @@ class WP_Term_Query {
* 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
* complete term objects), 'ids' (returns an array of ids),
* 'id=>parent' (returns an associative array with ids as keys,
* parent term IDs as values), 'names' (returns an array of term
* names), 'count' (returns the number of matching terms),
* 'id=>name' (returns an associative array with ids as keys,
* term names as values), or 'id=>slug' (returns an associative
* array with ids as keys, term slugs as values). Default 'all'.
* complete term objects), 'all_with_object_id' (returns an
* array of term objects with the 'object_id' param; only works
* when the `$fields` parameter is 'object_ids' ), 'ids'
* (returns an array of ids), 'tt_ids' (returns an array of
* term taxonomy ids), 'id=>parent' (returns an associative
* array with ids as keys, parent term IDs as values), 'names'
* (returns an array of term names), 'count' (returns the number
* of matching terms), 'id=>name' (returns an associative array
* with ids as keys, term names as values), or 'id=>slug'
* (returns an associative array with ids as keys, term slugs
* as values). Default 'all'.
* @type bool $count Whether to return a term count (true) or array of term objects
* (false). Will take precedence over `$fields` if true.
* Default false.
@ -183,6 +190,7 @@ class WP_Term_Query {
$this->query_var_defaults = array(
'taxonomy' => null,
'object_ids' => null,
'orderby' => 'name',
'order' => 'ASC',
'hide_empty' => true,
@ -392,7 +400,13 @@ class WP_Term_Query {
}
}
$orderby = $this->parse_orderby( $this->query_vars['orderby'] );
// 'term_order' is a legal sort order only when joining the relationship table.
$_orderby = $this->query_vars['orderby'];
if ( 'term_order' === $_orderby && empty( $this->query_vars['object_ids'] ) ) {
$_orderby = 'term_id';
}
$orderby = $this->parse_orderby( $_orderby );
if ( $orderby ) {
$orderby = "ORDER BY $orderby";
}
@ -507,6 +521,24 @@ class WP_Term_Query {
$this->sql_clauses['where']['description__like'] = $this->db->prepare( "tt.description LIKE %s", '%' . $this->db->esc_like( $args['description__like'] ) . '%' );
}
if ( ! empty( $args['object_ids'] ) ) {
$object_ids = $args['object_ids'];
if ( ! is_array( $object_ids ) ) {
$object_ids = array( $object_ids );
}
$object_ids = implode( ', ', array_map( 'intval', $object_ids ) );
$this->sql_clauses['where']['object_ids'] = "tr.object_id IN ($object_ids)";
}
/*
* When querying for object relationships, the 'count > 0' check
* added by 'hide_empty' is superfluous.
*/
if ( ! empty( $args['object_ids'] ) ) {
$args['hide_empty'] = false;
}
if ( '' !== $parent ) {
$parent = (int) $parent;
$this->sql_clauses['where']['parent'] = "tt.parent = '$parent'";
@ -558,7 +590,13 @@ class WP_Term_Query {
$selects = array();
switch ( $args['fields'] ) {
case 'all':
case 'all_with_object_id' :
case 'tt_ids' :
case 'slugs' :
$selects = array( 't.*', 'tt.*' );
if ( 'all_with_object_id' === $args['fields'] && ! empty( $args['object_ids'] ) ) {
$selects[] = 'tr.object_id';
}
break;
case 'ids':
case 'id=>parent':
@ -602,6 +640,10 @@ class WP_Term_Query {
$join .= " INNER JOIN {$this->db->term_taxonomy} AS tt ON t.term_id = tt.term_id";
if ( ! empty( $this->query_vars['object_ids'] ) ) {
$join .= " INNER JOIN {$this->db->term_relationships} AS tr ON tr.term_taxonomy_id = tt.term_taxonomy_id";
}
$where = implode( ' AND ', $this->sql_clauses['where'] );
/**
@ -657,7 +699,7 @@ class WP_Term_Query {
}
$terms = $this->db->get_results( $this->request );
if ( 'all' == $_fields ) {
if ( 'all' == $_fields || 'all_with_object_id' === $_fields ) {
update_term_cache( $terms );
}
@ -708,6 +750,26 @@ class WP_Term_Query {
}
}
/*
* When querying for terms connected to objects, we may get
* duplicate results. The duplicates should be preserved if
* `$fields` is 'all_with_object_id', but should otherwise be
* removed.
*/
if ( ! empty( $args['object_ids'] ) && 'all_with_object_id' != $_fields ) {
$_tt_ids = $_terms = array();
foreach ( $terms as $term ) {
if ( isset( $_tt_ids[ $term->term_id ] ) ) {
continue;
}
$_tt_ids[ $term->term_id ] = 1;
$_terms[] = $term;
}
$terms = $_terms;
}
$_terms = array();
if ( 'id=>parent' == $_fields ) {
foreach ( $terms as $term ) {
@ -715,12 +777,20 @@ class WP_Term_Query {
}
} elseif ( 'ids' == $_fields ) {
foreach ( $terms as $term ) {
$_terms[] = $term->term_id;
$_terms[] = (int) $term->term_id;
}
} elseif ( 'tt_ids' == $_fields ) {
foreach ( $terms as $term ) {
$_terms[] = (int) $term->term_taxonomy_id;
}
} elseif ( 'names' == $_fields ) {
foreach ( $terms as $term ) {
$_terms[] = $term->name;
}
} elseif ( 'slugs' == $_fields ) {
foreach ( $terms as $term ) {
$_terms[] = $term->slug;
}
} elseif ( 'id=>name' == $_fields ) {
foreach ( $terms as $term ) {
$_terms[ $term->term_id ] = $term->name;
@ -746,7 +816,7 @@ class WP_Term_Query {
wp_cache_add( $cache_key, $terms, 'terms', DAY_IN_SECONDS );
if ( 'all' === $_fields ) {
if ( 'all' === $_fields || 'all_with_object_id' === $_fields ) {
$terms = array_map( 'get_term', $terms );
}
@ -766,19 +836,16 @@ class WP_Term_Query {
protected function parse_orderby( $orderby_raw ) {
$_orderby = strtolower( $orderby_raw );
$maybe_orderby_meta = false;
if ( 'count' == $_orderby ) {
$orderby = 'tt.count';
} elseif ( 'name' == $_orderby ) {
$orderby = 't.name';
} elseif ( 'slug' == $_orderby ) {
$orderby = 't.slug';
if ( in_array( $_orderby, array( 'term_id', 'name', 'slug', 'term_group' ), true ) ) {
$orderby = "t.$_orderby";
} elseif ( in_array( $_orderby, array( 'count', 'parent', 'taxonomy', 'term_taxonomy_id', 'description' ), true ) ) {
$orderby = "tt.$_orderby";
} elseif ( 'term_order' === $_orderby ) {
$orderby = 'tr.term_order';
} elseif ( 'include' == $_orderby && ! empty( $this->query_vars['include'] ) ) {
$include = implode( ',', wp_parse_id_list( $this->query_vars['include'] ) );
$orderby = "FIELD( t.term_id, $include )";
} elseif ( 'term_group' == $_orderby ) {
$orderby = 't.term_group';
} elseif ( 'description' == $_orderby ) {
$orderby = 'tt.description';
} elseif ( 'none' == $_orderby ) {
$orderby = '';
} elseif ( empty( $_orderby ) || 'id' == $_orderby || 'term_id' === $_orderby ) {

View File

@ -1941,27 +1941,13 @@ function wp_delete_category( $cat_ID ) {
* Introduced `$parent` argument.
* @since 4.4.0 Introduced `$meta_query` and `$update_term_meta_cache` arguments. When `$fields` is 'all' or
* 'all_with_object_id', an array of `WP_Term` objects will be returned.
* @since 4.7.0 Refactored to use WP_Term_Query, and to support any WP_Term_Query arguments.
*
* @global wpdb $wpdb WordPress database abstraction object.
*
* @param int|array $object_ids The ID(s) of the object(s) to retrieve.
* @param string|array $taxonomies The taxonomies to retrieve terms from.
* @param array|string $args {
* Array of arguments.
* @type string $orderby Field by which results should be sorted. Accepts 'name', 'count', 'slug',
* 'term_group', 'term_order', 'taxonomy', 'parent', or 'term_taxonomy_id'.
* Default 'name'.
* @type string $order Sort order. Accepts 'ASC' or 'DESC'. Default 'ASC'.
* @type string $fields Fields to return for matched terms. Accepts 'all', 'ids', 'names', and
* 'all_with_object_id'. Note that 'all' or 'all_with_object_id' will result
* in an array of term objects being returned, 'ids' will return an array of
* integers, and 'names' an array of strings.
* @type int $parent Optional. Limit results to the direct children of a given term ID.
* @type bool $update_term_meta_cache Whether to prime termmeta cache for matched terms. Only applies when
* `$fields` is 'all', 'all_with_object_id', or 'term_id'. Default true.
* @type array $meta_query Meta query clauses to limit retrieved terms by. See `WP_Meta_Query`.
* Default empty.
* }
* @param array|string $args See WP_Term_Query::__construct() for supported arguments.
* @return array|WP_Error The requested term data or empty array if no terms found.
* WP_Error if any of the $taxonomies don't exist.
*/
@ -1983,185 +1969,26 @@ function wp_get_object_terms($object_ids, $taxonomies, $args = array()) {
$object_ids = array($object_ids);
$object_ids = array_map('intval', $object_ids);
$defaults = array(
'orderby' => 'name',
'order' => 'ASC',
'fields' => 'all',
'parent' => '',
'update_term_meta_cache' => true,
'meta_query' => '',
);
$args = wp_parse_args( $args, $defaults );
$args['taxonomy'] = $taxonomies;
$args['object_ids'] = $object_ids;
$terms = array();
if ( count($taxonomies) > 1 ) {
foreach ( $taxonomies as $index => $taxonomy ) {
$t = get_taxonomy($taxonomy);
if ( isset($t->args) && is_array($t->args) && $args != array_merge($args, $t->args) ) {
unset($taxonomies[$index]);
$terms = array_merge($terms, wp_get_object_terms($object_ids, $taxonomy, array_merge($args, $t->args)));
}
}
} else {
$t = get_taxonomy($taxonomies[0]);
if ( isset($t->args) && is_array($t->args) )
$args = array_merge($args, $t->args);
}
$orderby = $args['orderby'];
$order = $args['order'];
$fields = $args['fields'];
if ( in_array( $orderby, array( 'term_id', 'name', 'slug', 'term_group' ) ) ) {
$orderby = "t.$orderby";
} elseif ( in_array( $orderby, array( 'count', 'parent', 'taxonomy', 'term_taxonomy_id' ) ) ) {
$orderby = "tt.$orderby";
} elseif ( 'term_order' === $orderby ) {
$orderby = 'tr.term_order';
} elseif ( 'none' === $orderby ) {
$orderby = '';
$order = '';
} else {
$orderby = 't.term_id';
}
// tt_ids queries can only be none or tr.term_taxonomy_id
if ( ('tt_ids' == $fields) && !empty($orderby) )
$orderby = 'tr.term_taxonomy_id';
if ( !empty($orderby) )
$orderby = "ORDER BY $orderby";
$order = strtoupper( $order );
if ( '' !== $order && ! in_array( $order, array( 'ASC', 'DESC' ) ) )
$order = 'ASC';
$taxonomy_array = $taxonomies;
$object_id_array = $object_ids;
$taxonomies = "'" . implode("', '", array_map( 'esc_sql', $taxonomies ) ) . "'";
$object_ids = implode(', ', $object_ids);
$select_this = '';
if ( 'all' == $fields ) {
$select_this = 't.*, tt.*';
} elseif ( 'ids' == $fields ) {
$select_this = 't.term_id';
} elseif ( 'names' == $fields ) {
$select_this = 't.name';
} elseif ( 'slugs' == $fields ) {
$select_this = 't.slug';
} elseif ( 'all_with_object_id' == $fields ) {
$select_this = 't.*, tt.*, tr.object_id';
}
$where = array(
"tt.taxonomy IN ($taxonomies)",
"tr.object_id IN ($object_ids)",
);
if ( '' !== $args['parent'] ) {
$where[] = $wpdb->prepare( 'tt.parent = %d', $args['parent'] );
}
// Meta query support.
$meta_query_join = '';
if ( ! empty( $args['meta_query'] ) ) {
$mquery = new WP_Meta_Query( $args['meta_query'] );
$mq_sql = $mquery->get_sql( 'term', 't', 'term_id' );
$meta_query_join .= $mq_sql['join'];
// Strip leading AND.
$where[] = preg_replace( '/^\s*AND/', '', $mq_sql['where'] );
}
$where = implode( ' AND ', $where );
$query = "SELECT $select_this FROM $wpdb->terms AS t INNER JOIN $wpdb->term_taxonomy AS tt ON tt.term_id = t.term_id INNER JOIN $wpdb->term_relationships AS tr ON tr.term_taxonomy_id = tt.term_taxonomy_id $meta_query_join WHERE $where $orderby $order";
$objects = false;
if ( 'all' == $fields || 'all_with_object_id' == $fields ) {
$_terms = $wpdb->get_results( $query );
$object_id_index = array();
foreach ( $_terms as $key => $term ) {
$term = sanitize_term( $term, $taxonomy, 'raw' );
$_terms[ $key ] = $term;
if ( isset( $term->object_id ) ) {
$object_id_index[ $key ] = $term->object_id;
}
}
update_term_cache( $_terms );
$_terms = array_map( 'get_term', $_terms );
// Re-add the object_id data, which is lost when fetching terms from cache.
if ( 'all_with_object_id' === $fields ) {
foreach ( $_terms as $key => $_term ) {
if ( isset( $object_id_index[ $key ] ) ) {
$_term->object_id = $object_id_index[ $key ];
}
}
}
$terms = array_merge( $terms, $_terms );
$objects = true;
} elseif ( 'ids' == $fields || 'names' == $fields || 'slugs' == $fields ) {
$_terms = $wpdb->get_col( $query );
$_field = ( 'ids' == $fields ) ? 'term_id' : 'name';
foreach ( $_terms as $key => $term ) {
$_terms[$key] = sanitize_term_field( $_field, $term, $term, $taxonomy, 'raw' );
}
$terms = array_merge( $terms, $_terms );
} elseif ( 'tt_ids' == $fields ) {
$terms = $wpdb->get_col("SELECT tr.term_taxonomy_id FROM $wpdb->term_relationships AS tr INNER JOIN $wpdb->term_taxonomy AS tt ON tr.term_taxonomy_id = tt.term_taxonomy_id WHERE tr.object_id IN ($object_ids) AND tt.taxonomy IN ($taxonomies) $orderby $order");
foreach ( $terms as $key => $tt_id ) {
$terms[$key] = sanitize_term_field( 'term_taxonomy_id', $tt_id, 0, $taxonomy, 'raw' ); // 0 should be the term id, however is not needed when using raw context.
}
}
// Update termmeta cache, if necessary.
if ( $args['update_term_meta_cache'] && ( 'all' === $fields || 'all_with_object_id' === $fields || 'ids' === $fields ) ) {
if ( 'ids' === $fields ) {
$term_ids = $terms;
} else {
$term_ids = wp_list_pluck( $terms, 'term_id' );
}
update_termmeta_cache( $term_ids );
}
if ( ! $terms ) {
$terms = array();
} elseif ( $objects && 'all_with_object_id' !== $fields ) {
$_tt_ids = array();
$_terms = array();
foreach ( $terms as $term ) {
if ( in_array( $term->term_taxonomy_id, $_tt_ids ) ) {
continue;
}
$_tt_ids[] = $term->term_taxonomy_id;
$_terms[] = $term;
}
$terms = $_terms;
} elseif ( ! $objects ) {
$terms = array_values( array_unique( $terms ) );
}
$terms = get_terms( $args );
/**
* Filters the terms for a given object or objects.
*
* @since 4.2.0
*
* @param array $terms An array of terms for the given object or objects.
* @param array $object_id_array Array of object IDs for which `$terms` were retrieved.
* @param array $taxonomy_array Array of taxonomies from which `$terms` were retrieved.
* @param array $args An array of arguments for retrieving terms for the given
* object(s). See wp_get_object_terms() for details.
* @param array $terms An array of terms for the given object or objects.
* @param array $object_ids Array of object IDs for which `$terms` were retrieved.
* @param array $taxonomies Array of taxonomies from which `$terms` were retrieved.
* @param array $args An array of arguments for retrieving terms for the given
* object(s). See wp_get_object_terms() for details.
*/
$terms = apply_filters( 'get_object_terms', $terms, $object_id_array, $taxonomy_array, $args );
$terms = apply_filters( 'get_object_terms', $terms, $object_ids, $taxonomies, $args );
$object_ids = implode( ',', $object_ids );
$taxonomies = implode( ',', $taxonomies );
/**
* Filters the terms for a given object or objects.

View File

@ -4,7 +4,7 @@
*
* @global string $wp_version
*/
$wp_version = '4.7-alpha-38666';
$wp_version = '4.7-alpha-38667';
/**
* Holds the WordPress DB revision, increments when changes are made to the WordPress DB schema.