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


Generated : Thu Sep 24 08:20:02 2020 Cross-referenced by PHPXref