PageRenderTime 60ms CodeModel.GetById 22ms RepoModel.GetById 0ms app.codeStats 1ms

/wp-includes/taxonomy.php

https://bitbucket.org/Thane2376/death-edge.ru
PHP | 4002 lines | 1864 code | 497 blank | 1641 comment | 527 complexity | 5a08096c3172159741fd7ae135fa481e MD5 | raw file
Possible License(s): LGPL-2.1, GPL-2.0, LGPL-3.0, AGPL-1.0

Large files files are truncated, but you can click here to view the full file

  1. <?php
  2. /**
  3. * Taxonomy API
  4. *
  5. * @package WordPress
  6. * @subpackage Taxonomy
  7. * @since 2.3.0
  8. */
  9. //
  10. // Taxonomy Registration
  11. //
  12. /**
  13. * Creates the initial taxonomies.
  14. *
  15. * This function fires twice: in wp-settings.php before plugins are loaded (for
  16. * backwards compatibility reasons), and again on the 'init' action. We must avoid
  17. * registering rewrite rules before the 'init' action.
  18. */
  19. function create_initial_taxonomies() {
  20. global $wp_rewrite;
  21. if ( ! did_action( 'init' ) ) {
  22. $rewrite = array( 'category' => false, 'post_tag' => false, 'post_format' => false );
  23. } else {
  24. /**
  25. * Filter the post formats rewrite base.
  26. *
  27. * @since 3.1.0
  28. *
  29. * @param string $context Context of the rewrite base. Default 'type'.
  30. */
  31. $post_format_base = apply_filters( 'post_format_rewrite_base', 'type' );
  32. $rewrite = array(
  33. 'category' => array(
  34. 'hierarchical' => true,
  35. 'slug' => get_option('category_base') ? get_option('category_base') : 'category',
  36. 'with_front' => ! get_option('category_base') || $wp_rewrite->using_index_permalinks(),
  37. 'ep_mask' => EP_CATEGORIES,
  38. ),
  39. 'post_tag' => array(
  40. 'slug' => get_option('tag_base') ? get_option('tag_base') : 'tag',
  41. 'with_front' => ! get_option('tag_base') || $wp_rewrite->using_index_permalinks(),
  42. 'ep_mask' => EP_TAGS,
  43. ),
  44. 'post_format' => $post_format_base ? array( 'slug' => $post_format_base ) : false,
  45. );
  46. }
  47. register_taxonomy( 'category', 'post', array(
  48. 'hierarchical' => true,
  49. 'query_var' => 'category_name',
  50. 'rewrite' => $rewrite['category'],
  51. 'public' => true,
  52. 'show_ui' => true,
  53. 'show_admin_column' => true,
  54. '_builtin' => true,
  55. ) );
  56. register_taxonomy( 'post_tag', 'post', array(
  57. 'hierarchical' => false,
  58. 'query_var' => 'tag',
  59. 'rewrite' => $rewrite['post_tag'],
  60. 'public' => true,
  61. 'show_ui' => true,
  62. 'show_admin_column' => true,
  63. '_builtin' => true,
  64. ) );
  65. register_taxonomy( 'nav_menu', 'nav_menu_item', array(
  66. 'public' => false,
  67. 'hierarchical' => false,
  68. 'labels' => array(
  69. 'name' => __( 'Navigation Menus' ),
  70. 'singular_name' => __( 'Navigation Menu' ),
  71. ),
  72. 'query_var' => false,
  73. 'rewrite' => false,
  74. 'show_ui' => false,
  75. '_builtin' => true,
  76. 'show_in_nav_menus' => false,
  77. ) );
  78. register_taxonomy( 'link_category', 'link', array(
  79. 'hierarchical' => false,
  80. 'labels' => array(
  81. 'name' => __( 'Link Categories' ),
  82. 'singular_name' => __( 'Link Category' ),
  83. 'search_items' => __( 'Search Link Categories' ),
  84. 'popular_items' => null,
  85. 'all_items' => __( 'All Link Categories' ),
  86. 'edit_item' => __( 'Edit Link Category' ),
  87. 'update_item' => __( 'Update Link Category' ),
  88. 'add_new_item' => __( 'Add New Link Category' ),
  89. 'new_item_name' => __( 'New Link Category Name' ),
  90. 'separate_items_with_commas' => null,
  91. 'add_or_remove_items' => null,
  92. 'choose_from_most_used' => null,
  93. ),
  94. 'capabilities' => array(
  95. 'manage_terms' => 'manage_links',
  96. 'edit_terms' => 'manage_links',
  97. 'delete_terms' => 'manage_links',
  98. 'assign_terms' => 'manage_links',
  99. ),
  100. 'query_var' => false,
  101. 'rewrite' => false,
  102. 'public' => false,
  103. 'show_ui' => false,
  104. '_builtin' => true,
  105. ) );
  106. register_taxonomy( 'post_format', 'post', array(
  107. 'public' => true,
  108. 'hierarchical' => false,
  109. 'labels' => array(
  110. 'name' => _x( 'Format', 'post format' ),
  111. 'singular_name' => _x( 'Format', 'post format' ),
  112. ),
  113. 'query_var' => true,
  114. 'rewrite' => $rewrite['post_format'],
  115. 'show_ui' => false,
  116. '_builtin' => true,
  117. 'show_in_nav_menus' => current_theme_supports( 'post-formats' ),
  118. ) );
  119. }
  120. add_action( 'init', 'create_initial_taxonomies', 0 ); // highest priority
  121. /**
  122. * Get a list of registered taxonomy objects.
  123. *
  124. * @since 3.0.0
  125. * @uses $wp_taxonomies
  126. * @see register_taxonomy
  127. *
  128. * @param array $args An array of key => value arguments to match against the taxonomy objects.
  129. * @param string $output The type of output to return, either taxonomy 'names' or 'objects'. 'names' is the default.
  130. * @param string $operator The logical operation to perform. 'or' means only one element
  131. * from the array needs to match; 'and' means all elements must match. The default is 'and'.
  132. * @return array A list of taxonomy names or objects
  133. */
  134. function get_taxonomies( $args = array(), $output = 'names', $operator = 'and' ) {
  135. global $wp_taxonomies;
  136. $field = ('names' == $output) ? 'name' : false;
  137. return wp_filter_object_list($wp_taxonomies, $args, $operator, $field);
  138. }
  139. /**
  140. * Return all of the taxonomy names that are of $object_type.
  141. *
  142. * It appears that this function can be used to find all of the names inside of
  143. * $wp_taxonomies global variable.
  144. *
  145. * <code><?php $taxonomies = get_object_taxonomies('post'); ?></code> Should
  146. * result in <code>Array('category', 'post_tag')</code>
  147. *
  148. * @since 2.3.0
  149. *
  150. * @uses $wp_taxonomies
  151. *
  152. * @param array|string|object $object Name of the type of taxonomy object, or an object (row from posts)
  153. * @param string $output The type of output to return, either taxonomy 'names' or 'objects'. 'names' is the default.
  154. * @return array The names of all taxonomy of $object_type.
  155. */
  156. function get_object_taxonomies($object, $output = 'names') {
  157. global $wp_taxonomies;
  158. if ( is_object($object) ) {
  159. if ( $object->post_type == 'attachment' )
  160. return get_attachment_taxonomies($object);
  161. $object = $object->post_type;
  162. }
  163. $object = (array) $object;
  164. $taxonomies = array();
  165. foreach ( (array) $wp_taxonomies as $tax_name => $tax_obj ) {
  166. if ( array_intersect($object, (array) $tax_obj->object_type) ) {
  167. if ( 'names' == $output )
  168. $taxonomies[] = $tax_name;
  169. else
  170. $taxonomies[ $tax_name ] = $tax_obj;
  171. }
  172. }
  173. return $taxonomies;
  174. }
  175. /**
  176. * Retrieves the taxonomy object of $taxonomy.
  177. *
  178. * The get_taxonomy function will first check that the parameter string given
  179. * is a taxonomy object and if it is, it will return it.
  180. *
  181. * @since 2.3.0
  182. *
  183. * @uses $wp_taxonomies
  184. * @uses taxonomy_exists() Checks whether taxonomy exists
  185. *
  186. * @param string $taxonomy Name of taxonomy object to return
  187. * @return object|bool The Taxonomy Object or false if $taxonomy doesn't exist
  188. */
  189. function get_taxonomy( $taxonomy ) {
  190. global $wp_taxonomies;
  191. if ( ! taxonomy_exists( $taxonomy ) )
  192. return false;
  193. return $wp_taxonomies[$taxonomy];
  194. }
  195. /**
  196. * Checks that the taxonomy name exists.
  197. *
  198. * Formerly is_taxonomy(), introduced in 2.3.0.
  199. *
  200. * @since 3.0.0
  201. *
  202. * @uses $wp_taxonomies
  203. *
  204. * @param string $taxonomy Name of taxonomy object
  205. * @return bool Whether the taxonomy exists.
  206. */
  207. function taxonomy_exists( $taxonomy ) {
  208. global $wp_taxonomies;
  209. return isset( $wp_taxonomies[$taxonomy] );
  210. }
  211. /**
  212. * Whether the taxonomy object is hierarchical.
  213. *
  214. * Checks to make sure that the taxonomy is an object first. Then Gets the
  215. * object, and finally returns the hierarchical value in the object.
  216. *
  217. * A false return value might also mean that the taxonomy does not exist.
  218. *
  219. * @since 2.3.0
  220. *
  221. * @uses taxonomy_exists() Checks whether taxonomy exists
  222. * @uses get_taxonomy() Used to get the taxonomy object
  223. *
  224. * @param string $taxonomy Name of taxonomy object
  225. * @return bool Whether the taxonomy is hierarchical
  226. */
  227. function is_taxonomy_hierarchical($taxonomy) {
  228. if ( ! taxonomy_exists($taxonomy) )
  229. return false;
  230. $taxonomy = get_taxonomy($taxonomy);
  231. return $taxonomy->hierarchical;
  232. }
  233. /**
  234. * Create or modify a taxonomy object. Do not use before init.
  235. *
  236. * A simple function for creating or modifying a taxonomy object based on the
  237. * parameters given. The function will accept an array (third optional
  238. * parameter), along with strings for the taxonomy name and another string for
  239. * the object type.
  240. *
  241. * Nothing is returned, so expect error maybe or use taxonomy_exists() to check
  242. * whether taxonomy exists.
  243. *
  244. * Optional $args contents:
  245. *
  246. * - label - Name of the taxonomy shown in the menu. Usually plural. If not set, labels['name'] will be used.
  247. * - labels - An array of labels for this taxonomy.
  248. * * By default tag labels are used for non-hierarchical types and category labels for hierarchical ones.
  249. * * You can see accepted values in {@link get_taxonomy_labels()}.
  250. * - description - A short descriptive summary of what the taxonomy is for. Defaults to blank.
  251. * - public - If the taxonomy should be publicly queryable; //@TODO not implemented.
  252. * * Defaults to true.
  253. * - hierarchical - Whether the taxonomy is hierarchical (e.g. category). Defaults to false.
  254. * - show_ui - Whether to generate a default UI for managing this taxonomy in the admin.
  255. * * If not set, the default is inherited from public.
  256. * - show_in_menu - Whether to show the taxonomy in the admin menu.
  257. * * If true, the taxonomy is shown as a submenu of the object type menu.
  258. * * If false, no menu is shown.
  259. * * show_ui must be true.
  260. * * If not set, the default is inherited from show_ui.
  261. * - show_in_nav_menus - Makes this taxonomy available for selection in navigation menus.
  262. * * If not set, the default is inherited from public.
  263. * - show_tagcloud - Whether to list the taxonomy in the Tag Cloud Widget.
  264. * * If not set, the default is inherited from show_ui.
  265. * - show_admin_column - Whether to display a column for the taxonomy on its post type listing screens.
  266. * * Defaults to false.
  267. * - meta_box_cb - Provide a callback function for the meta box display.
  268. * * If not set, defaults to post_categories_meta_box for hierarchical taxonomies
  269. * and post_tags_meta_box for non-hierarchical.
  270. * * If false, no meta box is shown.
  271. * - capabilities - Array of capabilities for this taxonomy.
  272. * * You can see accepted values in this function.
  273. * - rewrite - Triggers the handling of rewrites for this taxonomy. Defaults to true, using $taxonomy as slug.
  274. * * To prevent rewrite, set to false.
  275. * * To specify rewrite rules, an array can be passed with any of these keys
  276. * * 'slug' => string Customize the permastruct slug. Defaults to $taxonomy key
  277. * * 'with_front' => bool Should the permastruct be prepended with WP_Rewrite::$front. Defaults to true.
  278. * * 'hierarchical' => bool Either hierarchical rewrite tag or not. Defaults to false.
  279. * * 'ep_mask' => const Assign an endpoint mask.
  280. * * If not specified, defaults to EP_NONE.
  281. * - query_var - Sets the query_var key for this taxonomy. Defaults to $taxonomy key
  282. * * If false, a taxonomy cannot be loaded at ?{query_var}={term_slug}
  283. * * If specified as a string, the query ?{query_var_string}={term_slug} will be valid.
  284. * - update_count_callback - Works much like a hook, in that it will be called when the count is updated.
  285. * * Defaults to _update_post_term_count() for taxonomies attached to post types, which then confirms
  286. * that the objects are published before counting them.
  287. * * Defaults to _update_generic_term_count() for taxonomies attached to other object types, such as links.
  288. * - _builtin - true if this taxonomy is a native or "built-in" taxonomy. THIS IS FOR INTERNAL USE ONLY!
  289. *
  290. * @since 2.3.0
  291. * @uses $wp_taxonomies Inserts new taxonomy object into the list
  292. * @uses $wp Adds query vars
  293. *
  294. * @param string $taxonomy Taxonomy key, must not exceed 32 characters.
  295. * @param array|string $object_type Name of the object type for the taxonomy object.
  296. * @param array|string $args See optional args description above.
  297. * @return null|WP_Error WP_Error if errors, otherwise null.
  298. */
  299. function register_taxonomy( $taxonomy, $object_type, $args = array() ) {
  300. global $wp_taxonomies, $wp;
  301. if ( ! is_array( $wp_taxonomies ) )
  302. $wp_taxonomies = array();
  303. $defaults = array(
  304. 'labels' => array(),
  305. 'description' => '',
  306. 'public' => true,
  307. 'hierarchical' => false,
  308. 'show_ui' => null,
  309. 'show_in_menu' => null,
  310. 'show_in_nav_menus' => null,
  311. 'show_tagcloud' => null,
  312. 'show_admin_column' => false,
  313. 'meta_box_cb' => null,
  314. 'capabilities' => array(),
  315. 'rewrite' => true,
  316. 'query_var' => $taxonomy,
  317. 'update_count_callback' => '',
  318. '_builtin' => false,
  319. );
  320. $args = wp_parse_args( $args, $defaults );
  321. if ( strlen( $taxonomy ) > 32 ) {
  322. _doing_it_wrong( __FUNCTION__, __( 'Taxonomies cannot exceed 32 characters in length' ), '4.0' );
  323. return new WP_Error( 'taxonomy_too_long', __( 'Taxonomies cannot exceed 32 characters in length' ) );
  324. }
  325. if ( false !== $args['query_var'] && ! empty( $wp ) ) {
  326. if ( true === $args['query_var'] )
  327. $args['query_var'] = $taxonomy;
  328. else
  329. $args['query_var'] = sanitize_title_with_dashes( $args['query_var'] );
  330. $wp->add_query_var( $args['query_var'] );
  331. }
  332. if ( false !== $args['rewrite'] && ( is_admin() || '' != get_option( 'permalink_structure' ) ) ) {
  333. $args['rewrite'] = wp_parse_args( $args['rewrite'], array(
  334. 'with_front' => true,
  335. 'hierarchical' => false,
  336. 'ep_mask' => EP_NONE,
  337. ) );
  338. if ( empty( $args['rewrite']['slug'] ) )
  339. $args['rewrite']['slug'] = sanitize_title_with_dashes( $taxonomy );
  340. if ( $args['hierarchical'] && $args['rewrite']['hierarchical'] )
  341. $tag = '(.+?)';
  342. else
  343. $tag = '([^/]+)';
  344. add_rewrite_tag( "%$taxonomy%", $tag, $args['query_var'] ? "{$args['query_var']}=" : "taxonomy=$taxonomy&term=" );
  345. add_permastruct( $taxonomy, "{$args['rewrite']['slug']}/%$taxonomy%", $args['rewrite'] );
  346. }
  347. // If not set, default to the setting for public.
  348. if ( null === $args['show_ui'] )
  349. $args['show_ui'] = $args['public'];
  350. // If not set, default to the setting for show_ui.
  351. if ( null === $args['show_in_menu' ] || ! $args['show_ui'] )
  352. $args['show_in_menu' ] = $args['show_ui'];
  353. // If not set, default to the setting for public.
  354. if ( null === $args['show_in_nav_menus'] )
  355. $args['show_in_nav_menus'] = $args['public'];
  356. // If not set, default to the setting for show_ui.
  357. if ( null === $args['show_tagcloud'] )
  358. $args['show_tagcloud'] = $args['show_ui'];
  359. $default_caps = array(
  360. 'manage_terms' => 'manage_categories',
  361. 'edit_terms' => 'manage_categories',
  362. 'delete_terms' => 'manage_categories',
  363. 'assign_terms' => 'edit_posts',
  364. );
  365. $args['cap'] = (object) array_merge( $default_caps, $args['capabilities'] );
  366. unset( $args['capabilities'] );
  367. $args['name'] = $taxonomy;
  368. $args['object_type'] = array_unique( (array) $object_type );
  369. $args['labels'] = get_taxonomy_labels( (object) $args );
  370. $args['label'] = $args['labels']->name;
  371. // If not set, use the default meta box
  372. if ( null === $args['meta_box_cb'] ) {
  373. if ( $args['hierarchical'] )
  374. $args['meta_box_cb'] = 'post_categories_meta_box';
  375. else
  376. $args['meta_box_cb'] = 'post_tags_meta_box';
  377. }
  378. $wp_taxonomies[ $taxonomy ] = (object) $args;
  379. // register callback handling for metabox
  380. add_filter( 'wp_ajax_add-' . $taxonomy, '_wp_ajax_add_hierarchical_term' );
  381. /**
  382. * Fires after a taxonomy is registered.
  383. *
  384. * @since 3.3.0
  385. *
  386. * @param string $taxonomy Taxonomy slug.
  387. * @param array|string $object_type Object type or array of object types.
  388. * @param array $args Array of taxonomy registration arguments.
  389. */
  390. do_action( 'registered_taxonomy', $taxonomy, $object_type, $args );
  391. }
  392. /**
  393. * Builds an object with all taxonomy labels out of a taxonomy object
  394. *
  395. * Accepted keys of the label array in the taxonomy object:
  396. * - name - general name for the taxonomy, usually plural. The same as and overridden by $tax->label. Default is Tags/Categories
  397. * - singular_name - name for one object of this taxonomy. Default is Tag/Category
  398. * - search_items - Default is Search Tags/Search Categories
  399. * - popular_items - This string isn't used on hierarchical taxonomies. Default is Popular Tags
  400. * - all_items - Default is All Tags/All Categories
  401. * - parent_item - This string isn't used on non-hierarchical taxonomies. In hierarchical ones the default is Parent Category
  402. * - parent_item_colon - The same as <code>parent_item</code>, but with colon <code>:</code> in the end
  403. * - edit_item - Default is Edit Tag/Edit Category
  404. * - view_item - Default is View Tag/View Category
  405. * - update_item - Default is Update Tag/Update Category
  406. * - add_new_item - Default is Add New Tag/Add New Category
  407. * - new_item_name - Default is New Tag Name/New Category Name
  408. * - separate_items_with_commas - This string isn't used on hierarchical taxonomies. Default is "Separate tags with commas", used in the meta box.
  409. * - add_or_remove_items - This string isn't used on hierarchical taxonomies. Default is "Add or remove tags", used in the meta box when JavaScript is disabled.
  410. * - choose_from_most_used - This string isn't used on hierarchical taxonomies. Default is "Choose from the most used tags", used in the meta box.
  411. * - not_found - This string isn't used on hierarchical taxonomies. Default is "No tags found", used in the meta box.
  412. *
  413. * Above, the first default value is for non-hierarchical taxonomies (like tags) and the second one is for hierarchical taxonomies (like categories).
  414. *
  415. * @since 3.0.0
  416. * @param object $tax Taxonomy object
  417. * @return object object with all the labels as member variables
  418. */
  419. function get_taxonomy_labels( $tax ) {
  420. $tax->labels = (array) $tax->labels;
  421. if ( isset( $tax->helps ) && empty( $tax->labels['separate_items_with_commas'] ) )
  422. $tax->labels['separate_items_with_commas'] = $tax->helps;
  423. if ( isset( $tax->no_tagcloud ) && empty( $tax->labels['not_found'] ) )
  424. $tax->labels['not_found'] = $tax->no_tagcloud;
  425. $nohier_vs_hier_defaults = array(
  426. 'name' => array( _x( 'Tags', 'taxonomy general name' ), _x( 'Categories', 'taxonomy general name' ) ),
  427. 'singular_name' => array( _x( 'Tag', 'taxonomy singular name' ), _x( 'Category', 'taxonomy singular name' ) ),
  428. 'search_items' => array( __( 'Search Tags' ), __( 'Search Categories' ) ),
  429. 'popular_items' => array( __( 'Popular Tags' ), null ),
  430. 'all_items' => array( __( 'All Tags' ), __( 'All Categories' ) ),
  431. 'parent_item' => array( null, __( 'Parent Category' ) ),
  432. 'parent_item_colon' => array( null, __( 'Parent Category:' ) ),
  433. 'edit_item' => array( __( 'Edit Tag' ), __( 'Edit Category' ) ),
  434. 'view_item' => array( __( 'View Tag' ), __( 'View Category' ) ),
  435. 'update_item' => array( __( 'Update Tag' ), __( 'Update Category' ) ),
  436. 'add_new_item' => array( __( 'Add New Tag' ), __( 'Add New Category' ) ),
  437. 'new_item_name' => array( __( 'New Tag Name' ), __( 'New Category Name' ) ),
  438. 'separate_items_with_commas' => array( __( 'Separate tags with commas' ), null ),
  439. 'add_or_remove_items' => array( __( 'Add or remove tags' ), null ),
  440. 'choose_from_most_used' => array( __( 'Choose from the most used tags' ), null ),
  441. 'not_found' => array( __( 'No tags found.' ), null ),
  442. );
  443. $nohier_vs_hier_defaults['menu_name'] = $nohier_vs_hier_defaults['name'];
  444. return _get_custom_object_labels( $tax, $nohier_vs_hier_defaults );
  445. }
  446. /**
  447. * Add an already registered taxonomy to an object type.
  448. *
  449. * @since 3.0.0
  450. * @uses $wp_taxonomies Modifies taxonomy object
  451. *
  452. * @param string $taxonomy Name of taxonomy object
  453. * @param string $object_type Name of the object type
  454. * @return bool True if successful, false if not
  455. */
  456. function register_taxonomy_for_object_type( $taxonomy, $object_type) {
  457. global $wp_taxonomies;
  458. if ( !isset($wp_taxonomies[$taxonomy]) )
  459. return false;
  460. if ( ! get_post_type_object($object_type) )
  461. return false;
  462. if ( ! in_array( $object_type, $wp_taxonomies[$taxonomy]->object_type ) )
  463. $wp_taxonomies[$taxonomy]->object_type[] = $object_type;
  464. return true;
  465. }
  466. /**
  467. * Remove an already registered taxonomy from an object type.
  468. *
  469. * @since 3.7.0
  470. *
  471. * @param string $taxonomy Name of taxonomy object.
  472. * @param string $object_type Name of the object type.
  473. * @return bool True if successful, false if not.
  474. */
  475. function unregister_taxonomy_for_object_type( $taxonomy, $object_type ) {
  476. global $wp_taxonomies;
  477. if ( ! isset( $wp_taxonomies[ $taxonomy ] ) )
  478. return false;
  479. if ( ! get_post_type_object( $object_type ) )
  480. return false;
  481. $key = array_search( $object_type, $wp_taxonomies[ $taxonomy ]->object_type, true );
  482. if ( false === $key )
  483. return false;
  484. unset( $wp_taxonomies[ $taxonomy ]->object_type[ $key ] );
  485. return true;
  486. }
  487. //
  488. // Term API
  489. //
  490. /**
  491. * Retrieve object_ids of valid taxonomy and term.
  492. *
  493. * The strings of $taxonomies must exist before this function will continue. On
  494. * failure of finding a valid taxonomy, it will return an WP_Error class, kind
  495. * of like Exceptions in PHP 5, except you can't catch them. Even so, you can
  496. * still test for the WP_Error class and get the error message.
  497. *
  498. * The $terms aren't checked the same as $taxonomies, but still need to exist
  499. * for $object_ids to be returned.
  500. *
  501. * It is possible to change the order that object_ids is returned by either
  502. * using PHP sort family functions or using the database by using $args with
  503. * either ASC or DESC array. The value should be in the key named 'order'.
  504. *
  505. * @since 2.3.0
  506. *
  507. * @uses $wpdb
  508. * @uses wp_parse_args() Creates an array from string $args.
  509. *
  510. * @param int|array $term_ids Term id or array of term ids of terms that will be used
  511. * @param string|array $taxonomies String of taxonomy name or Array of string values of taxonomy names
  512. * @param array|string $args Change the order of the object_ids, either ASC or DESC
  513. * @return WP_Error|array If the taxonomy does not exist, then WP_Error will be returned. On success
  514. * the array can be empty meaning that there are no $object_ids found or it will return the $object_ids found.
  515. */
  516. function get_objects_in_term( $term_ids, $taxonomies, $args = array() ) {
  517. global $wpdb;
  518. if ( ! is_array( $term_ids ) ) {
  519. $term_ids = array( $term_ids );
  520. }
  521. if ( ! is_array( $taxonomies ) ) {
  522. $taxonomies = array( $taxonomies );
  523. }
  524. foreach ( (array) $taxonomies as $taxonomy ) {
  525. if ( ! taxonomy_exists( $taxonomy ) ) {
  526. return new WP_Error( 'invalid_taxonomy', __( 'Invalid taxonomy' ) );
  527. }
  528. }
  529. $defaults = array( 'order' => 'ASC' );
  530. $args = wp_parse_args( $args, $defaults );
  531. $order = ( 'desc' == strtolower( $args['order'] ) ) ? 'DESC' : 'ASC';
  532. $term_ids = array_map('intval', $term_ids );
  533. $taxonomies = "'" . implode( "', '", $taxonomies ) . "'";
  534. $term_ids = "'" . implode( "', '", $term_ids ) . "'";
  535. $object_ids = $wpdb->get_col("SELECT tr.object_id FROM $wpdb->term_relationships AS tr INNER JOIN $wpdb->term_taxonomy AS tt ON tr.term_taxonomy_id = tt.term_taxonomy_id WHERE tt.taxonomy IN ($taxonomies) AND tt.term_id IN ($term_ids) ORDER BY tr.object_id $order");
  536. if ( ! $object_ids ){
  537. return array();
  538. }
  539. return $object_ids;
  540. }
  541. /**
  542. * Given a taxonomy query, generates SQL to be appended to a main query.
  543. *
  544. * @since 3.1.0
  545. *
  546. * @see WP_Tax_Query
  547. *
  548. * @param array $tax_query A compact tax query
  549. * @param string $primary_table
  550. * @param string $primary_id_column
  551. * @return array
  552. */
  553. function get_tax_sql( $tax_query, $primary_table, $primary_id_column ) {
  554. $tax_query_obj = new WP_Tax_Query( $tax_query );
  555. return $tax_query_obj->get_sql( $primary_table, $primary_id_column );
  556. }
  557. /**
  558. * Container class for a multiple taxonomy query.
  559. *
  560. * @since 3.1.0
  561. */
  562. class WP_Tax_Query {
  563. /**
  564. * List of taxonomy queries. A single taxonomy query is an associative array:
  565. * - 'taxonomy' string The taxonomy being queried. Optional when using the term_taxonomy_id field.
  566. * - 'terms' string|array The list of terms
  567. * - 'field' string (optional) Which term field is being used.
  568. * Possible values: 'term_id', 'slug', 'name', or 'term_taxonomy_id'
  569. * Default: 'term_id'
  570. * - 'operator' string (optional)
  571. * Possible values: 'AND', 'IN' or 'NOT IN'.
  572. * Default: 'IN'
  573. * - 'include_children' bool (optional) Whether to include child terms. Requires that a taxonomy be specified.
  574. * Default: true
  575. *
  576. * @since 3.1.0
  577. * @access public
  578. * @var array
  579. */
  580. public $queries = array();
  581. /**
  582. * The relation between the queries. Can be one of 'AND' or 'OR'.
  583. *
  584. * @since 3.1.0
  585. * @access public
  586. * @var string
  587. */
  588. public $relation;
  589. /**
  590. * Standard response when the query should not return any rows.
  591. *
  592. * @since 3.2.0
  593. * @access private
  594. * @var string
  595. */
  596. private static $no_results = array( 'join' => '', 'where' => ' AND 0 = 1' );
  597. /**
  598. * Constructor.
  599. *
  600. * Parses a compact tax query and sets defaults.
  601. *
  602. * @since 3.1.0
  603. * @access public
  604. *
  605. * @param array $tax_query A compact tax query:
  606. * array(
  607. * 'relation' => 'OR',
  608. * array(
  609. * 'taxonomy' => 'tax1',
  610. * 'terms' => array( 'term1', 'term2' ),
  611. * 'field' => 'slug',
  612. * ),
  613. * array(
  614. * 'taxonomy' => 'tax2',
  615. * 'terms' => array( 'term-a', 'term-b' ),
  616. * 'field' => 'slug',
  617. * ),
  618. * )
  619. */
  620. public function __construct( $tax_query ) {
  621. if ( isset( $tax_query['relation'] ) && strtoupper( $tax_query['relation'] ) == 'OR' ) {
  622. $this->relation = 'OR';
  623. } else {
  624. $this->relation = 'AND';
  625. }
  626. $defaults = array(
  627. 'taxonomy' => '',
  628. 'terms' => array(),
  629. 'include_children' => true,
  630. 'field' => 'term_id',
  631. 'operator' => 'IN',
  632. );
  633. foreach ( $tax_query as $query ) {
  634. if ( ! is_array( $query ) )
  635. continue;
  636. $query = array_merge( $defaults, $query );
  637. $query['terms'] = (array) $query['terms'];
  638. $this->queries[] = $query;
  639. }
  640. }
  641. /**
  642. * Generates SQL clauses to be appended to a main query.
  643. *
  644. * @since 3.1.0
  645. * @access public
  646. *
  647. * @param string $primary_table
  648. * @param string $primary_id_column
  649. * @return array
  650. */
  651. public function get_sql( $primary_table, $primary_id_column ) {
  652. global $wpdb;
  653. $join = '';
  654. $where = array();
  655. $i = 0;
  656. $count = count( $this->queries );
  657. foreach ( $this->queries as $index => $query ) {
  658. $this->clean_query( $query );
  659. if ( is_wp_error( $query ) ) {
  660. return self::$no_results;
  661. }
  662. $terms = $query['terms'];
  663. $operator = strtoupper( $query['operator'] );
  664. if ( 'IN' == $operator ) {
  665. if ( empty( $terms ) ) {
  666. if ( 'OR' == $this->relation ) {
  667. if ( ( $index + 1 === $count ) && empty( $where ) ) {
  668. return self::$no_results;
  669. }
  670. continue;
  671. } else {
  672. return self::$no_results;
  673. }
  674. }
  675. $terms = implode( ',', $terms );
  676. $alias = $i ? 'tt' . $i : $wpdb->term_relationships;
  677. $join .= " INNER JOIN $wpdb->term_relationships";
  678. $join .= $i ? " AS $alias" : '';
  679. $join .= " ON ($primary_table.$primary_id_column = $alias.object_id)";
  680. $where[] = "$alias.term_taxonomy_id $operator ($terms)";
  681. } elseif ( 'NOT IN' == $operator ) {
  682. if ( empty( $terms ) ) {
  683. continue;
  684. }
  685. $terms = implode( ',', $terms );
  686. $where[] = "$primary_table.$primary_id_column NOT IN (
  687. SELECT object_id
  688. FROM $wpdb->term_relationships
  689. WHERE term_taxonomy_id IN ($terms)
  690. )";
  691. } elseif ( 'AND' == $operator ) {
  692. if ( empty( $terms ) ) {
  693. continue;
  694. }
  695. $num_terms = count( $terms );
  696. $terms = implode( ',', $terms );
  697. $where[] = "(
  698. SELECT COUNT(1)
  699. FROM $wpdb->term_relationships
  700. WHERE term_taxonomy_id IN ($terms)
  701. AND object_id = $primary_table.$primary_id_column
  702. ) = $num_terms";
  703. }
  704. $i++;
  705. }
  706. if ( ! empty( $where ) ) {
  707. $where = ' AND ( ' . implode( " $this->relation ", $where ) . ' )';
  708. } else {
  709. $where = '';
  710. }
  711. return compact( 'join', 'where' );
  712. }
  713. /**
  714. * Validates a single query.
  715. *
  716. * @since 3.2.0
  717. * @access private
  718. *
  719. * @param array &$query The single query
  720. */
  721. private function clean_query( &$query ) {
  722. if ( empty( $query['taxonomy'] ) ) {
  723. if ( 'term_taxonomy_id' !== $query['field'] ) {
  724. $query = new WP_Error( 'Invalid taxonomy' );
  725. return;
  726. }
  727. // so long as there are shared terms, include_children requires that a taxonomy is set
  728. $query['include_children'] = false;
  729. } elseif ( ! taxonomy_exists( $query['taxonomy'] ) ) {
  730. $query = new WP_Error( 'Invalid taxonomy' );
  731. return;
  732. }
  733. $query['terms'] = array_unique( (array) $query['terms'] );
  734. if ( is_taxonomy_hierarchical( $query['taxonomy'] ) && $query['include_children'] ) {
  735. $this->transform_query( $query, 'term_id' );
  736. if ( is_wp_error( $query ) )
  737. return;
  738. $children = array();
  739. foreach ( $query['terms'] as $term ) {
  740. $children = array_merge( $children, get_term_children( $term, $query['taxonomy'] ) );
  741. $children[] = $term;
  742. }
  743. $query['terms'] = $children;
  744. }
  745. $this->transform_query( $query, 'term_taxonomy_id' );
  746. }
  747. /**
  748. * Transforms a single query, from one field to another.
  749. *
  750. * @since 3.2.0
  751. *
  752. * @param array &$query The single query
  753. * @param string $resulting_field The resulting field
  754. */
  755. public function transform_query( &$query, $resulting_field ) {
  756. global $wpdb;
  757. if ( empty( $query['terms'] ) )
  758. return;
  759. if ( $query['field'] == $resulting_field )
  760. return;
  761. $resulting_field = sanitize_key( $resulting_field );
  762. switch ( $query['field'] ) {
  763. case 'slug':
  764. case 'name':
  765. $terms = "'" . implode( "','", array_map( 'sanitize_title_for_query', $query['terms'] ) ) . "'";
  766. $terms = $wpdb->get_col( "
  767. SELECT $wpdb->term_taxonomy.$resulting_field
  768. FROM $wpdb->term_taxonomy
  769. INNER JOIN $wpdb->terms USING (term_id)
  770. WHERE taxonomy = '{$query['taxonomy']}'
  771. AND $wpdb->terms.{$query['field']} IN ($terms)
  772. " );
  773. break;
  774. case 'term_taxonomy_id':
  775. $terms = implode( ',', array_map( 'intval', $query['terms'] ) );
  776. $terms = $wpdb->get_col( "
  777. SELECT $resulting_field
  778. FROM $wpdb->term_taxonomy
  779. WHERE term_taxonomy_id IN ($terms)
  780. " );
  781. break;
  782. default:
  783. $terms = implode( ',', array_map( 'intval', $query['terms'] ) );
  784. $terms = $wpdb->get_col( "
  785. SELECT $resulting_field
  786. FROM $wpdb->term_taxonomy
  787. WHERE taxonomy = '{$query['taxonomy']}'
  788. AND term_id IN ($terms)
  789. " );
  790. }
  791. if ( 'AND' == $query['operator'] && count( $terms ) < count( $query['terms'] ) ) {
  792. $query = new WP_Error( 'Inexistent terms' );
  793. return;
  794. }
  795. $query['terms'] = $terms;
  796. $query['field'] = $resulting_field;
  797. }
  798. }
  799. /**
  800. * Get all Term data from database by Term ID.
  801. *
  802. * The usage of the get_term function is to apply filters to a term object. It
  803. * is possible to get a term object from the database before applying the
  804. * filters.
  805. *
  806. * $term ID must be part of $taxonomy, to get from the database. Failure, might
  807. * be able to be captured by the hooks. Failure would be the same value as $wpdb
  808. * returns for the get_row method.
  809. *
  810. * There are two hooks, one is specifically for each term, named 'get_term', and
  811. * the second is for the taxonomy name, 'term_$taxonomy'. Both hooks gets the
  812. * term object, and the taxonomy name as parameters. Both hooks are expected to
  813. * return a Term object.
  814. *
  815. * 'get_term' hook - Takes two parameters the term Object and the taxonomy name.
  816. * Must return term object. Used in get_term() as a catch-all filter for every
  817. * $term.
  818. *
  819. * 'get_$taxonomy' hook - Takes two parameters the term Object and the taxonomy
  820. * name. Must return term object. $taxonomy will be the taxonomy name, so for
  821. * example, if 'category', it would be 'get_category' as the filter name. Useful
  822. * for custom taxonomies or plugging into default taxonomies.
  823. *
  824. * @since 2.3.0
  825. *
  826. * @uses $wpdb
  827. * @uses sanitize_term() Cleanses the term based on $filter context before returning.
  828. * @see sanitize_term_field() The $context param lists the available values for get_term_by() $filter param.
  829. *
  830. * @param int|object $term If integer, will get from database. If object will apply filters and return $term.
  831. * @param string $taxonomy Taxonomy name that $term is part of.
  832. * @param string $output Constant OBJECT, ARRAY_A, or ARRAY_N
  833. * @param string $filter Optional, default is raw or no WordPress defined filter will applied.
  834. * @return mixed|null|WP_Error Term Row from database. Will return null if $term is empty. If taxonomy does not
  835. * exist then WP_Error will be returned.
  836. */
  837. function get_term($term, $taxonomy, $output = OBJECT, $filter = 'raw') {
  838. global $wpdb;
  839. if ( empty($term) ) {
  840. $error = new WP_Error('invalid_term', __('Empty Term'));
  841. return $error;
  842. }
  843. if ( ! taxonomy_exists($taxonomy) ) {
  844. $error = new WP_Error('invalid_taxonomy', __('Invalid taxonomy'));
  845. return $error;
  846. }
  847. if ( is_object($term) && empty($term->filter) ) {
  848. wp_cache_add($term->term_id, $term, $taxonomy);
  849. $_term = $term;
  850. } else {
  851. if ( is_object($term) )
  852. $term = $term->term_id;
  853. if ( !$term = (int) $term )
  854. return null;
  855. if ( ! $_term = wp_cache_get($term, $taxonomy) ) {
  856. $_term = $wpdb->get_row( $wpdb->prepare( "SELECT t.*, tt.* FROM $wpdb->terms AS t INNER JOIN $wpdb->term_taxonomy AS tt ON t.term_id = tt.term_id WHERE tt.taxonomy = %s AND t.term_id = %d LIMIT 1", $taxonomy, $term) );
  857. if ( ! $_term )
  858. return null;
  859. wp_cache_add($term, $_term, $taxonomy);
  860. }
  861. }
  862. /**
  863. * Filter a term.
  864. *
  865. * @since 2.3.0
  866. *
  867. * @param int|object $_term Term object or ID.
  868. * @param string $taxonomy The taxonomy slug.
  869. */
  870. $_term = apply_filters( 'get_term', $_term, $taxonomy );
  871. /**
  872. * Filter a taxonomy.
  873. *
  874. * The dynamic portion of the filter name, $taxonomy, refers
  875. * to the taxonomy slug.
  876. *
  877. * @since 2.3.0
  878. *
  879. * @param int|object $_term Term object or ID.
  880. * @param string $taxonomy The taxonomy slug.
  881. */
  882. $_term = apply_filters( "get_$taxonomy", $_term, $taxonomy );
  883. $_term = sanitize_term($_term, $taxonomy, $filter);
  884. if ( $output == OBJECT ) {
  885. return $_term;
  886. } elseif ( $output == ARRAY_A ) {
  887. $__term = get_object_vars($_term);
  888. return $__term;
  889. } elseif ( $output == ARRAY_N ) {
  890. $__term = array_values(get_object_vars($_term));
  891. return $__term;
  892. } else {
  893. return $_term;
  894. }
  895. }
  896. /**
  897. * Get all Term data from database by Term field and data.
  898. *
  899. * Warning: $value is not escaped for 'name' $field. You must do it yourself, if
  900. * required.
  901. *
  902. * The default $field is 'id', therefore it is possible to also use null for
  903. * field, but not recommended that you do so.
  904. *
  905. * If $value does not exist, the return value will be false. If $taxonomy exists
  906. * and $field and $value combinations exist, the Term will be returned.
  907. *
  908. * @since 2.3.0
  909. *
  910. * @uses $wpdb
  911. * @uses sanitize_term() Cleanses the term based on $filter context before returning.
  912. * @see sanitize_term_field() The $context param lists the available values for get_term_by() $filter param.
  913. *
  914. * @param string $field Either 'slug', 'name', 'id' (term_id), or 'term_taxonomy_id'
  915. * @param string|int $value Search for this term value
  916. * @param string $taxonomy Taxonomy Name
  917. * @param string $output Constant OBJECT, ARRAY_A, or ARRAY_N
  918. * @param string $filter Optional, default is raw or no WordPress defined filter will applied.
  919. * @return mixed Term Row from database. Will return false if $taxonomy does not exist or $term was not found.
  920. */
  921. function get_term_by($field, $value, $taxonomy, $output = OBJECT, $filter = 'raw') {
  922. global $wpdb;
  923. if ( ! taxonomy_exists($taxonomy) )
  924. return false;
  925. if ( 'slug' == $field ) {
  926. $field = 't.slug';
  927. $value = sanitize_title($value);
  928. if ( empty($value) )
  929. return false;
  930. } else if ( 'name' == $field ) {
  931. // Assume already escaped
  932. $value = wp_unslash($value);
  933. $field = 't.name';
  934. } else if ( 'term_taxonomy_id' == $field ) {
  935. $value = (int) $value;
  936. $field = 'tt.term_taxonomy_id';
  937. } else {
  938. $term = get_term( (int) $value, $taxonomy, $output, $filter);
  939. if ( is_wp_error( $term ) )
  940. $term = false;
  941. return $term;
  942. }
  943. $term = $wpdb->get_row( $wpdb->prepare( "SELECT t.*, tt.* FROM $wpdb->terms AS t INNER JOIN $wpdb->term_taxonomy AS tt ON t.term_id = tt.term_id WHERE tt.taxonomy = %s AND $field = %s LIMIT 1", $taxonomy, $value) );
  944. if ( !$term )
  945. return false;
  946. wp_cache_add($term->term_id, $term, $taxonomy);
  947. /** This filter is documented in wp-includes/taxonomy.php */
  948. $term = apply_filters( 'get_term', $term, $taxonomy );
  949. /** This filter is documented in wp-includes/taxonomy.php */
  950. $term = apply_filters( "get_$taxonomy", $term, $taxonomy );
  951. $term = sanitize_term($term, $taxonomy, $filter);
  952. if ( $output == OBJECT ) {
  953. return $term;
  954. } elseif ( $output == ARRAY_A ) {
  955. return get_object_vars($term);
  956. } elseif ( $output == ARRAY_N ) {
  957. return array_values(get_object_vars($term));
  958. } else {
  959. return $term;
  960. }
  961. }
  962. /**
  963. * Merge all term children into a single array of their IDs.
  964. *
  965. * This recursive function will merge all of the children of $term into the same
  966. * array of term IDs. Only useful for taxonomies which are hierarchical.
  967. *
  968. * Will return an empty array if $term does not exist in $taxonomy.
  969. *
  970. * @since 2.3.0
  971. *
  972. * @uses $wpdb
  973. * @uses _get_term_hierarchy()
  974. * @uses get_term_children() Used to get the children of both $taxonomy and the parent $term
  975. *
  976. * @param string $term_id ID of Term to get children
  977. * @param string $taxonomy Taxonomy Name
  978. * @return array|WP_Error List of Term IDs. WP_Error returned if $taxonomy does not exist
  979. */
  980. function get_term_children( $term_id, $taxonomy ) {
  981. if ( ! taxonomy_exists($taxonomy) )
  982. return new WP_Error('invalid_taxonomy', __('Invalid taxonomy'));
  983. $term_id = intval( $term_id );
  984. $terms = _get_term_hierarchy($taxonomy);
  985. if ( ! isset($terms[$term_id]) )
  986. return array();
  987. $children = $terms[$term_id];
  988. foreach ( (array) $terms[$term_id] as $child ) {
  989. if ( $term_id == $child ) {
  990. continue;
  991. }
  992. if ( isset($terms[$child]) )
  993. $children = array_merge($children, get_term_children($child, $taxonomy));
  994. }
  995. return $children;
  996. }
  997. /**
  998. * Get sanitized Term field.
  999. *
  1000. * Does checks for $term, based on the $taxonomy. The function is for contextual
  1001. * reasons and for simplicity of usage. See sanitize_term_field() for more
  1002. * information.
  1003. *
  1004. * @since 2.3.0
  1005. *
  1006. * @uses sanitize_term_field() Passes the return value in sanitize_term_field on success.
  1007. *
  1008. * @param string $field Term field to fetch
  1009. * @param int $term Term ID
  1010. * @param string $taxonomy Taxonomy Name
  1011. * @param string $context Optional, default is display. Look at sanitize_term_field() for available options.
  1012. * @return mixed Will return an empty string if $term is not an object or if $field is not set in $term.
  1013. */
  1014. function get_term_field( $field, $term, $taxonomy, $context = 'display' ) {
  1015. $term = (int) $term;
  1016. $term = get_term( $term, $taxonomy );
  1017. if ( is_wp_error($term) )
  1018. return $term;
  1019. if ( !is_object($term) )
  1020. return '';
  1021. if ( !isset($term->$field) )
  1022. return '';
  1023. return sanitize_term_field($field, $term->$field, $term->term_id, $taxonomy, $context);
  1024. }
  1025. /**
  1026. * Sanitizes Term for editing.
  1027. *
  1028. * Return value is sanitize_term() and usage is for sanitizing the term for
  1029. * editing. Function is for contextual and simplicity.
  1030. *
  1031. * @since 2.3.0
  1032. *
  1033. * @uses sanitize_term() Passes the return value on success
  1034. *
  1035. * @param int|object $id Term ID or Object
  1036. * @param string $taxonomy Taxonomy Name
  1037. * @return mixed|null|WP_Error Will return empty string if $term is not an object.
  1038. */
  1039. function get_term_to_edit( $id, $taxonomy ) {
  1040. $term = get_term( $id, $taxonomy );
  1041. if ( is_wp_error($term) )
  1042. return $term;
  1043. if ( !is_object($term) )
  1044. return '';
  1045. return sanitize_term($term, $taxonomy, 'edit');
  1046. }
  1047. /**
  1048. * Retrieve the terms in a given taxonomy or list of taxonomies.
  1049. *
  1050. * You can fully inject any customizations to the query before it is sent, as
  1051. * well as control the output with a filter.
  1052. *
  1053. * The 'get_terms' filter will be called when the cache has the term and will
  1054. * pass the found term along with the array of $taxonomies and array of $args.
  1055. * This filter is also called before the array of terms is passed and will pass
  1056. * the array of terms, along with the $taxonomies and $args.
  1057. *
  1058. * The 'list_terms_exclusions' filter passes the compiled exclusions along with
  1059. * the $args.
  1060. *
  1061. * The 'get_terms_orderby' filter passes the ORDER BY clause for the query
  1062. * along with the $args array.
  1063. *
  1064. * The 'get_terms_fields' filter passes the fields for the SELECT query
  1065. * along with the $args array.
  1066. *
  1067. * @since 2.3.0
  1068. *
  1069. * @global wpdb $wpdb WordPress database access abstraction object.
  1070. *
  1071. * @param string|array $taxonomies Taxonomy name or list of Taxonomy names.
  1072. * @param array|string $args {
  1073. * Optional. Array or string of arguments to get terms.
  1074. *
  1075. * @type string $orderby Field(s) to order terms by. Accepts term fields, though
  1076. * empty defaults to 'term_id'. Default 'name'.
  1077. * @type string $order Whether to order terms in ascending or descending order.
  1078. * Accepts 'ASC' (ascending) or 'DESC' (descending).
  1079. * Default 'ASC'.
  1080. * @type bool|int $hide_empty Whether to hide terms not assigned to any posts. Accepts
  1081. * 1|true or 0|false. Default 1|true.
  1082. * @type array|string $include Array or comma/space-separated string of term ids to include.
  1083. * Default empty array.
  1084. * @type array|string $exclude Array or comma/space-separated string of term ids to exclude.
  1085. * If $include is non-empty, $exclude is ignored.
  1086. * Default empty array.
  1087. * @type array|string $exclude_tree Array or comma/space-separated string of term ids to exclude
  1088. * along with all of their descendant terms. If $include is
  1089. * non-empty, $exclude_tree is ignored. Default empty array.
  1090. * @type int $number Maximum number of terms to return. Accepts 1+ or -1 (all).
  1091. * Default -1.
  1092. * @type int $offset The number by which to offset the terms query. Default empty.
  1093. * @type string $fields Term fields to query for. Accepts 'all' (returns an array of
  1094. * term objects), 'ids' or 'names' (returns an array of integers
  1095. * or strings, respectively. Default 'all'.
  1096. * @type string $slug Slug to return term(s) for. Default empty.
  1097. * @type bool $hierarchical Whether to include terms that have non-empty descendants (even
  1098. * if $hide_empty is set to true). Default true.
  1099. * @type string $search Search criteria to match terms. Will be SQL-formatted with
  1100. * wildcards before and after. Default empty.
  1101. * @type string $name__like Retrieve terms with criteria by which a term is LIKE $name__like.
  1102. * Default empty.
  1103. * @type string $description__like Retrieve terms where the description is LIKE $description__like.
  1104. * Default empty.
  1105. * @type bool $pad_counts Whether to pad the quantity of a term's children in the quantity
  1106. * of each term's "count" object variable. Default false.
  1107. * @type string $get Whether to return terms regardless of ancestry or whether the terms
  1108. * are empty. Accepts 'all' or empty (disabled). Default empty.
  1109. * @type int $child_of Term ID to retrieve child terms of. If multiple taxonomies
  1110. * are passed, $child_of is ignored. Default 0.
  1111. * @type int|string $parent Parent term ID to retrieve direct-child terms of. Default empty.
  1112. * @type string $cache_domain Unique cache key to be produced when this query is stored in an
  1113. * object cache. Default is 'core'.
  1114. * }
  1115. * @return array|WP_Error List of Term Objects and their children. Will return WP_Error, if any of $taxonomies
  1116. * do not exist.
  1117. */
  1118. function get_terms( $taxonomies, $args = '' ) {
  1119. global $wpdb;
  1120. $empty_array = array();
  1121. $single_taxonomy = ! is_array( $taxonomies ) || 1 === count( $taxonomies );
  1122. if ( ! is_array( $taxonomies ) ) {
  1123. $taxonomies = array( $taxonomies );
  1124. }
  1125. foreach ( $taxonomies as $taxonomy ) {
  1126. if ( ! taxonomy_exists($taxonomy) ) {
  1127. $error = new WP_Error('invalid_taxonomy', __('Invalid taxonomy'));
  1128. return $error;
  1129. }
  1130. }
  1131. $defaults = array('orderby' => 'name', 'order' => 'ASC',
  1132. 'hide_empty' => true, 'exclude' => array(), 'exclude_tree' => array(), 'include' => array(),
  1133. 'number' => '', 'fields' => 'all', 'slug' => '', 'parent' => '',
  1134. 'hierarchical' => true, 'child_of' => 0, 'get' => '', 'name__like' => '', 'description__like' => '',
  1135. 'pad_counts' => false, 'offset' => '', 'search' => '', 'cache_domain' => 'core' );
  1136. $args = wp_parse_args( $args, $defaults );
  1137. $args['number'] = absint( $args['number'] );
  1138. $args['offset'] = absint( $args['offset'] );
  1139. if ( !$single_taxonomy || ! is_taxonomy_hierarchical( reset( $taxonomies ) ) ||
  1140. ( '' !== $args['parent'] && 0 !== $args['parent'] ) ) {
  1141. $args['child_of'] = 0;
  1142. $args['hierarchical'] = false;
  1143. $args['pad_counts'] = false;
  1144. }
  1145. if ( 'all' == $args['get'] ) {
  1146. $args['child_of'] = 0;
  1147. $args['hide_empty'] = 0;
  1148. $args['hierarchical'] = false;
  1149. $args['pad_counts'] = false;
  1150. }
  1151. /**
  1152. * Filter the terms query arguments.
  1153. *
  1154. * @since 3.1.0
  1155. *
  1156. * @param array $args An array of arguments.
  1157. * @param string|array $taxonomies A taxonomy or array of taxonomies.
  1158. */
  1159. $args = apply_filters( 'get_terms_args', $args, $taxonomies );
  1160. $child_of = $args['child_of'];
  1161. if ( $child_of ) {
  1162. $hierarchy = _get_term_hierarchy( reset( $taxonomies ) );
  1163. if ( ! isset( $hierarchy[ $child_of ] ) ) {
  1164. return $empty_array;
  1165. }
  1166. }
  1167. $parent = $args['parent'];
  1168. if ( $parent ) {
  1169. $hierarchy = _get_term_hierarchy( reset( $taxonomies ) );
  1170. if ( ! isset( $hierarchy[ $parent ] ) ) {
  1171. return $empty_array;
  1172. }
  1173. }
  1174. // $args can be whatever, only use the args defined in defaults to compute the key
  1175. $filter_key = ( has_filter('list_terms_exclusions') ) ? serialize($GLOBALS['wp_filter']['list_terms_exclusions']) : '';
  1176. $key = md5( serialize( wp_array_slice_assoc( $args, array_keys( $defaults ) ) ) . serialize( $taxonomies ) . $filter_key );
  1177. $last_changed = wp_cache_get( 'last_changed', 'terms' );
  1178. if ( ! $last_changed ) {
  1179. $last_changed = microtime();
  1180. wp_cache_set( 'last_changed', $last_changed, 'terms' );
  1181. }
  1182. $cache_key = "get_terms:$key:$last_changed";
  1183. $cache = wp_cache_get( $cache_key, 'terms' );
  1184. if ( false !== $cache ) {
  1185. /**
  1186. * Filter the given taxonomy's terms cache.
  1187. *
  1188. * @since 2.3.0
  1189. *
  1190. * @param array $cache Cached array of terms for the given taxonomy.
  1191. * @param string|array $taxonomies A taxonomy or array of taxonomies.
  1192. * @param array $args An array of arguments to get terms.
  1193. */
  1194. $cache = apply_filters( 'get_terms', $cache, $taxonomies, $args );
  1195. return $cache;
  1196. }
  1197. $_orderby = strtolower( $args['orderby'] );
  1198. if ( 'count' == $_orderby ) {
  1199. $orderby = 'tt.count';
  1200. } else if ( 'name' == $_orderby ) {
  1201. $orderby = 't.name';
  1202. } else if ( 'slug' == $_orderby ) {
  1203. $orderby = 't.slug';
  1204. } else if ( 'term_group' == $_orderby ) {
  1205. $orderby = 't.term_group';
  1206. } else if ( 'none' == $_orderby ) {
  1207. $orderby = '';
  1208. } elseif ( empty($_orderby) || 'id' == $_orderby ) {
  1209. $orderby = 't.term_id';
  1210. } else {
  1211. $orderby = 't.name';
  1212. }
  1213. /**
  1214. * Filter the ORDERBY clause of the terms query.
  1215. *
  1216. * @since 2.8.0
  1217. *
  1218. * @param string $orderby ORDERBY clause of the terms query.
  1219. * @param array $args An array of terms query arguments.
  1220. * @param string|array $taxonomies A taxonomy or array of taxonomies.
  1221. */
  1222. $orderby = apply_filters( 'get_terms_orderby', $orderby, $args, $taxonomies );
  1223. $order = strtoupper( $args['order'] );
  1224. if ( ! empty( $orderby ) ) {
  1225. $orderby = "ORDER BY $orderby";
  1226. } else {
  1227. $order = '';
  1228. }
  1229. if ( '' !== $order && ! in_array( $order, array( 'ASC', 'DESC' ) ) ) {
  1230. $order = 'ASC';
  1231. }
  1232. $where = "tt.taxonomy IN ('" . implode("', '", $taxonomies) . "')";
  1233. $exclude = $args['exclude'];
  1234. $exclude_tree = $args['exclude_tree'];
  1235. $include = $args['include'];
  1236. $inclusions = '';
  1237. if ( ! empty( $include ) ) {
  1238. $exclude = '';
  1239. $exclude_tree = '';
  1240. $inclusions = implode( ',', wp_parse_id_list( $include ) );
  1241. }
  1242. if ( ! empty( $inclusions ) ) {
  1243. $inclusions = ' AND t.term_id IN ( ' . $inclusions . ' )';
  1244. $where .= $inclusions;
  1245. }
  1246. if ( ! empty( $exclude_tree ) ) {
  1247. $exclude_tree =

Large files files are truncated, but you can click here to view the full file