class-wp-term-query.php 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996
  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; only works
  117. * when the `$fields` parameter is 'object_ids' ), '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 array $taxonomies An array of taxonomies.
  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. }
  302. if ( ! $has_hierarchical_tax ) {
  303. $args['hierarchical'] = false;
  304. $args['pad_counts'] = false;
  305. }
  306. // 'parent' overrides 'child_of'.
  307. if ( 0 < intval( $args['parent'] ) ) {
  308. $args['child_of'] = false;
  309. }
  310. if ( 'all' == $args['get'] ) {
  311. $args['childless'] = false;
  312. $args['child_of'] = 0;
  313. $args['hide_empty'] = 0;
  314. $args['hierarchical'] = false;
  315. $args['pad_counts'] = false;
  316. }
  317. /**
  318. * Filters the terms query arguments.
  319. *
  320. * @since 3.1.0
  321. *
  322. * @param array $args An array of get_terms() arguments.
  323. * @param array $taxonomies An array of taxonomies.
  324. */
  325. $args = apply_filters( 'get_terms_args', $args, $taxonomies );
  326. // Avoid the query if the queried parent/child_of term has no descendants.
  327. $child_of = $args['child_of'];
  328. $parent = $args['parent'];
  329. if ( $child_of ) {
  330. $_parent = $child_of;
  331. } elseif ( $parent ) {
  332. $_parent = $parent;
  333. } else {
  334. $_parent = false;
  335. }
  336. if ( $_parent ) {
  337. $in_hierarchy = false;
  338. foreach ( $taxonomies as $_tax ) {
  339. $hierarchy = _get_term_hierarchy( $_tax );
  340. if ( isset( $hierarchy[ $_parent ] ) ) {
  341. $in_hierarchy = true;
  342. }
  343. }
  344. if ( ! $in_hierarchy ) {
  345. return array();
  346. }
  347. }
  348. // 'term_order' is a legal sort order only when joining the relationship table.
  349. $_orderby = $this->query_vars['orderby'];
  350. if ( 'term_order' === $_orderby && empty( $this->query_vars['object_ids'] ) ) {
  351. $_orderby = 'term_id';
  352. }
  353. $orderby = $this->parse_orderby( $_orderby );
  354. if ( $orderby ) {
  355. $orderby = "ORDER BY $orderby";
  356. }
  357. $order = $this->parse_order( $this->query_vars['order'] );
  358. if ( $taxonomies ) {
  359. $this->sql_clauses['where']['taxonomy'] = "tt.taxonomy IN ('" . implode( "', '", array_map( 'esc_sql', $taxonomies ) ) . "')";
  360. }
  361. $exclude = $args['exclude'];
  362. $exclude_tree = $args['exclude_tree'];
  363. $include = $args['include'];
  364. $inclusions = '';
  365. if ( ! empty( $include ) ) {
  366. $exclude = '';
  367. $exclude_tree = '';
  368. $inclusions = implode( ',', wp_parse_id_list( $include ) );
  369. }
  370. if ( ! empty( $inclusions ) ) {
  371. $this->sql_clauses['where']['inclusions'] = 't.term_id IN ( ' . $inclusions . ' )';
  372. }
  373. $exclusions = array();
  374. if ( ! empty( $exclude_tree ) ) {
  375. $exclude_tree = wp_parse_id_list( $exclude_tree );
  376. $excluded_children = $exclude_tree;
  377. foreach ( $exclude_tree as $extrunk ) {
  378. $excluded_children = array_merge(
  379. $excluded_children,
  380. (array) get_terms( reset( $taxonomies ), array(
  381. 'child_of' => intval( $extrunk ),
  382. 'fields' => 'ids',
  383. 'hide_empty' => 0
  384. ) )
  385. );
  386. }
  387. $exclusions = array_merge( $excluded_children, $exclusions );
  388. }
  389. if ( ! empty( $exclude ) ) {
  390. $exclusions = array_merge( wp_parse_id_list( $exclude ), $exclusions );
  391. }
  392. // 'childless' terms are those without an entry in the flattened term hierarchy.
  393. $childless = (bool) $args['childless'];
  394. if ( $childless ) {
  395. foreach ( $taxonomies as $_tax ) {
  396. $term_hierarchy = _get_term_hierarchy( $_tax );
  397. $exclusions = array_merge( array_keys( $term_hierarchy ), $exclusions );
  398. }
  399. }
  400. if ( ! empty( $exclusions ) ) {
  401. $exclusions = 't.term_id NOT IN (' . implode( ',', array_map( 'intval', $exclusions ) ) . ')';
  402. } else {
  403. $exclusions = '';
  404. }
  405. /**
  406. * Filters the terms to exclude from the terms query.
  407. *
  408. * @since 2.3.0
  409. *
  410. * @param string $exclusions `NOT IN` clause of the terms query.
  411. * @param array $args An array of terms query arguments.
  412. * @param array $taxonomies An array of taxonomies.
  413. */
  414. $exclusions = apply_filters( 'list_terms_exclusions', $exclusions, $args, $taxonomies );
  415. if ( ! empty( $exclusions ) ) {
  416. // Must do string manipulation here for backward compatibility with filter.
  417. $this->sql_clauses['where']['exclusions'] = preg_replace( '/^\s*AND\s*/', '', $exclusions );
  418. }
  419. if (
  420. ( ! empty( $args['name'] ) ) ||
  421. ( is_string( $args['name'] ) && 0 !== strlen( $args['name'] ) )
  422. ) {
  423. $names = (array) $args['name'];
  424. foreach ( $names as &$_name ) {
  425. // `sanitize_term_field()` returns slashed data.
  426. $_name = stripslashes( sanitize_term_field( 'name', $_name, 0, reset( $taxonomies ), 'db' ) );
  427. }
  428. $this->sql_clauses['where']['name'] = "t.name IN ('" . implode( "', '", array_map( 'esc_sql', $names ) ) . "')";
  429. }
  430. if (
  431. ( ! empty( $args['slug'] ) ) ||
  432. ( is_string( $args['slug'] ) && 0 !== strlen( $args['slug'] ) )
  433. ) {
  434. if ( is_array( $args['slug'] ) ) {
  435. $slug = array_map( 'sanitize_title', $args['slug'] );
  436. $this->sql_clauses['where']['slug'] = "t.slug IN ('" . implode( "', '", $slug ) . "')";
  437. } else {
  438. $slug = sanitize_title( $args['slug'] );
  439. $this->sql_clauses['where']['slug'] = "t.slug = '$slug'";
  440. }
  441. }
  442. if ( ! empty( $args['term_taxonomy_id'] ) ) {
  443. if ( is_array( $args['term_taxonomy_id'] ) ) {
  444. $tt_ids = implode( ',', array_map( 'intval', $args['term_taxonomy_id'] ) );
  445. $this->sql_clauses['where']['term_taxonomy_id'] = "tt.term_taxonomy_id IN ({$tt_ids})";
  446. } else {
  447. $this->sql_clauses['where']['term_taxonomy_id'] = $wpdb->prepare( "tt.term_taxonomy_id = %d", $args['term_taxonomy_id'] );
  448. }
  449. }
  450. if ( ! empty( $args['name__like'] ) ) {
  451. $this->sql_clauses['where']['name__like'] = $wpdb->prepare( "t.name LIKE %s", '%' . $wpdb->esc_like( $args['name__like'] ) . '%' );
  452. }
  453. if ( ! empty( $args['description__like'] ) ) {
  454. $this->sql_clauses['where']['description__like'] = $wpdb->prepare( "tt.description LIKE %s", '%' . $wpdb->esc_like( $args['description__like'] ) . '%' );
  455. }
  456. if ( ! empty( $args['object_ids'] ) ) {
  457. $object_ids = $args['object_ids'];
  458. if ( ! is_array( $object_ids ) ) {
  459. $object_ids = array( $object_ids );
  460. }
  461. $object_ids = implode( ', ', array_map( 'intval', $object_ids ) );
  462. $this->sql_clauses['where']['object_ids'] = "tr.object_id IN ($object_ids)";
  463. }
  464. /*
  465. * When querying for object relationships, the 'count > 0' check
  466. * added by 'hide_empty' is superfluous.
  467. */
  468. if ( ! empty( $args['object_ids'] ) ) {
  469. $args['hide_empty'] = false;
  470. }
  471. if ( '' !== $parent ) {
  472. $parent = (int) $parent;
  473. $this->sql_clauses['where']['parent'] = "tt.parent = '$parent'";
  474. }
  475. $hierarchical = $args['hierarchical'];
  476. if ( 'count' == $args['fields'] ) {
  477. $hierarchical = false;
  478. }
  479. if ( $args['hide_empty'] && !$hierarchical ) {
  480. $this->sql_clauses['where']['count'] = 'tt.count > 0';
  481. }
  482. $number = $args['number'];
  483. $offset = $args['offset'];
  484. // Don't limit the query results when we have to descend the family tree.
  485. if ( $number && ! $hierarchical && ! $child_of && '' === $parent ) {
  486. if ( $offset ) {
  487. $limits = 'LIMIT ' . $offset . ',' . $number;
  488. } else {
  489. $limits = 'LIMIT ' . $number;
  490. }
  491. } else {
  492. $limits = '';
  493. }
  494. if ( ! empty( $args['search'] ) ) {
  495. $this->sql_clauses['where']['search'] = $this->get_search_sql( $args['search'] );
  496. }
  497. // Meta query support.
  498. $join = '';
  499. $distinct = '';
  500. // Reparse meta_query query_vars, in case they were modified in a 'pre_get_terms' callback.
  501. $this->meta_query->parse_query_vars( $this->query_vars );
  502. $mq_sql = $this->meta_query->get_sql( 'term', 't', 'term_id' );
  503. $meta_clauses = $this->meta_query->get_clauses();
  504. if ( ! empty( $meta_clauses ) ) {
  505. $join .= $mq_sql['join'];
  506. $this->sql_clauses['where']['meta_query'] = preg_replace( '/^\s*AND\s*/', '', $mq_sql['where'] );
  507. $distinct .= "DISTINCT";
  508. }
  509. $selects = array();
  510. switch ( $args['fields'] ) {
  511. case 'all':
  512. case 'all_with_object_id' :
  513. case 'tt_ids' :
  514. case 'slugs' :
  515. $selects = array( 't.*', 'tt.*' );
  516. if ( 'all_with_object_id' === $args['fields'] && ! empty( $args['object_ids'] ) ) {
  517. $selects[] = 'tr.object_id';
  518. }
  519. break;
  520. case 'ids':
  521. case 'id=>parent':
  522. $selects = array( 't.term_id', 'tt.parent', 'tt.count', 'tt.taxonomy' );
  523. break;
  524. case 'names':
  525. $selects = array( 't.term_id', 'tt.parent', 'tt.count', 't.name', 'tt.taxonomy' );
  526. break;
  527. case 'count':
  528. $orderby = '';
  529. $order = '';
  530. $selects = array( 'COUNT(*)' );
  531. break;
  532. case 'id=>name':
  533. $selects = array( 't.term_id', 't.name', 'tt.count', 'tt.taxonomy' );
  534. break;
  535. case 'id=>slug':
  536. $selects = array( 't.term_id', 't.slug', 'tt.count', 'tt.taxonomy' );
  537. break;
  538. }
  539. $_fields = $args['fields'];
  540. /**
  541. * Filters the fields to select in the terms query.
  542. *
  543. * Field lists modified using this filter will only modify the term fields returned
  544. * by the function when the `$fields` parameter set to 'count' or 'all'. In all other
  545. * cases, the term fields in the results array will be determined by the `$fields`
  546. * parameter alone.
  547. *
  548. * Use of this filter can result in unpredictable behavior, and is not recommended.
  549. *
  550. * @since 2.8.0
  551. *
  552. * @param array $selects An array of fields to select for the terms query.
  553. * @param array $args An array of term query arguments.
  554. * @param array $taxonomies An array of taxonomies.
  555. */
  556. $fields = implode( ', ', apply_filters( 'get_terms_fields', $selects, $args, $taxonomies ) );
  557. $join .= " INNER JOIN $wpdb->term_taxonomy AS tt ON t.term_id = tt.term_id";
  558. if ( ! empty( $this->query_vars['object_ids'] ) ) {
  559. $join .= " INNER JOIN {$wpdb->term_relationships} AS tr ON tr.term_taxonomy_id = tt.term_taxonomy_id";
  560. }
  561. $where = implode( ' AND ', $this->sql_clauses['where'] );
  562. /**
  563. * Filters the terms query SQL clauses.
  564. *
  565. * @since 3.1.0
  566. *
  567. * @param array $pieces Terms query SQL clauses.
  568. * @param array $taxonomies An array of taxonomies.
  569. * @param array $args An array of terms query arguments.
  570. */
  571. $clauses = apply_filters( 'terms_clauses', compact( 'fields', 'join', 'where', 'distinct', 'orderby', 'order', 'limits' ), $taxonomies, $args );
  572. $fields = isset( $clauses[ 'fields' ] ) ? $clauses[ 'fields' ] : '';
  573. $join = isset( $clauses[ 'join' ] ) ? $clauses[ 'join' ] : '';
  574. $where = isset( $clauses[ 'where' ] ) ? $clauses[ 'where' ] : '';
  575. $distinct = isset( $clauses[ 'distinct' ] ) ? $clauses[ 'distinct' ] : '';
  576. $orderby = isset( $clauses[ 'orderby' ] ) ? $clauses[ 'orderby' ] : '';
  577. $order = isset( $clauses[ 'order' ] ) ? $clauses[ 'order' ] : '';
  578. $limits = isset( $clauses[ 'limits' ] ) ? $clauses[ 'limits' ] : '';
  579. if ( $where ) {
  580. $where = "WHERE $where";
  581. }
  582. $this->sql_clauses['select'] = "SELECT $distinct $fields";
  583. $this->sql_clauses['from'] = "FROM $wpdb->terms AS t $join";
  584. $this->sql_clauses['orderby'] = $orderby ? "$orderby $order" : '';
  585. $this->sql_clauses['limits'] = $limits;
  586. $this->request = "{$this->sql_clauses['select']} {$this->sql_clauses['from']} {$where} {$this->sql_clauses['orderby']} {$this->sql_clauses['limits']}";
  587. // $args can be anything. Only use the args defined in defaults to compute the key.
  588. $key = md5( serialize( wp_array_slice_assoc( $args, array_keys( $this->query_var_defaults ) ) ) . serialize( $taxonomies ) . $this->request );
  589. $last_changed = wp_cache_get_last_changed( 'terms' );
  590. $cache_key = "get_terms:$key:$last_changed";
  591. $cache = wp_cache_get( $cache_key, 'terms' );
  592. if ( false !== $cache ) {
  593. if ( 'all' === $_fields || 'all_with_object_id' === $_fields ) {
  594. $cache = $this->populate_terms( $cache );
  595. }
  596. $this->terms = $cache;
  597. return $this->terms;
  598. }
  599. if ( 'count' == $_fields ) {
  600. $count = $wpdb->get_var( $this->request );
  601. wp_cache_set( $cache_key, $count, 'terms' );
  602. return $count;
  603. }
  604. $terms = $wpdb->get_results( $this->request );
  605. if ( 'all' == $_fields || 'all_with_object_id' === $_fields ) {
  606. update_term_cache( $terms );
  607. }
  608. // Prime termmeta cache.
  609. if ( $args['update_term_meta_cache'] ) {
  610. $term_ids = wp_list_pluck( $terms, 'term_id' );
  611. update_termmeta_cache( $term_ids );
  612. }
  613. if ( empty( $terms ) ) {
  614. wp_cache_add( $cache_key, array(), 'terms', DAY_IN_SECONDS );
  615. return array();
  616. }
  617. if ( $child_of ) {
  618. foreach ( $taxonomies as $_tax ) {
  619. $children = _get_term_hierarchy( $_tax );
  620. if ( ! empty( $children ) ) {
  621. $terms = _get_term_children( $child_of, $terms, $_tax );
  622. }
  623. }
  624. }
  625. // Update term counts to include children.
  626. if ( $args['pad_counts'] && 'all' == $_fields ) {
  627. foreach ( $taxonomies as $_tax ) {
  628. _pad_term_counts( $terms, $_tax );
  629. }
  630. }
  631. // Make sure we show empty categories that have children.
  632. if ( $hierarchical && $args['hide_empty'] && is_array( $terms ) ) {
  633. foreach ( $terms as $k => $term ) {
  634. if ( ! $term->count ) {
  635. $children = get_term_children( $term->term_id, $term->taxonomy );
  636. if ( is_array( $children ) ) {
  637. foreach ( $children as $child_id ) {
  638. $child = get_term( $child_id, $term->taxonomy );
  639. if ( $child->count ) {
  640. continue 2;
  641. }
  642. }
  643. }
  644. // It really is empty.
  645. unset( $terms[ $k ] );
  646. }
  647. }
  648. }
  649. /*
  650. * When querying for terms connected to objects, we may get
  651. * duplicate results. The duplicates should be preserved if
  652. * `$fields` is 'all_with_object_id', but should otherwise be
  653. * removed.
  654. */
  655. if ( ! empty( $args['object_ids'] ) && 'all_with_object_id' != $_fields ) {
  656. $_tt_ids = $_terms = array();
  657. foreach ( $terms as $term ) {
  658. if ( isset( $_tt_ids[ $term->term_id ] ) ) {
  659. continue;
  660. }
  661. $_tt_ids[ $term->term_id ] = 1;
  662. $_terms[] = $term;
  663. }
  664. $terms = $_terms;
  665. }
  666. $_terms = array();
  667. if ( 'id=>parent' == $_fields ) {
  668. foreach ( $terms as $term ) {
  669. $_terms[ $term->term_id ] = $term->parent;
  670. }
  671. } elseif ( 'ids' == $_fields ) {
  672. foreach ( $terms as $term ) {
  673. $_terms[] = (int) $term->term_id;
  674. }
  675. } elseif ( 'tt_ids' == $_fields ) {
  676. foreach ( $terms as $term ) {
  677. $_terms[] = (int) $term->term_taxonomy_id;
  678. }
  679. } elseif ( 'names' == $_fields ) {
  680. foreach ( $terms as $term ) {
  681. $_terms[] = $term->name;
  682. }
  683. } elseif ( 'slugs' == $_fields ) {
  684. foreach ( $terms as $term ) {
  685. $_terms[] = $term->slug;
  686. }
  687. } elseif ( 'id=>name' == $_fields ) {
  688. foreach ( $terms as $term ) {
  689. $_terms[ $term->term_id ] = $term->name;
  690. }
  691. } elseif ( 'id=>slug' == $_fields ) {
  692. foreach ( $terms as $term ) {
  693. $_terms[ $term->term_id ] = $term->slug;
  694. }
  695. }
  696. if ( ! empty( $_terms ) ) {
  697. $terms = $_terms;
  698. }
  699. // Hierarchical queries are not limited, so 'offset' and 'number' must be handled now.
  700. if ( $hierarchical && $number && is_array( $terms ) ) {
  701. if ( $offset >= count( $terms ) ) {
  702. $terms = array();
  703. } else {
  704. $terms = array_slice( $terms, $offset, $number, true );
  705. }
  706. }
  707. wp_cache_add( $cache_key, $terms, 'terms', DAY_IN_SECONDS );
  708. if ( 'all' === $_fields || 'all_with_object_id' === $_fields ) {
  709. $terms = $this->populate_terms( $terms );
  710. }
  711. $this->terms = $terms;
  712. return $this->terms;
  713. }
  714. /**
  715. * Parse and sanitize 'orderby' keys passed to the term query.
  716. *
  717. * @since 4.6.0
  718. *
  719. * @global wpdb $wpdb WordPress database abstraction object.
  720. *
  721. * @param string $orderby_raw Alias for the field to order by.
  722. * @return string|false Value to used in the ORDER clause. False otherwise.
  723. */
  724. protected function parse_orderby( $orderby_raw ) {
  725. $_orderby = strtolower( $orderby_raw );
  726. $maybe_orderby_meta = false;
  727. if ( in_array( $_orderby, array( 'term_id', 'name', 'slug', 'term_group' ), true ) ) {
  728. $orderby = "t.$_orderby";
  729. } elseif ( in_array( $_orderby, array( 'count', 'parent', 'taxonomy', 'term_taxonomy_id', 'description' ), true ) ) {
  730. $orderby = "tt.$_orderby";
  731. } elseif ( 'term_order' === $_orderby ) {
  732. $orderby = 'tr.term_order';
  733. } elseif ( 'include' == $_orderby && ! empty( $this->query_vars['include'] ) ) {
  734. $include = implode( ',', wp_parse_id_list( $this->query_vars['include'] ) );
  735. $orderby = "FIELD( t.term_id, $include )";
  736. } elseif ( 'slug__in' == $_orderby && ! empty( $this->query_vars['slug'] ) && is_array( $this->query_vars['slug'] ) ) {
  737. $slugs = implode( "', '", array_map( 'sanitize_title_for_query', $this->query_vars['slug'] ) );
  738. $orderby = "FIELD( t.slug, '" . $slugs . "')";
  739. } elseif ( 'none' == $_orderby ) {
  740. $orderby = '';
  741. } elseif ( empty( $_orderby ) || 'id' == $_orderby || 'term_id' === $_orderby ) {
  742. $orderby = 't.term_id';
  743. } else {
  744. $orderby = 't.name';
  745. // This may be a value of orderby related to meta.
  746. $maybe_orderby_meta = true;
  747. }
  748. /**
  749. * Filters the ORDERBY clause of the terms query.
  750. *
  751. * @since 2.8.0
  752. *
  753. * @param string $orderby `ORDERBY` clause of the terms query.
  754. * @param array $args An array of terms query arguments.
  755. * @param array $taxonomies An array of taxonomies.
  756. */
  757. $orderby = apply_filters( 'get_terms_orderby', $orderby, $this->query_vars, $this->query_vars['taxonomy'] );
  758. // Run after the 'get_terms_orderby' filter for backward compatibility.
  759. if ( $maybe_orderby_meta ) {
  760. $maybe_orderby_meta = $this->parse_orderby_meta( $_orderby );
  761. if ( $maybe_orderby_meta ) {
  762. $orderby = $maybe_orderby_meta;
  763. }
  764. }
  765. return $orderby;
  766. }
  767. /**
  768. * Generate the ORDER BY clause for an 'orderby' param that is potentially related to a meta query.
  769. *
  770. * @since 4.6.0
  771. *
  772. * @param string $orderby_raw Raw 'orderby' value passed to WP_Term_Query.
  773. * @return string ORDER BY clause.
  774. */
  775. protected function parse_orderby_meta( $orderby_raw ) {
  776. $orderby = '';
  777. // Tell the meta query to generate its SQL, so we have access to table aliases.
  778. $this->meta_query->get_sql( 'term', 't', 'term_id' );
  779. $meta_clauses = $this->meta_query->get_clauses();
  780. if ( ! $meta_clauses || ! $orderby_raw ) {
  781. return $orderby;
  782. }
  783. $allowed_keys = array();
  784. $primary_meta_key = null;
  785. $primary_meta_query = reset( $meta_clauses );
  786. if ( ! empty( $primary_meta_query['key'] ) ) {
  787. $primary_meta_key = $primary_meta_query['key'];
  788. $allowed_keys[] = $primary_meta_key;
  789. }
  790. $allowed_keys[] = 'meta_value';
  791. $allowed_keys[] = 'meta_value_num';
  792. $allowed_keys = array_merge( $allowed_keys, array_keys( $meta_clauses ) );
  793. if ( ! in_array( $orderby_raw, $allowed_keys, true ) ) {
  794. return $orderby;
  795. }
  796. switch( $orderby_raw ) {
  797. case $primary_meta_key:
  798. case 'meta_value':
  799. if ( ! empty( $primary_meta_query['type'] ) ) {
  800. $orderby = "CAST({$primary_meta_query['alias']}.meta_value AS {$primary_meta_query['cast']})";
  801. } else {
  802. $orderby = "{$primary_meta_query['alias']}.meta_value";
  803. }
  804. break;
  805. case 'meta_value_num':
  806. $orderby = "{$primary_meta_query['alias']}.meta_value+0";
  807. break;
  808. default:
  809. if ( array_key_exists( $orderby_raw, $meta_clauses ) ) {
  810. // $orderby corresponds to a meta_query clause.
  811. $meta_clause = $meta_clauses[ $orderby_raw ];
  812. $orderby = "CAST({$meta_clause['alias']}.meta_value AS {$meta_clause['cast']})";
  813. }
  814. break;
  815. }
  816. return $orderby;
  817. }
  818. /**
  819. * Parse an 'order' query variable and cast it to ASC or DESC as necessary.
  820. *
  821. * @since 4.6.0
  822. *
  823. * @param string $order The 'order' query variable.
  824. * @return string The sanitized 'order' query variable.
  825. */
  826. protected function parse_order( $order ) {
  827. if ( ! is_string( $order ) || empty( $order ) ) {
  828. return 'DESC';
  829. }
  830. if ( 'ASC' === strtoupper( $order ) ) {
  831. return 'ASC';
  832. } else {
  833. return 'DESC';
  834. }
  835. }
  836. /**
  837. * Used internally to generate a SQL string related to the 'search' parameter.
  838. *
  839. * @since 4.6.0
  840. *
  841. * @global wpdb $wpdb WordPress database abstraction object.
  842. *
  843. * @param string $string
  844. * @return string
  845. */
  846. protected function get_search_sql( $string ) {
  847. global $wpdb;
  848. $like = '%' . $wpdb->esc_like( $string ) . '%';
  849. return $wpdb->prepare( '((t.name LIKE %s) OR (t.slug LIKE %s))', $like, $like );
  850. }
  851. /**
  852. * Creates an array of term objects from an array of term IDs.
  853. *
  854. * Also discards invalid term objects.
  855. *
  856. * @since 4.9.8
  857. *
  858. * @param array $term_ids Term IDs.
  859. * @return array
  860. */
  861. protected function populate_terms( $term_ids ) {
  862. $terms = array();
  863. if ( ! is_array( $term_ids ) ) {
  864. return $terms;
  865. }
  866. foreach ( $term_ids as $key => $term_id ) {
  867. $term = get_term( $term_id );
  868. if ( $term instanceof WP_Term ) {
  869. $terms[ $key ] = $term;
  870. }
  871. }
  872. return $terms;
  873. }
  874. }