class-wp-term-query.php 35 KB

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