暫無描述

class-wp-term-query.php 39KB

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