You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 
 

969 lines
32 KiB

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