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