[ Index ]

PHP Cross Reference of WordPress

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


Generated: Mon Nov 18 01:00:04 2019 Cross-referenced by PHPXref 0.7.1