File "class-wp-term-query.php"

Full Path: /home/rrterraplen/public_html/wp-includes-20241221212712/blocks/embed/class-wp-term-query.php
File size: 20 KB
MIME-type: text/x-php
Charset: utf-8

<?php

/**
 * Taxonomy API: WP_Term_Query class.
 *
 * @package WordPress
 * @subpackage Taxonomy
 * @since 4.6.0
 */

/**
 * 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;

	/**
	 * Metadata query clauses.
	 *
	 * @since 4.6.0
	 * @var array
	 */
	protected $meta_query_clauses;

	/**
	 * SQL query clauses.
	 *
	 * @since 4.6.0
	 * @var array
	 */
	protected $sql_clauses = array(
		'select'  => '',
		'from'    => '',
		'where'   => array(),
		'orderby' => '',
		'limits'  => '',
	);

	/**
	 * 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'           => '',
		);

		if ( ! empty( $query ) ) {
			$this->query( $query );
		}
	}

	/**
	 * Parse arguments passed to the term query with default query parameters.
	 *
	 * @since 4.6.0
	 *
	 * @param string|array $query WP_Term_Query arguments. See WP_Term_Query::__construct() for accepted arguments.
	 */
	public function parse_query( $query = '' ) {
		if ( empty( $query ) ) {
			$query = $this->query_vars;
		}

		$taxonomies = isset( $query['taxonomy'] ) ? (array) $query['taxonomy'] : null;

		/**
		 * Filters the terms query default arguments.
		 *
		 * Use {@see 'get_terms_args'} to filter the passed arguments.
		 *
		 * @since 4.4.0
		 *
		 * @param array    $defaults   An array of default get_terms() arguments.
		 * @param string[] $taxonomies An array of taxonomy names.
		 */
		$this->query_var_defaults = apply_filters( 'get_terms_defaults', $this->query_var_defaults, $taxonomies );

		$query = wp_parse_args( $query, $this->query_var_defaults );

		$query['number'] = absint( $query['number'] );
		$query['offset'] = absint( $query['offset'] );

		// 'parent' overrides 'child_of'.
		if ( 0 < (int) $query['parent'] ) {
			$query['child_of'] = false;
		}

		if ( 'all' === $query['get'] ) {
			$query['childless']    = false;
			$query['child_of']     = 0;
			$query['hide_empty']   = 0;
			$query['hierarchical'] = false;
			$query['pad_counts']   = false;
		}

		$query['taxonomy'] = $taxonomies;

		$this->query_vars = $query;

		/**
		 * 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;

		$this->parse_query( $this->query_vars );
		$args = &$this->query_vars;

		// 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;
		}

		if ( ! $has_hierarchical_tax ) {
			$args['hierarchical'] = false;
			$args['pad_counts']   = false;
		}

		// 'parent' overrides 'child_of'.
		if ( 0 < (int) $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;
		}

		/**
		 * Filters the terms query arguments.
		 *
		 * @since 3.1.0
		 *
		 * @param array    $args       An array of get_terms() arguments.
		 * @param string[] $taxonomies An array of taxonomy names.
		 */
		$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 ) {
				if ( 'count' === $args['fields'] ) {
					return 0;
				} else {
					$this->terms = array();
					return $this->terms;
				}
			}
		}

		// '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";
		}

		$order = $this->parse_order( $this->query_vars['order'] );

		if ( $taxonomies ) {
			$this->sql_clauses['where']['taxonomy'] =
				"tt.taxonomy IN ('" . implode( "', '", array_map( 'esc_sql', $taxonomies ) ) . "')";
		}

		if ( empty( $args['exclude'] ) ) {
			$args['exclude'] = array();
		}

		if ( empty( $args['include'] ) ) {
			$args['include'] = array();
		}

		$exclude      = $args['exclude'];
		$exclude_tree = $args['exclude_tree'];
		$include      = $args['include'];

		$inclusions = '';
		if ( ! empty( $include ) ) {
			$exclude      = '';
			$exclude_tree = '';
			$inclusions   = implode( ',', wp_parse_id_list( $include ) );
		}

		if ( ! empty( $inclusions ) ) {
			$this->sql_clauses['where']['inclusions'] = 't.term_id IN ( ' . $inclusions . ' )';
		}

		$exclusions = array();
		if ( ! empty( $exclude_tree ) ) {
			$exclude_tree      = wp_parse_id_list( $exclude_tree );
			$excluded_children = $exclude_tree;

			foreach ( $exclude_tree as $extrunk ) {
				$excluded_children = array_merge(
					$excluded_children,
					(array) get_terms(
						array(
							'taxonomy'   => reset( $taxonomies ),
							'child_of'   => (int) $extrunk,
							'fields'     => 'ids',
							'hide_empty' => 0,
						)
					)
				);
			}

			$exclusions = array_merge( $excluded_children, $exclusions );
		}

		if ( ! empty( $exclude ) ) {
			$exclusions = array_merge( wp_parse_id_list( $exclude ), $exclusions );
		}

		// '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 );
			}
		}

		if ( ! empty( $exclusions ) ) {
			$exclusions = 't.term_id NOT IN (' . implode( ',', array_map( 'intval', $exclusions ) ) . ')';
		} else {
			$exclusions = '';
		}

		/**
		 * Filters the terms to exclude from the terms query.
		 *
		 * @since 2.3.0
		 *
		 * @param string   $ex