class-wp-term-query.php 39 KB

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