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


Generated: Mon Jul 26 01:00:04 2021 Cross-referenced by PHPXref 0.7.1