/** * Class used for querying terms. * * @since 4.6.0 * * @see WP_Term_Query::__construct() for accepted arguments. */ #[AllowDynamicProperties] class WP_Term_Query {
/** * SQL string used to perform database query. * * @since 4.6.0 * @var string */ public $request;
/** * Metadata query container. * * @since 4.6.0 * @var WP_Meta_Query A meta query instance. */ public $meta_query = false;
/** * Query vars set by the user. * * @since 4.6.0 * @var array */ public $query_vars;
/** * Default values for query vars. * * @since 4.6.0 * @var array */ public $query_var_defaults;
/** * List of terms located by the query. * * @since 4.6.0 * @var array */ public $terms;
/** * Constructor. * * Sets up the term query, based on the query vars passed. * * @since 4.6.0 * @since 4.6.0 Introduced 'term_taxonomy_id' parameter. * @since 4.7.0 Introduced 'object_ids' parameter. * @since 4.9.0 Added 'slug__in' support for 'orderby'. * @since 5.1.0 Introduced the 'meta_compare_key' parameter. * @since 5.3.0 Introduced the 'meta_type_key' parameter. * @since 6.4.0 Introduced the 'cache_results' parameter. * * @param string|array $query { * Optional. Array or query string of term query parameters. Default empty. * * @type string|string[] $taxonomy Taxonomy name, or array of taxonomy names, to which results * should be limited. * @type int|int[] $object_ids 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', 'parent', 'term_order'). Unless `$object_ids` * is not empty, 'term_order' is treated the same as 'term_id'. * - 'count' to use the number of objects associated with the term. * - 'include' to match the 'order' of the `$include` param. * - 'slug__in' to match the 'order' of the `$slug` param. * - 'meta_value' * - 'meta_value_num'. * - The value of `$meta_key`. * - The array keys of `$meta_query`. * - 'none' to omit the ORDER BY clause. * Default '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 int[]|string $include Array or comma/space-separated string of term IDs to include. * Default empty array. * @type int[]|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 int[]|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). Note that `$number` may * not return accurate results when coupled with `$object_ids`. * See #41796 for details. * @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 (`WP_Term[]`). * - 'all_with_object_id' Returns an array of term objects * with the 'object_id' param (`WP_Term[]`). Works only * when the `$object_ids` parameter is populated. * - 'ids' Returns an array of term IDs (`int[]`). * - 'tt_ids' Returns an array of term taxonomy IDs (`int[]`). * - 'names' Returns an array of term names (`string[]`). * - 'slugs' Returns an array of term slugs (`string[]`). * - 'count' Returns the number of matching terms (`int`). * - 'id=>parent' Returns an associative array of parent term IDs, * keyed by term ID (`int[]`). * - 'id=>name' Returns an associative array of term names, * keyed by term ID (`string[]`). * - 'id=>slug' Returns an associative array of term slugs, * keyed by term ID (`string[]`). * Default 'all'. * @type string|string[] $name Name or array of names to return term(s) for. * Default empty. * @type string|string[] $slug Slug or array of slugs to return term(s) for. * Default empty. * @type int|int[] $term_taxonomy_id Term taxonomy ID, or array of term taxonomy IDs, * to match when querying terms. * @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 '' (disabled). * Default ''. * @type int $child_of Term ID to retrieve child terms of. If multiple taxonomies * are passed, `$child_of` is ignored. Default 0. * @type int $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 'core'. * @type bool $cache_results Whether to cache term information. Default true. * @type bool $update_term_meta_cache Whether to prime meta caches for matched terms. Default true. * @type string|string[] $meta_key Meta key or keys to filter by. * @type string|string[] $meta_value Meta value or values to filter by. * @type string $meta_compare MySQL operator used for comparing the meta value. * See WP_Meta_Query::__construct() for accepted values and default value. * @type string $meta_compare_key MySQL operator used for comparing the meta key. * See WP_Meta_Query::__construct() for accepted values and default value. * @type string $meta_type MySQL data type that the meta_value column will be CAST to for comparisons. * See WP_Meta_Query::__construct() for accepted values and default value. * @type string $meta_type_key MySQL data type that the meta_key column will be CAST to for comparisons. * See WP_Meta_Query::__construct() for accepted values and default value. * @type array $meta_query An associative array of WP_Meta_Query arguments. * See WP_Meta_Query::__construct() for accepted values. * } */ public function __construct( $query = '' ) { $this->query_var_defaults = array( 'taxonomy' => null, 'object_ids' => null, 'orderby' => 'name', 'order' => 'ASC', 'hide_empty' => true, 'include' => array(), 'exclude' => array(), 'exclude_tree' => array(), 'number' => '', 'offset' => '', 'fields' => 'all', 'name' => '', 'slug' => '', 'term_taxonomy_id' => '', 'hierarchical' => true, 'search' => '', 'name__like' => '', 'description__like' => '', 'pad_counts' => false, 'get' => '', 'child_of' => 0, 'parent' => '', 'childless' => false, 'cache_domain' => 'core', 'cache_results' => true, 'update_term_meta_cache' => true, 'meta_query' => '', 'meta_key' => '', 'meta_value' => '', 'meta_type' => '', 'meta_compare' => '', );
/** * Fires after term query vars have been parsed. * * @since 4.6.0 * * @param WP_Term_Query $query Current instance of WP_Term_Query. */ do_action( 'parse_term_query', $this ); }
/** * Sets up the query and retrieves the results. * * The return type varies depending on the value passed to `$args['fields']`. See * WP_Term_Query::get_terms() for details. * * @since 4.6.0 * * @param string|array $query Array or URL query string of parameters. * @return WP_Term[]|int[]|string[]|string Array of terms, or number of terms as numeric string * when 'count' is passed to `$args['fields']`. */ public function query( $query ) { $this->query_vars = wp_parse_args( $query ); return $this->get_terms(); }
/** * Retrieves the query results. * * The return type varies depending on the value passed to `$args['fields']`. * * The following will result in an array of `WP_Term` objects being returned: * * - 'all' * - 'all_with_object_id' * * The following will result in a numeric string being returned: * * - 'count' * * The following will result in an array of text strings being returned: * * - 'id=>name' * - 'id=>slug' * - 'names' * - 'slugs' * * The following will result in an array of numeric strings being returned: * * - 'id=>parent' * * The following will result in an array of integers being returned: * * - 'ids' * - 'tt_ids' * * @since 4.6.0 * * @global wpdb $wpdb WordPress database abstraction object. * * @return WP_Term[]|int[]|string[]|string Array of terms, or number of terms as numeric string * when 'count' is passed to `$args['fields']`. */ public function get_terms() { global $wpdb;
// Set up meta_query so it's available to 'pre_get_terms'. $this->meta_query = new WP_Meta_Query(); $this->meta_query->parse_query_vars( $args );
/** * Fires before terms are retrieved. * * @since 4.6.0 * * @param WP_Term_Query $query Current instance of WP_Term_Query (passed by reference). */ do_action_ref_array( 'pre_get_terms', array( &$this ) );
$taxonomies = (array) $args['taxonomy'];
// Save queries by not crawling the tree in the case of multiple taxes or a flat tax. $has_hierarchical_tax = false; if ( $taxonomies ) { foreach ( $taxonomies as $_tax ) { if ( is_taxonomy_hierarchical( $_tax ) ) { $has_hierarchical_tax = true; } } } else { // When no taxonomies are provided, assume we have to descend the tree. $has_hierarchical_tax = true; }
// '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"; }
// 'childless' terms are those without an entry in the flattened term hierarchy. $childless = (bool) $args['childless']; if ( $childless ) { foreach ( $taxonomies as $_tax ) { $term_hierarchy = _get_term_hierarchy( $_tax ); $exclusions = array_merge( array_keys( $term_hierarchy ), $exclusions ); } }
/** * Filters the terms to exclude from the terms query. * * @since 2.3.0 * * @param string $exclusions `NOT IN` clause of the terms query. * @param array $args An array of terms query arguments. * @param string[] $taxonomies An array of taxonomy names. */ $exclusions = apply_filters( 'list_terms_exclusions', $exclusions, $args, $taxonomies );
if ( ! empty( $exclusions ) ) { // Strip leading 'AND'. Must do string manipulation here for backward compatibility with filter. $this->sql_clauses['where']['exclusions'] = preg_replace( '/^\s*AND\s*/', '', $exclusions ); }
// Meta query support. $join = ''; $distinct = '';
// Reparse meta_query query_vars, in case they were modified in a 'pre_get_terms' callback. $this->meta_query->parse_query_vars( $this->query_vars ); $mq_sql = $this->meta_query->get_sql( 'term', 't', 'term_id' ); $meta_clauses = $this->meta_query->get_clauses();
/** * Filters the fields to select in the terms query. * * Field lists modified using this filter will only modify the term fields returned * by the function when the `$fields` parameter set to 'count' or 'all'. In all other * cases, the term fields in the results array will be determined by the `$fields` * parameter alone. * * Use of this filter can result in unpredictable behavior, and is not recommended. * * @since 2.8.0 * * @param string[] $selects An array of fields to select for the terms query. * @param array $args An array of term query arguments. * @param string[] $taxonomies An array of taxonomy names. */ $fields = implode( ', ', apply_filters( 'get_terms_fields', $selects, $args, $taxonomies ) );
$join .= " INNER JOIN $wpdb->term_taxonomy AS tt ON t.term_id = tt.term_id";
if ( ! empty( $this->query_vars['object_ids'] ) ) { $join .= " INNER JOIN {$wpdb->term_relationships} AS tr ON tr.term_taxonomy_id = tt.term_taxonomy_id"; $distinct = 'DISTINCT'; }
$where = implode( ' AND ', $this->sql_clauses['where'] );
/** * Filters the terms query SQL clauses. * * @since 3.1.0 * * @param string[] $clauses { * Associative array of the clauses for the query. * * @type string $fields The SELECT clause of the query. * @type string $join The JOIN clause of the query. * @type string $where The WHERE clause of the query. * @type string $distinct The DISTINCT clause of the query. * @type string $orderby The ORDER BY clause of the query. * @type string $order The ORDER clause of the query. * @type string $limits The LIMIT clause of the query. * } * @param string[] $taxonomies An array of taxonomy names. * @param array $args An array of term query arguments. */ $clauses = apply_filters( 'terms_clauses', compact( $pieces ), $taxonomies, $args );
// Beginning of the string is on a new line to prevent leading whitespace. See https://core.trac.wordpress.org/ticket/56841. $this->request = "{$this->sql_clauses['select']} {$this->sql_clauses['from']} {$where} {$this->sql_clauses['orderby']} {$this->sql_clauses['limits']}";
$this->terms = null;
/** * Filters the terms array before the query takes place. * * Return a non-null value to bypass WordPress' default term queries. * * @since 5.3.0 * * @param array|null $terms Return an array of term data to short-circuit WP's term query, * or null to allow WP queries to run normally. * @param WP_Term_Query $query The WP_Term_Query instance, passed by reference. */ $this->terms = apply_filters_ref_array( 'terms_pre_query', array( $this->terms, &$this ) );
if ( null !== $this->terms ) { return $this->terms; }
/** * Parse and sanitize 'orderby' keys passed to the term query. * * @since 4.6.0 * * @param string $orderby_raw Alias for the field to order by. * @return string|false Value to used in the ORDER clause. False otherwise. */ protected function parse_orderby( $orderby_raw ) { $_orderby = strtolower( $orderby_raw ); $maybe_orderby_meta = false;
// This may be a value of orderby related to meta. $maybe_orderby_meta = true; }
/** * Filters the ORDERBY clause of the terms query. * * @since 2.8.0 * * @param string $orderby `ORDERBY` clause of the terms query. * @param array $args An array of term query arguments. * @param string[] $taxonomies An array of taxonomy names. */ $orderby = apply_filters( 'get_terms_orderby', $orderby, $this->query_vars, $this->query_vars['taxonomy'] );
// Run after the 'get_terms_orderby' filter for backward compatibility. if ( $maybe_orderby_meta ) { $maybe_orderby_meta = $this->parse_orderby_meta( $_orderby ); if ( $maybe_orderby_meta ) { $orderby = $maybe_orderby_meta; } }
/** * Generate the ORDER BY clause for an 'orderby' param that is potentially related to a meta query. * * @since 4.6.0 * * @param string $orderby_raw Raw 'orderby' value passed to WP_Term_Query. * @return string ORDER BY clause. */ protected function parse_orderby_meta( $orderby_raw ) { $orderby = '';
// Tell the meta query to generate its SQL, so we have access to table aliases. $this->meta_query->get_sql( 'term', 't', 'term_id' ); $meta_clauses = $this->meta_query->get_clauses(); if ( ! $meta_clauses || ! $orderby_raw ) { return $orderby; }
/** * Used internally to generate a SQL string related to the 'search' parameter. * * @since 4.6.0 * * @global wpdb $wpdb WordPress database abstraction object. * * @param string $search Search string. * @return string Search SQL. */ protected function get_search_sql( $search ) { global $wpdb;
$like = '%' . $wpdb->esc_like( $search ) . '%';
return $wpdb->prepare( '((t.name LIKE %s) OR (t.slug LIKE %s))', $like, $like ); }
/** * Creates an array of term objects from an array of term IDs. * * Also discards invalid term objects. * * @since 4.9.8 * * @param Object[]|int[] $terms List of objects or term ids. * @return WP_Term[] Array of `WP_Term` objects. */ protected function populate_terms( $terms ) { $term_objects = array(); if ( ! is_array( $terms ) ) { return $term_objects; }