[ Index ]

PHP Cross Reference of WordPress Trunk (Updated Daily)

Search

title

Body

[close]

/wp-includes/ -> class-wp-term-query.php (source)

   1  <?php
   2  
   3  /**
   4   * Taxonomy API: WP_Term_Query class.
   5   *
   6   * @package WordPress
   7   * @subpackage Taxonomy
   8   * @since 4.6.0
   9   */
  10  
  11  /**
  12   * Class used for querying terms.
  13   *
  14   * @since 4.6.0
  15   *
  16   * @see WP_Term_Query::__construct() for accepted arguments.
  17   */
  18  #[AllowDynamicProperties]
  19  class WP_Term_Query {
  20  
  21      /**
  22       * SQL string used to perform database query.
  23       *
  24       * @since 4.6.0
  25       * @var string
  26       */
  27      public $request;
  28  
  29      /**
  30       * Metadata query container.
  31       *
  32       * @since 4.6.0
  33       * @var WP_Meta_Query A meta query instance.
  34       */
  35      public $meta_query = false;
  36  
  37      /**
  38       * Metadata query clauses.
  39       *
  40       * @since 4.6.0
  41       * @var array
  42       */
  43      protected $meta_query_clauses;
  44  
  45      /**
  46       * SQL query clauses.
  47       *
  48       * @since 4.6.0
  49       * @var array
  50       */
  51      protected $sql_clauses = array(
  52          'select'  => '',
  53          'from'    => '',
  54          'where'   => array(),
  55          'orderby' => '',
  56          'limits'  => '',
  57      );
  58  
  59      /**
  60       * Query vars set by the user.
  61       *
  62       * @since 4.6.0
  63       * @var array
  64       */
  65      public $query_vars;
  66  
  67      /**
  68       * Default values for query vars.
  69       *
  70       * @since 4.6.0
  71       * @var array
  72       */
  73      public $query_var_defaults;
  74  
  75      /**
  76       * List of terms located by the query.
  77       *
  78       * @since 4.6.0
  79       * @var array
  80       */
  81      public $terms;
  82  
  83      /**
  84       * Constructor.
  85       *
  86       * Sets up the term query, based on the query vars passed.
  87       *
  88       * @since 4.6.0
  89       * @since 4.6.0 Introduced 'term_taxonomy_id' parameter.
  90       * @since 4.7.0 Introduced 'object_ids' parameter.
  91       * @since 4.9.0 Added 'slug__in' support for 'orderby'.
  92       * @since 5.1.0 Introduced the 'meta_compare_key' parameter.
  93       * @since 5.3.0 Introduced the 'meta_type_key' parameter.
  94       * @since 6.4.0 Introduced the 'cache_results' parameter.
  95       *
  96       * @param string|array $query {
  97       *     Optional. Array or query string of term query parameters. Default empty.
  98       *
  99       *     @type string|string[] $taxonomy               Taxonomy name, or array of taxonomy names, to which results
 100       *                                                   should be limited.
 101       *     @type int|int[]       $object_ids             Object ID, or array of object IDs. Results will be
 102       *                                                   limited to terms associated with these objects.
 103       *     @type string          $orderby                Field(s) to order terms by. Accepts:
 104       *                                                   - Term fields ('name', 'slug', 'term_group', 'term_id', 'id',
 105       *                                                     'description', 'parent', 'term_order'). Unless `$object_ids`
 106       *                                                     is not empty, 'term_order' is treated the same as 'term_id'.
 107       *                                                   - 'count' to use the number of objects associated with the term.
 108       *                                                   - 'include' to match the 'order' of the `$include` param.
 109       *                                                   - 'slug__in' to match the 'order' of the `$slug` param.
 110       *                                                   - 'meta_value'
 111       *                                                   - 'meta_value_num'.
 112       *                                                   - The value of `$meta_key`.
 113       *                                                   - The array keys of `$meta_query`.
 114       *                                                   - 'none' to omit the ORDER BY clause.
 115       *                                                   Default 'name'.
 116       *     @type string          $order                  Whether to order terms in ascending or descending order.
 117       *                                                   Accepts 'ASC' (ascending) or 'DESC' (descending).
 118       *                                                   Default 'ASC'.
 119       *     @type bool|int        $hide_empty             Whether to hide terms not assigned to any posts. Accepts
 120       *                                                   1|true or 0|false. Default 1|true.
 121       *     @type int[]|string    $include                Array or comma/space-separated string of term IDs to include.
 122       *                                                   Default empty array.
 123       *     @type int[]|string    $exclude                Array or comma/space-separated string of term IDs to exclude.
 124       *                                                   If `$include` is non-empty, `$exclude` is ignored.
 125       *                                                   Default empty array.
 126       *     @type int[]|string    $exclude_tree           Array or comma/space-separated string of term IDs to exclude
 127       *                                                   along with all of their descendant terms. If `$include` is
 128       *                                                   non-empty, `$exclude_tree` is ignored. Default empty array.
 129       *     @type int|string      $number                 Maximum number of terms to return. Accepts ''|0 (all) or any
 130       *                                                   positive number. Default ''|0 (all). Note that `$number` may
 131       *                                                   not return accurate results when coupled with `$object_ids`.
 132       *                                                   See #41796 for details.
 133       *     @type int             $offset                 The number by which to offset the terms query. Default empty.
 134       *     @type string          $fields                 Term fields to query for. Accepts:
 135       *                                                   - 'all' Returns an array of complete term objects (`WP_Term[]`).
 136       *                                                   - 'all_with_object_id' Returns an array of term objects
 137       *                                                     with the 'object_id' param (`WP_Term[]`). Works only
 138       *                                                     when the `$object_ids` parameter is populated.
 139       *                                                   - 'ids' Returns an array of term IDs (`int[]`).
 140       *                                                   - 'tt_ids' Returns an array of term taxonomy IDs (`int[]`).
 141       *                                                   - 'names' Returns an array of term names (`string[]`).
 142       *                                                   - 'slugs' Returns an array of term slugs (`string[]`).
 143       *                                                   - 'count' Returns the number of matching terms (`int`).
 144       *                                                   - 'id=>parent' Returns an associative array of parent term IDs,
 145       *                                                      keyed by term ID (`int[]`).
 146       *                                                   - 'id=>name' Returns an associative array of term names,
 147       *                                                      keyed by term ID (`string[]`).
 148       *                                                   - 'id=>slug' Returns an associative array of term slugs,
 149       *                                                      keyed by term ID (`string[]`).
 150       *                                                   Default 'all'.
 151       *     @type string|string[] $name                   Name or array of names to return term(s) for.
 152       *                                                   Default empty.
 153       *     @type string|string[] $slug                   Slug or array of slugs to return term(s) for.
 154       *                                                   Default empty.
 155       *     @type int|int[]       $term_taxonomy_id       Term taxonomy ID, or array of term taxonomy IDs,
 156       *                                                   to match when querying terms.
 157       *     @type bool            $hierarchical           Whether to include terms that have non-empty descendants
 158       *                                                   (even if `$hide_empty` is set to true). Default true.
 159       *     @type string          $search                 Search criteria to match terms. Will be SQL-formatted with
 160       *                                                   wildcards before and after. Default empty.
 161       *     @type string          $name__like             Retrieve terms with criteria by which a term is LIKE
 162       *                                                   `$name__like`. Default empty.
 163       *     @type string          $description__like      Retrieve terms where the description is LIKE
 164       *                                                   `$description__like`. Default empty.
 165       *     @type bool            $pad_counts             Whether to pad the quantity of a term's children in the
 166       *                                                   quantity of each term's "count" object variable.
 167       *                                                   Default false.
 168       *     @type string          $get                    Whether to return terms regardless of ancestry or whether the
 169       *                                                   terms are empty. Accepts 'all' or '' (disabled).
 170       *                                                   Default ''.
 171       *     @type int             $child_of               Term ID to retrieve child terms of. If multiple taxonomies
 172       *                                                   are passed, `$child_of` is ignored. Default 0.
 173       *     @type int             $parent                 Parent term ID to retrieve direct-child terms of.
 174       *                                                   Default empty.
 175       *     @type bool            $childless              True to limit results to terms that have no children.
 176       *                                                   This parameter has no effect on non-hierarchical taxonomies.
 177       *                                                   Default false.
 178       *     @type string          $cache_domain           Unique cache key to be produced when this query is stored in
 179       *                                                   an object cache. Default 'core'.
 180       *     @type bool            $cache_results          Whether to cache term information. Default true.
 181       *     @type bool            $update_term_meta_cache Whether to prime meta caches for matched terms. Default true.
 182       *     @type string|string[] $meta_key               Meta key or keys to filter by.
 183       *     @type string|string[] $meta_value             Meta value or values to filter by.
 184       *     @type string          $meta_compare           MySQL operator used for comparing the meta value.
 185       *                                                   See WP_Meta_Query::__construct() for accepted values and default value.
 186       *     @type string          $meta_compare_key       MySQL operator used for comparing the meta key.
 187       *                                                   See WP_Meta_Query::__construct() for accepted values and default value.
 188       *     @type string          $meta_type              MySQL data type that the meta_value column will be CAST to for comparisons.
 189       *                                                   See WP_Meta_Query::__construct() for accepted values and default value.
 190       *     @type string          $meta_type_key          MySQL data type that the meta_key column will be CAST to for comparisons.
 191       *                                                   See WP_Meta_Query::__construct() for accepted values and default value.
 192       *     @type array           $meta_query             An associative array of WP_Meta_Query arguments.
 193       *                                                   See WP_Meta_Query::__construct() for accepted values.
 194       * }
 195       */
 196  	public function __construct( $query = '' ) {
 197          $this->query_var_defaults = array(
 198              'taxonomy'               => null,
 199              'object_ids'             => null,
 200              'orderby'                => 'name',
 201              'order'                  => 'ASC',
 202              'hide_empty'             => true,
 203              'include'                => array(),
 204              'exclude'                => array(),
 205              'exclude_tree'           => array(),
 206              'number'                 => '',
 207              'offset'                 => '',
 208              'fields'                 => 'all',
 209              'name'                   => '',
 210              'slug'                   => '',
 211              'term_taxonomy_id'       => '',
 212              'hierarchical'           => true,
 213              'search'                 => '',
 214              'name__like'             => '',
 215              'description__like'      => '',
 216              'pad_counts'             => false,
 217              'get'                    => '',
 218              'child_of'               => 0,
 219              'parent'                 => '',
 220              'childless'              => false,
 221              'cache_domain'           => 'core',
 222              'cache_results'          => true,
 223              'update_term_meta_cache' => true,
 224              'meta_query'             => '',
 225              'meta_key'               => '',
 226              'meta_value'             => '',
 227              'meta_type'              => '',
 228              'meta_compare'           => '',
 229          );
 230  
 231          if ( ! empty( $query ) ) {
 232              $this->query( $query );
 233          }
 234      }
 235  
 236      /**
 237       * Parse arguments passed to the term query with default query parameters.
 238       *
 239       * @since 4.6.0
 240       *
 241       * @param string|array $query WP_Term_Query arguments. See WP_Term_Query::__construct() for accepted arguments.
 242       */
 243  	public function parse_query( $query = '' ) {
 244          if ( empty( $query ) ) {
 245              $query = $this->query_vars;
 246          }
 247  
 248          $taxonomies = isset( $query['taxonomy'] ) ? (array) $query['taxonomy'] : null;
 249  
 250          /**
 251           * Filters the terms query default arguments.
 252           *
 253           * Use {@see 'get_terms_args'} to filter the passed arguments.
 254           *
 255           * @since 4.4.0
 256           *
 257           * @param array    $defaults   An array of default get_terms() arguments.
 258           * @param string[] $taxonomies An array of taxonomy names.
 259           */
 260          $this->query_var_defaults = apply_filters( 'get_terms_defaults', $this->query_var_defaults, $taxonomies );
 261  
 262          $query = wp_parse_args( $query, $this->query_var_defaults );
 263  
 264          $query['number'] = absint( $query['number'] );
 265          $query['offset'] = absint( $query['offset'] );
 266  
 267          // 'parent' overrides 'child_of'.
 268          if ( 0 < (int) $query['parent'] ) {
 269              $query['child_of'] = false;
 270          }
 271  
 272          if ( 'all' === $query['get'] ) {
 273              $query['childless']    = false;
 274              $query['child_of']     = 0;
 275              $query['hide_empty']   = 0;
 276              $query['hierarchical'] = false;
 277              $query['pad_counts']   = false;
 278          }
 279  
 280          $query['taxonomy'] = $taxonomies;
 281  
 282          $this->query_vars = $query;
 283  
 284          /**
 285           * Fires after term query vars have been parsed.
 286           *
 287           * @since 4.6.0
 288           *
 289           * @param WP_Term_Query $query Current instance of WP_Term_Query.
 290           */
 291          do_action( 'parse_term_query', $this );
 292      }
 293  
 294      /**
 295       * Sets up the query and retrieves the results.
 296       *
 297       * The return type varies depending on the value passed to `$args['fields']`. See
 298       * WP_Term_Query::get_terms() for details.
 299       *
 300       * @since 4.6.0
 301       *
 302       * @param string|array $query Array or URL query string of parameters.
 303       * @return WP_Term[]|int[]|string[]|string Array of terms, or number of terms as numeric string
 304       *                                         when 'count' is passed to `$args['fields']`.
 305       */
 306  	public function query( $query ) {
 307          $this->query_vars = wp_parse_args( $query );
 308          return $this->get_terms();
 309      }
 310  
 311      /**
 312       * Retrieves the query results.
 313       *
 314       * The return type varies depending on the value passed to `$args['fields']`.
 315       *
 316       * The following will result in an array of `WP_Term` objects being returned:
 317       *
 318       *   - 'all'
 319       *   - 'all_with_object_id'
 320       *
 321       * The following will result in a numeric string being returned:
 322       *
 323       *   - 'count'
 324       *
 325       * The following will result in an array of text strings being returned:
 326       *
 327       *   - 'id=>name'
 328       *   - 'id=>slug'
 329       *   - 'names'
 330       *   - 'slugs'
 331       *
 332       * The following will result in an array of numeric strings being returned:
 333       *
 334       *   - 'id=>parent'
 335       *
 336       * The following will result in an array of integers being returned:
 337       *
 338       *   - 'ids'
 339       *   - 'tt_ids'
 340       *
 341       * @since 4.6.0
 342       *
 343       * @global wpdb $wpdb WordPress database abstraction object.
 344       *
 345       * @return WP_Term[]|int[]|string[]|string Array of terms, or number of terms as numeric string
 346       *                                         when 'count' is passed to `$args['fields']`.
 347       */
 348  	public function get_terms() {
 349          global $wpdb;
 350  
 351          $this->parse_query( $this->query_vars );
 352          $args = &$this->query_vars;
 353  
 354          // Set up meta_query so it's available to 'pre_get_terms'.
 355          $this->meta_query = new WP_Meta_Query();
 356          $this->meta_query->parse_query_vars( $args );
 357  
 358          /**
 359           * Fires before terms are retrieved.
 360           *
 361           * @since 4.6.0
 362           *
 363           * @param WP_Term_Query $query Current instance of WP_Term_Query (passed by reference).
 364           */
 365          do_action_ref_array( 'pre_get_terms', array( &$this ) );
 366  
 367          $taxonomies = (array) $args['taxonomy'];
 368  
 369          // Save queries by not crawling the tree in the case of multiple taxes or a flat tax.
 370          $has_hierarchical_tax = false;
 371          if ( $taxonomies ) {
 372              foreach ( $taxonomies as $_tax ) {
 373                  if ( is_taxonomy_hierarchical( $_tax ) ) {
 374                      $has_hierarchical_tax = true;
 375                  }
 376              }
 377          } else {
 378              // When no taxonomies are provided, assume we have to descend the tree.
 379              $has_hierarchical_tax = true;
 380          }
 381  
 382          if ( ! $has_hierarchical_tax ) {
 383              $args['hierarchical'] = false;
 384              $args['pad_counts']   = false;
 385          }
 386  
 387          // 'parent' overrides 'child_of'.
 388          if ( 0 < (int) $args['parent'] ) {
 389              $args['child_of'] = false;
 390          }
 391  
 392          if ( 'all' === $args['get'] ) {
 393              $args['childless']    = false;
 394              $args['child_of']     = 0;
 395              $args['hide_empty']   = 0;
 396              $args['hierarchical'] = false;
 397              $args['pad_counts']   = false;
 398          }
 399  
 400          /**
 401           * Filters the terms query arguments.
 402           *
 403           * @since 3.1.0
 404           *
 405           * @param array    $args       An array of get_terms() arguments.
 406           * @param string[] $taxonomies An array of taxonomy names.
 407           */
 408          $args = apply_filters( 'get_terms_args', $args, $taxonomies );
 409  
 410          // Avoid the query if the queried parent/child_of term has no descendants.
 411          $child_of = $args['child_of'];
 412          $parent   = $args['parent'];
 413  
 414          if ( $child_of ) {
 415              $_parent = $child_of;
 416          } elseif ( $parent ) {
 417              $_parent = $parent;
 418          } else {
 419              $_parent = false;
 420          }
 421  
 422          if ( $_parent ) {
 423              $in_hierarchy = false;
 424              foreach ( $taxonomies as $_tax ) {
 425                  $hierarchy = _get_term_hierarchy( $_tax );
 426  
 427                  if ( isset( $hierarchy[ $_parent ] ) ) {
 428                      $in_hierarchy = true;
 429                  }
 430              }
 431  
 432              if ( ! $in_hierarchy ) {
 433                  if ( 'count' === $args['fields'] ) {
 434                      return 0;
 435                  } else {
 436                      $this->terms = array();
 437                      return $this->terms;
 438                  }
 439              }
 440          }
 441  
 442          // 'term_order' is a legal sort order only when joining the relationship table.
 443          $_orderby = $this->query_vars['orderby'];
 444          if ( 'term_order' === $_orderby && empty( $this->query_vars['object_ids'] ) ) {
 445              $_orderby = 'term_id';
 446          }
 447  
 448          $orderby = $this->parse_orderby( $_orderby );
 449  
 450          if ( $orderby ) {
 451              $orderby = "ORDER BY $orderby";
 452          }
 453  
 454          $order = $this->parse_order( $this->query_vars['order'] );
 455  
 456          if ( $taxonomies ) {
 457              $this->sql_clauses['where']['taxonomy'] =
 458                  "tt.taxonomy IN ('" . implode( "', '", array_map( 'esc_sql', $taxonomies ) ) . "')";
 459          }
 460  
 461          if ( empty( $args['exclude'] ) ) {
 462              $args['exclude'] = array();
 463          }
 464  
 465          if ( empty( $args['include'] ) ) {
 466              $args['include'] = array();
 467          }
 468  
 469          $exclude      = $args['exclude'];
 470          $exclude_tree = $args['exclude_tree'];
 471          $include      = $args['include'];
 472  
 473          $inclusions = '';
 474          if ( ! empty( $include ) ) {
 475              $exclude      = '';
 476              $exclude_tree = '';
 477              $inclusions   = implode( ',', wp_parse_id_list( $include ) );
 478          }
 479  
 480          if ( ! empty( $inclusions ) ) {
 481              $this->sql_clauses['where']['inclusions'] = 't.term_id IN ( ' . $inclusions . ' )';
 482          }
 483  
 484          $exclusions = array();
 485          if ( ! empty( $exclude_tree ) ) {
 486              $exclude_tree      = wp_parse_id_list( $exclude_tree );
 487              $excluded_children = $exclude_tree;
 488  
 489              foreach ( $exclude_tree as $extrunk ) {
 490                  $excluded_children = array_merge(
 491                      $excluded_children,
 492                      (array) get_terms(
 493                          array(
 494                              'taxonomy'   => reset( $taxonomies ),
 495                              'child_of'   => (int) $extrunk,
 496                              'fields'     => 'ids',
 497                              'hide_empty' => 0,
 498                          )
 499                      )
 500                  );
 501              }
 502  
 503              $exclusions = array_merge( $excluded_children, $exclusions );
 504          }
 505  
 506          if ( ! empty( $exclude ) ) {
 507              $exclusions = array_merge( wp_parse_id_list( $exclude ), $exclusions );
 508          }
 509  
 510          // 'childless' terms are those without an entry in the flattened term hierarchy.
 511          $childless = (bool) $args['childless'];
 512          if ( $childless ) {
 513              foreach ( $taxonomies as $_tax ) {
 514                  $term_hierarchy = _get_term_hierarchy( $_tax );
 515                  $exclusions     = array_merge( array_keys( $term_hierarchy ), $exclusions );
 516              }
 517          }
 518  
 519          if ( ! empty( $exclusions ) ) {
 520              $exclusions = 't.term_id NOT IN (' . implode( ',', array_map( 'intval', $exclusions ) ) . ')';
 521          } else {
 522              $exclusions = '';
 523          }
 524  
 525          /**
 526           * Filters the terms to exclude from the terms query.
 527           *
 528           * @since 2.3.0
 529           *
 530           * @param string   $exclusions `NOT IN` clause of the terms query.
 531           * @param array    $args       An array of terms query arguments.
 532           * @param string[] $taxonomies An array of taxonomy names.
 533           */
 534          $exclusions = apply_filters( 'list_terms_exclusions', $exclusions, $args, $taxonomies );
 535  
 536          if ( ! empty( $exclusions ) ) {
 537              // Strip leading 'AND'. Must do string manipulation here for backward compatibility with filter.
 538              $this->sql_clauses['where']['exclusions'] = preg_replace( '/^\s*AND\s*/', '', $exclusions );
 539          }
 540  
 541          if ( '' === $args['name'] ) {
 542              $args['name'] = array();
 543          } else {
 544              $args['name'] = (array) $args['name'];
 545          }
 546  
 547          if ( ! empty( $args['name'] ) ) {
 548              $names = $args['name'];
 549  
 550              foreach ( $names as &$_name ) {
 551                  // `sanitize_term_field()` returns slashed data.
 552                  $_name = stripslashes( sanitize_term_field( 'name', $_name, 0, reset( $taxonomies ), 'db' ) );
 553              }
 554  
 555              $this->sql_clauses['where']['name'] = "t.name IN ('" . implode( "', '", array_map( 'esc_sql', $names ) ) . "')";
 556          }
 557  
 558          if ( '' === $args['slug'] ) {
 559              $args['slug'] = array();
 560          } else {
 561              $args['slug'] = array_map( 'sanitize_title', (array) $args['slug'] );
 562          }
 563  
 564          if ( ! empty( $args['slug'] ) ) {
 565              $slug = implode( "', '", $args['slug'] );
 566  
 567              $this->sql_clauses['where']['slug'] = "t.slug IN ('" . $slug . "')";
 568          }
 569  
 570          if ( '' === $args['term_taxonomy_id'] ) {
 571              $args['term_taxonomy_id'] = array();
 572          } else {
 573              $args['term_taxonomy_id'] = array_map( 'intval', (array) $args['term_taxonomy_id'] );
 574          }
 575  
 576          if ( ! empty( $args['term_taxonomy_id'] ) ) {
 577              $tt_ids = implode( ',', $args['term_taxonomy_id'] );
 578  
 579              $this->sql_clauses['where']['term_taxonomy_id'] = "tt.term_taxonomy_id IN ({$tt_ids})";
 580          }
 581  
 582          if ( ! empty( $args['name__like'] ) ) {
 583              $this->sql_clauses['where']['name__like'] = $wpdb->prepare(
 584                  't.name LIKE %s',
 585                  '%' . $wpdb->esc_like( $args['name__like'] ) . '%'
 586              );
 587          }
 588  
 589          if ( ! empty( $args['description__like'] ) ) {
 590              $this->sql_clauses['where']['description__like'] = $wpdb->prepare(
 591                  'tt.description LIKE %s',
 592                  '%' . $wpdb->esc_like( $args['description__like'] ) . '%'
 593              );
 594          }
 595  
 596          if ( '' === $args['object_ids'] ) {
 597              $args['object_ids'] = array();
 598          } else {
 599              $args['object_ids'] = array_map( 'intval', (array) $args['object_ids'] );
 600          }
 601  
 602          if ( ! empty( $args['object_ids'] ) ) {
 603              $object_ids = implode( ', ', $args['object_ids'] );
 604  
 605              $this->sql_clauses['where']['object_ids'] = "tr.object_id IN ($object_ids)";
 606          }
 607  
 608          /*
 609           * When querying for object relationships, the 'count > 0' check
 610           * added by 'hide_empty' is superfluous.
 611           */
 612          if ( ! empty( $args['object_ids'] ) ) {
 613              $args['hide_empty'] = false;
 614          }
 615  
 616          if ( '' !== $parent ) {
 617              $parent                               = (int) $parent;
 618              $this->sql_clauses['where']['parent'] = "tt.parent = '$parent'";
 619          }
 620  
 621          $hierarchical = $args['hierarchical'];
 622          if ( 'count' === $args['fields'] ) {
 623              $hierarchical = false;
 624          }
 625          if ( $args['hide_empty'] && ! $hierarchical ) {
 626              $this->sql_clauses['where']['count'] = 'tt.count > 0';
 627          }
 628  
 629          $number = $args['number'];
 630          $offset = $args['offset'];
 631  
 632          // Don't limit the query results when we have to descend the family tree.
 633          if ( $number && ! $hierarchical && ! $child_of && '' === $parent ) {
 634              if ( $offset ) {
 635                  $limits = 'LIMIT ' . $offset . ',' . $number;
 636              } else {
 637                  $limits = 'LIMIT ' . $number;
 638              }
 639          } else {
 640              $limits = '';
 641          }
 642  
 643          if ( ! empty( $args['search'] ) ) {
 644              $this->sql_clauses['where']['search'] = $this->get_search_sql( $args['search'] );
 645          }
 646  
 647          // Meta query support.
 648          $join     = '';
 649          $distinct = '';
 650  
 651          // Reparse meta_query query_vars, in case they were modified in a 'pre_get_terms' callback.
 652          $this->meta_query->parse_query_vars( $this->query_vars );
 653          $mq_sql       = $this->meta_query->get_sql( 'term', 't', 'term_id' );
 654          $meta_clauses = $this->meta_query->get_clauses();
 655  
 656          if ( ! empty( $meta_clauses ) ) {
 657              $join .= $mq_sql['join'];
 658  
 659              // Strip leading 'AND'.
 660              $this->sql_clauses['where']['meta_query'] = preg_replace( '/^\s*AND\s*/', '', $mq_sql['where'] );
 661  
 662              $distinct .= 'DISTINCT';
 663  
 664          }
 665  
 666          $selects = array();
 667          switch ( $args['fields'] ) {
 668              case 'count':
 669                  $orderby = '';
 670                  $order   = '';
 671                  $selects = array( 'COUNT(*)' );
 672                  break;
 673              default:
 674                  $selects = array( 't.term_id' );
 675                  if ( 'all_with_object_id' === $args['fields'] && ! empty( $args['object_ids'] ) ) {
 676                      $selects[] = 'tr.object_id';
 677                  }
 678                  break;
 679          }
 680  
 681          $_fields = $args['fields'];
 682  
 683          /**
 684           * Filters the fields to select in the terms query.
 685           *
 686           * Field lists modified using this filter will only modify the term fields returned
 687           * by the function when the `$fields` parameter set to 'count' or 'all'. In all other
 688           * cases, the term fields in the results array will be determined by the `$fields`
 689           * parameter alone.
 690           *
 691           * Use of this filter can result in unpredictable behavior, and is not recommended.
 692           *
 693           * @since 2.8.0
 694           *
 695           * @param string[] $selects    An array of fields to select for the terms query.
 696           * @param array    $args       An array of term query arguments.
 697           * @param string[] $taxonomies An array of taxonomy names.
 698           */
 699          $fields = implode( ', ', apply_filters( 'get_terms_fields', $selects, $args, $taxonomies ) );
 700  
 701          $join .= " INNER JOIN $wpdb->term_taxonomy AS tt ON t.term_id = tt.term_id";
 702  
 703          if ( ! empty( $this->query_vars['object_ids'] ) ) {
 704              $join    .= " INNER JOIN {$wpdb->term_relationships} AS tr ON tr.term_taxonomy_id = tt.term_taxonomy_id";
 705              $distinct = 'DISTINCT';
 706          }
 707  
 708          $where = implode( ' AND ', $this->sql_clauses['where'] );
 709  
 710          $pieces = array( 'fields', 'join', 'where', 'distinct', 'orderby', 'order', 'limits' );
 711  
 712          /**
 713           * Filters the terms query SQL clauses.
 714           *
 715           * @since 3.1.0
 716           *
 717           * @param string[] $clauses {
 718           *     Associative array of the clauses for the query.
 719           *
 720           *     @type string $fields   The SELECT clause of the query.
 721           *     @type string $join     The JOIN clause of the query.
 722           *     @type string $where    The WHERE clause of the query.
 723           *     @type string $distinct The DISTINCT clause of the query.
 724           *     @type string $orderby  The ORDER BY clause of the query.
 725           *     @type string $order    The ORDER clause of the query.
 726           *     @type string $limits   The LIMIT clause of the query.
 727           * }
 728           * @param string[] $taxonomies An array of taxonomy names.
 729           * @param array    $args       An array of term query arguments.
 730           */
 731          $clauses = apply_filters( 'terms_clauses', compact( $pieces ), $taxonomies, $args );
 732  
 733          $fields   = isset( $clauses['fields'] ) ? $clauses['fields'] : '';
 734          $join     = isset( $clauses['join'] ) ? $clauses['join'] : '';
 735          $where    = isset( $clauses['where'] ) ? $clauses['where'] : '';
 736          $distinct = isset( $clauses['distinct'] ) ? $clauses['distinct'] : '';
 737          $orderby  = isset( $clauses['orderby'] ) ? $clauses['orderby'] : '';
 738          $order    = isset( $clauses['order'] ) ? $clauses['order'] : '';
 739          $limits   = isset( $clauses['limits'] ) ? $clauses['limits'] : '';
 740  
 741          $fields_is_filtered = implode( ', ', $selects ) !== $fields;
 742  
 743          if ( $where ) {
 744              $where = "WHERE $where";
 745          }
 746  
 747          $this->sql_clauses['select']  = "SELECT $distinct $fields";
 748          $this->sql_clauses['from']    = "FROM $wpdb->terms AS t $join";
 749          $this->sql_clauses['orderby'] = $orderby ? "$orderby $order" : '';
 750          $this->sql_clauses['limits']  = $limits;
 751  
 752          // Beginning of the string is on a new line to prevent leading whitespace. See https://core.trac.wordpress.org/ticket/56841.
 753          $this->request =
 754              "{$this->sql_clauses['select']}
 755               {$this->sql_clauses['from']}
 756               {$where}
 757               {$this->sql_clauses['orderby']}
 758               {$this->sql_clauses['limits']}";
 759  
 760          $this->terms = null;
 761  
 762          /**
 763           * Filters the terms array before the query takes place.
 764           *
 765           * Return a non-null value to bypass WordPress' default term queries.
 766           *
 767           * @since 5.3.0
 768           *
 769           * @param array|null    $terms Return an array of term data to short-circuit WP's term query,
 770           *                             or null to allow WP queries to run normally.
 771           * @param WP_Term_Query $query The WP_Term_Query instance, passed by reference.
 772           */
 773          $this->terms = apply_filters_ref_array( 'terms_pre_query', array( $this->terms, &$this ) );
 774  
 775          if ( null !== $this->terms ) {
 776              return $this->terms;
 777          }
 778  
 779          if ( $args['cache_results'] ) {
 780              $cache_key = $this->generate_cache_key( $args, $this->request );
 781              $cache     = wp_cache_get( $cache_key, 'term-queries' );
 782  
 783              if ( false !== $cache ) {
 784                  if ( 'ids' === $_fields ) {
 785                      $cache = array_map( 'intval', $cache );
 786                  } elseif ( 'count' !== $_fields ) {
 787                      if ( ( 'all_with_object_id' === $_fields && ! empty( $args['object_ids'] ) )
 788                      || ( 'all' === $_fields && $args['pad_counts'] || $fields_is_filtered )
 789                      ) {
 790                          $term_ids = wp_list_pluck( $cache, 'term_id' );
 791                      } else {
 792                          $term_ids = array_map( 'intval', $cache );
 793                      }
 794  
 795                      _prime_term_caches( $term_ids, $args['update_term_meta_cache'] );
 796  
 797                      $term_objects = $this->populate_terms( $cache );
 798                      $cache        = $this->format_terms( $term_objects, $_fields );
 799                  }
 800  
 801                  $this->terms = $cache;
 802                  return $this->terms;
 803              }
 804          }
 805  
 806          if ( 'count' === $_fields ) {
 807              $count = $wpdb->get_var( $this->request ); // phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared
 808              if ( $args['cache_results'] ) {
 809                  wp_cache_set( $cache_key, $count, 'term-queries' );
 810              }
 811              return $count;
 812          }
 813  
 814          $terms = $wpdb->get_results( $this->request ); // phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared
 815  
 816          if ( empty( $terms ) ) {
 817              if ( $args['cache_results'] ) {
 818                  wp_cache_add( $cache_key, array(), 'term-queries' );
 819              }
 820              return array();
 821          }
 822  
 823          $term_ids = wp_list_pluck( $terms, 'term_id' );
 824          _prime_term_caches( $term_ids, false );
 825          $term_objects = $this->populate_terms( $terms );
 826  
 827          if ( $child_of ) {
 828              foreach ( $taxonomies as $_tax ) {
 829                  $children = _get_term_hierarchy( $_tax );
 830                  if ( ! empty( $children ) ) {
 831                      $term_objects = _get_term_children( $child_of, $term_objects, $_tax );
 832                  }
 833              }
 834          }
 835  
 836          // Update term counts to include children.
 837          if ( $args['pad_counts'] && 'all' === $_fields ) {
 838              foreach ( $taxonomies as $_tax ) {
 839                  _pad_term_counts( $term_objects, $_tax );
 840              }
 841          }
 842  
 843          // Make sure we show empty categories that have children.
 844          if ( $hierarchical && $args['hide_empty'] && is_array( $term_objects ) ) {
 845              foreach ( $term_objects as $k => $term ) {
 846                  if ( ! $term->count ) {
 847                      $children = get_term_children( $term->term_id, $term->taxonomy );
 848  
 849                      if ( is_array( $children ) ) {
 850                          foreach ( $children as $child_id ) {
 851                              $child = get_term( $child_id, $term->taxonomy );
 852                              if ( $child->count ) {
 853                                  continue 2;
 854                              }
 855                          }
 856                      }
 857  
 858                      // It really is empty.
 859                      unset( $term_objects[ $k ] );
 860                  }
 861              }
 862          }
 863  
 864          // Hierarchical queries are not limited, so 'offset' and 'number' must be handled now.
 865          if ( $hierarchical && $number && is_array( $term_objects ) ) {
 866              if ( $offset >= count( $term_objects ) ) {
 867                  $term_objects = array();
 868              } else {
 869                  $term_objects = array_slice( $term_objects, $offset, $number, true );
 870              }
 871          }
 872  
 873          // Prime termmeta cache.
 874          if ( $args['update_term_meta_cache'] ) {
 875              $term_ids = wp_list_pluck( $term_objects, 'term_id' );
 876              wp_lazyload_term_meta( $term_ids );
 877          }
 878  
 879          if ( 'all_with_object_id' === $_fields && ! empty( $args['object_ids'] ) ) {
 880              $term_cache = array();
 881              foreach ( $term_objects as $term ) {
 882                  $object            = new stdClass();
 883                  $object->term_id   = $term->term_id;
 884                  $object->object_id = $term->object_id;
 885                  $term_cache[]      = $object;
 886              }
 887          } elseif ( 'all' === $_fields && $args['pad_counts'] ) {
 888              $term_cache = array();
 889              foreach ( $term_objects as $term ) {
 890                  $object          = new stdClass();
 891                  $object->term_id = $term->term_id;
 892                  $object->count   = $term->count;
 893                  $term_cache[]    = $object;
 894              }
 895          } elseif ( $fields_is_filtered ) {
 896              $term_cache = $term_objects;
 897          } else {
 898              $term_cache = wp_list_pluck( $term_objects, 'term_id' );
 899          }
 900  
 901          if ( $args['cache_results'] ) {
 902              wp_cache_add( $cache_key, $term_cache, 'term-queries' );
 903          }
 904  
 905          $this->terms = $this->format_terms( $term_objects, $_fields );
 906  
 907          return $this->terms;
 908      }
 909  
 910      /**
 911       * Parse and sanitize 'orderby' keys passed to the term query.
 912       *
 913       * @since 4.6.0
 914       *
 915       * @param string $orderby_raw Alias for the field to order by.
 916       * @return string|false Value to used in the ORDER clause. False otherwise.
 917       */
 918  	protected function parse_orderby( $orderby_raw ) {
 919          $_orderby           = strtolower( $orderby_raw );
 920          $maybe_orderby_meta = false;
 921  
 922          if ( in_array( $_orderby, array( 'term_id', 'name', 'slug', 'term_group' ), true ) ) {
 923              $orderby = "t.$_orderby";
 924          } elseif ( in_array( $_orderby, array( 'count', 'parent', 'taxonomy', 'term_taxonomy_id', 'description' ), true ) ) {
 925              $orderby = "tt.$_orderby";
 926          } elseif ( 'term_order' === $_orderby ) {
 927              $orderby = 'tr.term_order';
 928          } elseif ( 'include' === $_orderby && ! empty( $this->query_vars['include'] ) ) {
 929              $include = implode( ',', wp_parse_id_list( $this->query_vars['include'] ) );
 930              $orderby = "FIELD( t.term_id, $include )";
 931          } elseif ( 'slug__in' === $_orderby && ! empty( $this->query_vars['slug'] ) && is_array( $this->query_vars['slug'] ) ) {
 932              $slugs   = implode( "', '", array_map( 'sanitize_title_for_query', $this->query_vars['slug'] ) );
 933              $orderby = "FIELD( t.slug, '" . $slugs . "')";
 934          } elseif ( 'none' === $_orderby ) {
 935              $orderby = '';
 936          } elseif ( empty( $_orderby ) || 'id' === $_orderby || 'term_id' === $_orderby ) {
 937              $orderby = 't.term_id';
 938          } else {
 939              $orderby = 't.name';
 940  
 941              // This may be a value of orderby related to meta.
 942              $maybe_orderby_meta = true;
 943          }
 944  
 945          /**
 946           * Filters the ORDERBY clause of the terms query.
 947           *
 948           * @since 2.8.0
 949           *
 950           * @param string   $orderby    `ORDERBY` clause of the terms query.
 951           * @param array    $args       An array of term query arguments.
 952           * @param string[] $taxonomies An array of taxonomy names.
 953           */
 954          $orderby = apply_filters( 'get_terms_orderby', $orderby, $this->query_vars, $this->query_vars['taxonomy'] );
 955  
 956          // Run after the 'get_terms_orderby' filter for backward compatibility.
 957          if ( $maybe_orderby_meta ) {
 958              $maybe_orderby_meta = $this->parse_orderby_meta( $_orderby );
 959              if ( $maybe_orderby_meta ) {
 960                  $orderby = $maybe_orderby_meta;
 961              }
 962          }
 963  
 964          return $orderby;
 965      }
 966  
 967      /**
 968       * Format response depending on field requested.
 969       *
 970       * @since 6.0.0
 971       *
 972       * @param WP_Term[] $term_objects Array of term objects.
 973       * @param string    $_fields      Field to format.
 974       *
 975       * @return WP_Term[]|int[]|string[] Array of terms / strings / ints depending on field requested.
 976       */
 977  	protected function format_terms( $term_objects, $_fields ) {
 978          $_terms = array();
 979          if ( 'id=>parent' === $_fields ) {
 980              foreach ( $term_objects as $term ) {
 981                  $_terms[ $term->term_id ] = $term->parent;
 982              }
 983          } elseif ( 'ids' === $_fields ) {
 984              foreach ( $term_objects as $term ) {
 985                  $_terms[] = (int) $term->term_id;
 986              }
 987          } elseif ( 'tt_ids' === $_fields ) {
 988              foreach ( $term_objects as $term ) {
 989                  $_terms[] = (int) $term->term_taxonomy_id;
 990              }
 991          } elseif ( 'names' === $_fields ) {
 992              foreach ( $term_objects as $term ) {
 993                  $_terms[] = $term->name;
 994              }
 995          } elseif ( 'slugs' === $_fields ) {
 996              foreach ( $term_objects as $term ) {
 997                  $_terms[] = $term->slug;
 998              }
 999          } elseif ( 'id=>name' === $_fields ) {
1000              foreach ( $term_objects as $term ) {
1001                  $_terms[ $term->term_id ] = $term->name;
1002              }
1003          } elseif ( 'id=>slug' === $_fields ) {
1004              foreach ( $term_objects as $term ) {
1005                  $_terms[ $term->term_id ] = $term->slug;
1006              }
1007          } elseif ( 'all' === $_fields || 'all_with_object_id' === $_fields ) {
1008              $_terms = $term_objects;
1009          }
1010  
1011          return $_terms;
1012      }
1013  
1014      /**
1015       * Generate the ORDER BY clause for an 'orderby' param that is potentially related to a meta query.
1016       *
1017       * @since 4.6.0
1018       *
1019       * @param string $orderby_raw Raw 'orderby' value passed to WP_Term_Query.
1020       * @return string ORDER BY clause.
1021       */
1022  	protected function parse_orderby_meta( $orderby_raw ) {
1023          $orderby = '';
1024  
1025          // Tell the meta query to generate its SQL, so we have access to table aliases.
1026          $this->meta_query->get_sql( 'term', 't', 'term_id' );
1027          $meta_clauses = $this->meta_query->get_clauses();
1028          if ( ! $meta_clauses || ! $orderby_raw ) {
1029              return $orderby;
1030          }
1031  
1032          $allowed_keys       = array();
1033          $primary_meta_key   = null;
1034          $primary_meta_query = reset( $meta_clauses );
1035          if ( ! empty( $primary_meta_query['key'] ) ) {
1036              $primary_meta_key = $primary_meta_query['key'];
1037              $allowed_keys[]   = $primary_meta_key;
1038          }
1039          $allowed_keys[] = 'meta_value';
1040          $allowed_keys[] = 'meta_value_num';
1041          $allowed_keys   = array_merge( $allowed_keys, array_keys( $meta_clauses ) );
1042  
1043          if ( ! in_array( $orderby_raw, $allowed_keys, true ) ) {
1044              return $orderby;
1045          }
1046  
1047          switch ( $orderby_raw ) {
1048              case $primary_meta_key:
1049              case 'meta_value':
1050                  if ( ! empty( $primary_meta_query['type'] ) ) {
1051                      $orderby = "CAST({$primary_meta_query['alias']}.meta_value AS {$primary_meta_query['cast']})";
1052                  } else {
1053                      $orderby = "{$primary_meta_query['alias']}.meta_value";
1054                  }
1055                  break;
1056  
1057              case 'meta_value_num':
1058                  $orderby = "{$primary_meta_query['alias']}.meta_value+0";
1059                  break;
1060  
1061              default:
1062                  if ( array_key_exists( $orderby_raw, $meta_clauses ) ) {
1063                      // $orderby corresponds to a meta_query clause.
1064                      $meta_clause = $meta_clauses[ $orderby_raw ];
1065                      $orderby     = "CAST({$meta_clause['alias']}.meta_value AS {$meta_clause['cast']})";
1066                  }
1067                  break;
1068          }
1069  
1070          return $orderby;
1071      }
1072  
1073      /**
1074       * Parse an 'order' query variable and cast it to ASC or DESC as necessary.
1075       *
1076       * @since 4.6.0
1077       *
1078       * @param string $order The 'order' query variable.
1079       * @return string The sanitized 'order' query variable.
1080       */
1081  	protected function parse_order( $order ) {
1082          if ( ! is_string( $order ) || empty( $order ) ) {
1083              return 'DESC';
1084          }
1085  
1086          if ( 'ASC' === strtoupper( $order ) ) {
1087              return 'ASC';
1088          } else {
1089              return 'DESC';
1090          }
1091      }
1092  
1093      /**
1094       * Used internally to generate a SQL string related to the 'search' parameter.
1095       *
1096       * @since 4.6.0
1097       *
1098       * @global wpdb $wpdb WordPress database abstraction object.
1099       *
1100       * @param string $search Search string.
1101       * @return string Search SQL.
1102       */
1103  	protected function get_search_sql( $search ) {
1104          global $wpdb;
1105  
1106          $like = '%' . $wpdb->esc_like( $search ) . '%';
1107  
1108          return $wpdb->prepare( '((t.name LIKE %s) OR (t.slug LIKE %s))', $like, $like );
1109      }
1110  
1111      /**
1112       * Creates an array of term objects from an array of term IDs.
1113       *
1114       * Also discards invalid term objects.
1115       *
1116       * @since 4.9.8
1117       *
1118       * @param Object[]|int[] $terms List of objects or term ids.
1119       * @return WP_Term[] Array of `WP_Term` objects.
1120       */
1121  	protected function populate_terms( $terms ) {
1122          $term_objects = array();
1123          if ( ! is_array( $terms ) ) {
1124              return $term_objects;
1125          }
1126  
1127          foreach ( $terms as $key => $term_data ) {
1128              if ( is_object( $term_data ) && property_exists( $term_data, 'term_id' ) ) {
1129                  $term = get_term( $term_data->term_id );
1130                  if ( property_exists( $term_data, 'object_id' ) ) {
1131                      $term->object_id = (int) $term_data->object_id;
1132                  }
1133                  if ( property_exists( $term_data, 'count' ) ) {
1134                      $term->count = (int) $term_data->count;
1135                  }
1136              } else {
1137                  $term = get_term( $term_data );
1138              }
1139  
1140              if ( $term instanceof WP_Term ) {
1141                  $term_objects[ $key ] = $term;
1142              }
1143          }
1144  
1145          return $term_objects;
1146      }
1147  
1148      /**
1149       * Generate cache key.
1150       *
1151       * @since 6.2.0
1152       *
1153       * @global wpdb $wpdb WordPress database abstraction object.
1154       *
1155       * @param array  $args WP_Term_Query arguments.
1156       * @param string $sql  SQL statement.
1157       *
1158       * @return string Cache key.
1159       */
1160  	protected function generate_cache_key( array $args, $sql ) {
1161          global $wpdb;
1162          // $args can be anything. Only use the args defined in defaults to compute the key.
1163          $cache_args = wp_array_slice_assoc( $args, array_keys( $this->query_var_defaults ) );
1164  
1165          unset( $cache_args['cache_results'], $cache_args['update_term_meta_cache'] );
1166  
1167          if ( 'count' !== $args['fields'] && 'all_with_object_id' !== $args['fields'] ) {
1168              $cache_args['fields'] = 'all';
1169          }
1170  
1171          // Replace wpdb placeholder in the SQL statement used by the cache key.
1172          $sql = $wpdb->remove_placeholder_escape( $sql );
1173  
1174          $key          = md5( serialize( $cache_args ) . $sql );
1175          $last_changed = wp_cache_get_last_changed( 'terms' );
1176          return "get_terms:$key:$last_changed";
1177      }
1178  }


Generated : Thu Nov 21 08:20:01 2024 Cross-referenced by PHPXref