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

/wp-includes/taxonomy.php

https://github.com/Jezfx/synergy
PHP | 3934 lines | 1766 code | 505 blank | 1663 comment | 511 complexity | 4aa149549baa0879a1e0f2230622a900 MD5 | raw file
Possible License(s): GPL-2.0, MIT, BSD-3-Clause, LGPL-2.1

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 - Where 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. return new WP_Error( 'taxonomy_too_long', __( 'Taxonomies cannot exceed 32 characters in length' ) );
  323. if ( false !== $args['query_var'] && ! empty( $wp ) ) {
  324. if ( true === $args['query_var'] )
  325. $args['query_var'] = $taxonomy;
  326. else
  327. $args['query_var'] = sanitize_title_with_dashes( $args['query_var'] );
  328. $wp->add_query_var( $args['query_var'] );
  329. }
  330. if ( false !== $args['rewrite'] && ( is_admin() || '' != get_option( 'permalink_structure' ) ) ) {
  331. $args['rewrite'] = wp_parse_args( $args['rewrite'], array(
  332. 'with_front' => true,
  333. 'hierarchical' => false,
  334. 'ep_mask' => EP_NONE,
  335. ) );
  336. if ( empty( $args['rewrite']['slug'] ) )
  337. $args['rewrite']['slug'] = sanitize_title_with_dashes( $taxonomy );
  338. if ( $args['hierarchical'] && $args['rewrite']['hierarchical'] )
  339. $tag = '(.+?)';
  340. else
  341. $tag = '([^/]+)';
  342. add_rewrite_tag( "%$taxonomy%", $tag, $args['query_var'] ? "{$args['query_var']}=" : "taxonomy=$taxonomy&term=" );
  343. add_permastruct( $taxonomy, "{$args['rewrite']['slug']}/%$taxonomy%", $args['rewrite'] );
  344. }
  345. // If not set, default to the setting for public.
  346. if ( null === $args['show_ui'] )
  347. $args['show_ui'] = $args['public'];
  348. // If not set, default to the setting for show_ui.
  349. if ( null === $args['show_in_menu' ] || ! $args['show_ui'] )
  350. $args['show_in_menu' ] = $args['show_ui'];
  351. // If not set, default to the setting for public.
  352. if ( null === $args['show_in_nav_menus'] )
  353. $args['show_in_nav_menus'] = $args['public'];
  354. // If not set, default to the setting for show_ui.
  355. if ( null === $args['show_tagcloud'] )
  356. $args['show_tagcloud'] = $args['show_ui'];
  357. $default_caps = array(
  358. 'manage_terms' => 'manage_categories',
  359. 'edit_terms' => 'manage_categories',
  360. 'delete_terms' => 'manage_categories',
  361. 'assign_terms' => 'edit_posts',
  362. );
  363. $args['cap'] = (object) array_merge( $default_caps, $args['capabilities'] );
  364. unset( $args['capabilities'] );
  365. $args['name'] = $taxonomy;
  366. $args['object_type'] = array_unique( (array) $object_type );
  367. $args['labels'] = get_taxonomy_labels( (object) $args );
  368. $args['label'] = $args['labels']->name;
  369. // If not set, use the default meta box
  370. if ( null === $args['meta_box_cb'] ) {
  371. if ( $args['hierarchical'] )
  372. $args['meta_box_cb'] = 'post_categories_meta_box';
  373. else
  374. $args['meta_box_cb'] = 'post_tags_meta_box';
  375. }
  376. $wp_taxonomies[ $taxonomy ] = (object) $args;
  377. // register callback handling for metabox
  378. add_filter( 'wp_ajax_add-' . $taxonomy, '_wp_ajax_add_hierarchical_term' );
  379. /**
  380. * Fires after a taxonomy is registered.
  381. *
  382. * @since 3.3.0
  383. *
  384. * @param string $taxonomy Taxonomy slug.
  385. * @param array|string $object_type Object type or array of object types.
  386. * @param array|string $args Array or string of taxonomy registration arguments.
  387. */
  388. do_action( 'registered_taxonomy', $taxonomy, $object_type, $args );
  389. }
  390. /**
  391. * Builds an object with all taxonomy labels out of a taxonomy object
  392. *
  393. * Accepted keys of the label array in the taxonomy object:
  394. * - name - general name for the taxonomy, usually plural. The same as and overridden by $tax->label. Default is Tags/Categories
  395. * - singular_name - name for one object of this taxonomy. Default is Tag/Category
  396. * - search_items - Default is Search Tags/Search Categories
  397. * - popular_items - This string isn't used on hierarchical taxonomies. Default is Popular Tags
  398. * - all_items - Default is All Tags/All Categories
  399. * - parent_item - This string isn't used on non-hierarchical taxonomies. In hierarchical ones the default is Parent Category
  400. * - parent_item_colon - The same as <code>parent_item</code>, but with colon <code>:</code> in the end
  401. * - edit_item - Default is Edit Tag/Edit Category
  402. * - view_item - Default is View Tag/View Category
  403. * - update_item - Default is Update Tag/Update Category
  404. * - add_new_item - Default is Add New Tag/Add New Category
  405. * - new_item_name - Default is New Tag Name/New Category Name
  406. * - separate_items_with_commas - This string isn't used on hierarchical taxonomies. Default is "Separate tags with commas", used in the meta box.
  407. * - 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.
  408. * - 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.
  409. * - not_found - This string isn't used on hierarchical taxonomies. Default is "No tags found", used in the meta box.
  410. *
  411. * Above, the first default value is for non-hierarchical taxonomies (like tags) and the second one is for hierarchical taxonomies (like categories).
  412. *
  413. * @since 3.0.0
  414. * @param object $tax Taxonomy object
  415. * @return object object with all the labels as member variables
  416. */
  417. function get_taxonomy_labels( $tax ) {
  418. $tax->labels = (array) $tax->labels;
  419. if ( isset( $tax->helps ) && empty( $tax->labels['separate_items_with_commas'] ) )
  420. $tax->labels['separate_items_with_commas'] = $tax->helps;
  421. if ( isset( $tax->no_tagcloud ) && empty( $tax->labels['not_found'] ) )
  422. $tax->labels['not_found'] = $tax->no_tagcloud;
  423. $nohier_vs_hier_defaults = array(
  424. 'name' => array( _x( 'Tags', 'taxonomy general name' ), _x( 'Categories', 'taxonomy general name' ) ),
  425. 'singular_name' => array( _x( 'Tag', 'taxonomy singular name' ), _x( 'Category', 'taxonomy singular name' ) ),
  426. 'search_items' => array( __( 'Search Tags' ), __( 'Search Categories' ) ),
  427. 'popular_items' => array( __( 'Popular Tags' ), null ),
  428. 'all_items' => array( __( 'All Tags' ), __( 'All Categories' ) ),
  429. 'parent_item' => array( null, __( 'Parent Category' ) ),
  430. 'parent_item_colon' => array( null, __( 'Parent Category:' ) ),
  431. 'edit_item' => array( __( 'Edit Tag' ), __( 'Edit Category' ) ),
  432. 'view_item' => array( __( 'View Tag' ), __( 'View Category' ) ),
  433. 'update_item' => array( __( 'Update Tag' ), __( 'Update Category' ) ),
  434. 'add_new_item' => array( __( 'Add New Tag' ), __( 'Add New Category' ) ),
  435. 'new_item_name' => array( __( 'New Tag Name' ), __( 'New Category Name' ) ),
  436. 'separate_items_with_commas' => array( __( 'Separate tags with commas' ), null ),
  437. 'add_or_remove_items' => array( __( 'Add or remove tags' ), null ),
  438. 'choose_from_most_used' => array( __( 'Choose from the most used tags' ), null ),
  439. 'not_found' => array( __( 'No tags found.' ), null ),
  440. );
  441. $nohier_vs_hier_defaults['menu_name'] = $nohier_vs_hier_defaults['name'];
  442. return _get_custom_object_labels( $tax, $nohier_vs_hier_defaults );
  443. }
  444. /**
  445. * Add an already registered taxonomy to an object type.
  446. *
  447. * @since 3.0.0
  448. * @uses $wp_taxonomies Modifies taxonomy object
  449. *
  450. * @param string $taxonomy Name of taxonomy object
  451. * @param string $object_type Name of the object type
  452. * @return bool True if successful, false if not
  453. */
  454. function register_taxonomy_for_object_type( $taxonomy, $object_type) {
  455. global $wp_taxonomies;
  456. if ( !isset($wp_taxonomies[$taxonomy]) )
  457. return false;
  458. if ( ! get_post_type_object($object_type) )
  459. return false;
  460. if ( ! in_array( $object_type, $wp_taxonomies[$taxonomy]->object_type ) )
  461. $wp_taxonomies[$taxonomy]->object_type[] = $object_type;
  462. return true;
  463. }
  464. /**
  465. * Remove an already registered taxonomy from an object type.
  466. *
  467. * @since 3.7.0
  468. *
  469. * @param string $taxonomy Name of taxonomy object.
  470. * @param string $object_type Name of the object type.
  471. * @return bool True if successful, false if not.
  472. */
  473. function unregister_taxonomy_for_object_type( $taxonomy, $object_type ) {
  474. global $wp_taxonomies;
  475. if ( ! isset( $wp_taxonomies[ $taxonomy ] ) )
  476. return false;
  477. if ( ! get_post_type_object( $object_type ) )
  478. return false;
  479. $key = array_search( $object_type, $wp_taxonomies[ $taxonomy ]->object_type, true );
  480. if ( false === $key )
  481. return false;
  482. unset( $wp_taxonomies[ $taxonomy ]->object_type[ $key ] );
  483. return true;
  484. }
  485. //
  486. // Term API
  487. //
  488. /**
  489. * Retrieve object_ids of valid taxonomy and term.
  490. *
  491. * The strings of $taxonomies must exist before this function will continue. On
  492. * failure of finding a valid taxonomy, it will return an WP_Error class, kind
  493. * of like Exceptions in PHP 5, except you can't catch them. Even so, you can
  494. * still test for the WP_Error class and get the error message.
  495. *
  496. * The $terms aren't checked the same as $taxonomies, but still need to exist
  497. * for $object_ids to be returned.
  498. *
  499. * It is possible to change the order that object_ids is returned by either
  500. * using PHP sort family functions or using the database by using $args with
  501. * either ASC or DESC array. The value should be in the key named 'order'.
  502. *
  503. * @since 2.3.0
  504. *
  505. * @uses $wpdb
  506. * @uses wp_parse_args() Creates an array from string $args.
  507. *
  508. * @param int|array $term_ids Term id or array of term ids of terms that will be used
  509. * @param string|array $taxonomies String of taxonomy name or Array of string values of taxonomy names
  510. * @param array|string $args Change the order of the object_ids, either ASC or DESC
  511. * @return WP_Error|array If the taxonomy does not exist, then WP_Error will be returned. On success
  512. * the array can be empty meaning that there are no $object_ids found or it will return the $object_ids found.
  513. */
  514. function get_objects_in_term( $term_ids, $taxonomies, $args = array() ) {
  515. global $wpdb;
  516. if ( ! is_array( $term_ids ) )
  517. $term_ids = array( $term_ids );
  518. if ( ! is_array( $taxonomies ) )
  519. $taxonomies = array( $taxonomies );
  520. foreach ( (array) $taxonomies as $taxonomy ) {
  521. if ( ! taxonomy_exists( $taxonomy ) )
  522. return new WP_Error( 'invalid_taxonomy', __( 'Invalid taxonomy' ) );
  523. }
  524. $defaults = array( 'order' => 'ASC' );
  525. $args = wp_parse_args( $args, $defaults );
  526. extract( $args, EXTR_SKIP );
  527. $order = ( 'desc' == strtolower( $order ) ) ? 'DESC' : 'ASC';
  528. $term_ids = array_map('intval', $term_ids );
  529. $taxonomies = "'" . implode( "', '", $taxonomies ) . "'";
  530. $term_ids = "'" . implode( "', '", $term_ids ) . "'";
  531. $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");
  532. if ( ! $object_ids )
  533. return array();
  534. return $object_ids;
  535. }
  536. /**
  537. * Given a taxonomy query, generates SQL to be appended to a main query.
  538. *
  539. * @since 3.1.0
  540. *
  541. * @see WP_Tax_Query
  542. *
  543. * @param array $tax_query A compact tax query
  544. * @param string $primary_table
  545. * @param string $primary_id_column
  546. * @return array
  547. */
  548. function get_tax_sql( $tax_query, $primary_table, $primary_id_column ) {
  549. $tax_query_obj = new WP_Tax_Query( $tax_query );
  550. return $tax_query_obj->get_sql( $primary_table, $primary_id_column );
  551. }
  552. /**
  553. * Container class for a multiple taxonomy query.
  554. *
  555. * @since 3.1.0
  556. */
  557. class WP_Tax_Query {
  558. /**
  559. * List of taxonomy queries. A single taxonomy query is an associative array:
  560. * - 'taxonomy' string The taxonomy being queried
  561. * - 'terms' string|array The list of terms
  562. * - 'field' string (optional) Which term field is being used.
  563. * Possible values: 'term_id', 'slug' or 'name'
  564. * Default: 'term_id'
  565. * - 'operator' string (optional)
  566. * Possible values: 'AND', 'IN' or 'NOT IN'.
  567. * Default: 'IN'
  568. * - 'include_children' bool (optional) Whether to include child terms.
  569. * Default: true
  570. *
  571. * @since 3.1.0
  572. * @access public
  573. * @var array
  574. */
  575. public $queries = array();
  576. /**
  577. * The relation between the queries. Can be one of 'AND' or 'OR'.
  578. *
  579. * @since 3.1.0
  580. * @access public
  581. * @var string
  582. */
  583. public $relation;
  584. /**
  585. * Standard response when the query should not return any rows.
  586. *
  587. * @since 3.2.0
  588. * @access private
  589. * @var string
  590. */
  591. private static $no_results = array( 'join' => '', 'where' => ' AND 0 = 1' );
  592. /**
  593. * Constructor.
  594. *
  595. * Parses a compact tax query and sets defaults.
  596. *
  597. * @since 3.1.0
  598. * @access public
  599. *
  600. * @param array $tax_query A compact tax query:
  601. * array(
  602. * 'relation' => 'OR',
  603. * array(
  604. * 'taxonomy' => 'tax1',
  605. * 'terms' => array( 'term1', 'term2' ),
  606. * 'field' => 'slug',
  607. * ),
  608. * array(
  609. * 'taxonomy' => 'tax2',
  610. * 'terms' => array( 'term-a', 'term-b' ),
  611. * 'field' => 'slug',
  612. * ),
  613. * )
  614. */
  615. public function __construct( $tax_query ) {
  616. if ( isset( $tax_query['relation'] ) && strtoupper( $tax_query['relation'] ) == 'OR' ) {
  617. $this->relation = 'OR';
  618. } else {
  619. $this->relation = 'AND';
  620. }
  621. $defaults = array(
  622. 'taxonomy' => '',
  623. 'terms' => array(),
  624. 'include_children' => true,
  625. 'field' => 'term_id',
  626. 'operator' => 'IN',
  627. );
  628. foreach ( $tax_query as $query ) {
  629. if ( ! is_array( $query ) )
  630. continue;
  631. $query = array_merge( $defaults, $query );
  632. $query['terms'] = (array) $query['terms'];
  633. $this->queries[] = $query;
  634. }
  635. }
  636. /**
  637. * Generates SQL clauses to be appended to a main query.
  638. *
  639. * @since 3.1.0
  640. * @access public
  641. *
  642. * @param string $primary_table
  643. * @param string $primary_id_column
  644. * @return array
  645. */
  646. public function get_sql( $primary_table, $primary_id_column ) {
  647. global $wpdb;
  648. $join = '';
  649. $where = array();
  650. $i = 0;
  651. $count = count( $this->queries );
  652. foreach ( $this->queries as $index => $query ) {
  653. $this->clean_query( $query );
  654. if ( is_wp_error( $query ) )
  655. return self::$no_results;
  656. extract( $query );
  657. if ( 'IN' == $operator ) {
  658. if ( empty( $terms ) ) {
  659. if ( 'OR' == $this->relation ) {
  660. if ( ( $index + 1 === $count ) && empty( $where ) )
  661. return self::$no_results;
  662. continue;
  663. } else {
  664. return self::$no_results;
  665. }
  666. }
  667. $terms = implode( ',', $terms );
  668. $alias = $i ? 'tt' . $i : $wpdb->term_relationships;
  669. $join .= " INNER JOIN $wpdb->term_relationships";
  670. $join .= $i ? " AS $alias" : '';
  671. $join .= " ON ($primary_table.$primary_id_column = $alias.object_id)";
  672. $where[] = "$alias.term_taxonomy_id $operator ($terms)";
  673. } elseif ( 'NOT IN' == $operator ) {
  674. if ( empty( $terms ) )
  675. continue;
  676. $terms = implode( ',', $terms );
  677. $where[] = "$primary_table.$primary_id_column NOT IN (
  678. SELECT object_id
  679. FROM $wpdb->term_relationships
  680. WHERE term_taxonomy_id IN ($terms)
  681. )";
  682. } elseif ( 'AND' == $operator ) {
  683. if ( empty( $terms ) )
  684. continue;
  685. $num_terms = count( $terms );
  686. $terms = implode( ',', $terms );
  687. $where[] = "(
  688. SELECT COUNT(1)
  689. FROM $wpdb->term_relationships
  690. WHERE term_taxonomy_id IN ($terms)
  691. AND object_id = $primary_table.$primary_id_column
  692. ) = $num_terms";
  693. }
  694. $i++;
  695. }
  696. if ( ! empty( $where ) )
  697. $where = ' AND ( ' . implode( " $this->relation ", $where ) . ' )';
  698. else
  699. $where = '';
  700. return compact( 'join', 'where' );
  701. }
  702. /**
  703. * Validates a single query.
  704. *
  705. * @since 3.2.0
  706. * @access private
  707. *
  708. * @param array &$query The single query
  709. */
  710. private function clean_query( &$query ) {
  711. if ( ! taxonomy_exists( $query['taxonomy'] ) ) {
  712. $query = new WP_Error( 'Invalid taxonomy' );
  713. return;
  714. }
  715. $query['terms'] = array_unique( (array) $query['terms'] );
  716. if ( is_taxonomy_hierarchical( $query['taxonomy'] ) && $query['include_children'] ) {
  717. $this->transform_query( $query, 'term_id' );
  718. if ( is_wp_error( $query ) )
  719. return;
  720. $children = array();
  721. foreach ( $query['terms'] as $term ) {
  722. $children = array_merge( $children, get_term_children( $term, $query['taxonomy'] ) );
  723. $children[] = $term;
  724. }
  725. $query['terms'] = $children;
  726. }
  727. $this->transform_query( $query, 'term_taxonomy_id' );
  728. }
  729. /**
  730. * Transforms a single query, from one field to another.
  731. *
  732. * @since 3.2.0
  733. *
  734. * @param array &$query The single query
  735. * @param string $resulting_field The resulting field
  736. */
  737. public function transform_query( &$query, $resulting_field ) {
  738. global $wpdb;
  739. if ( empty( $query['terms'] ) )
  740. return;
  741. if ( $query['field'] == $resulting_field )
  742. return;
  743. $resulting_field = sanitize_key( $resulting_field );
  744. switch ( $query['field'] ) {
  745. case 'slug':
  746. case 'name':
  747. $terms = "'" . implode( "','", array_map( 'sanitize_title_for_query', $query['terms'] ) ) . "'";
  748. $terms = $wpdb->get_col( "
  749. SELECT $wpdb->term_taxonomy.$resulting_field
  750. FROM $wpdb->term_taxonomy
  751. INNER JOIN $wpdb->terms USING (term_id)
  752. WHERE taxonomy = '{$query['taxonomy']}'
  753. AND $wpdb->terms.{$query['field']} IN ($terms)
  754. " );
  755. break;
  756. case 'term_taxonomy_id':
  757. $terms = implode( ',', array_map( 'intval', $query['terms'] ) );
  758. $terms = $wpdb->get_col( "
  759. SELECT $resulting_field
  760. FROM $wpdb->term_taxonomy
  761. WHERE term_taxonomy_id IN ($terms)
  762. " );
  763. break;
  764. default:
  765. $terms = implode( ',', array_map( 'intval', $query['terms'] ) );
  766. $terms = $wpdb->get_col( "
  767. SELECT $resulting_field
  768. FROM $wpdb->term_taxonomy
  769. WHERE taxonomy = '{$query['taxonomy']}'
  770. AND term_id IN ($terms)
  771. " );
  772. }
  773. if ( 'AND' == $query['operator'] && count( $terms ) < count( $query['terms'] ) ) {
  774. $query = new WP_Error( 'Inexistent terms' );
  775. return;
  776. }
  777. $query['terms'] = $terms;
  778. $query['field'] = $resulting_field;
  779. }
  780. }
  781. /**
  782. * Get all Term data from database by Term ID.
  783. *
  784. * The usage of the get_term function is to apply filters to a term object. It
  785. * is possible to get a term object from the database before applying the
  786. * filters.
  787. *
  788. * $term ID must be part of $taxonomy, to get from the database. Failure, might
  789. * be able to be captured by the hooks. Failure would be the same value as $wpdb
  790. * returns for the get_row method.
  791. *
  792. * There are two hooks, one is specifically for each term, named 'get_term', and
  793. * the second is for the taxonomy name, 'term_$taxonomy'. Both hooks gets the
  794. * term object, and the taxonomy name as parameters. Both hooks are expected to
  795. * return a Term object.
  796. *
  797. * 'get_term' hook - Takes two parameters the term Object and the taxonomy name.
  798. * Must return term object. Used in get_term() as a catch-all filter for every
  799. * $term.
  800. *
  801. * 'get_$taxonomy' hook - Takes two parameters the term Object and the taxonomy
  802. * name. Must return term object. $taxonomy will be the taxonomy name, so for
  803. * example, if 'category', it would be 'get_category' as the filter name. Useful
  804. * for custom taxonomies or plugging into default taxonomies.
  805. *
  806. * @since 2.3.0
  807. *
  808. * @uses $wpdb
  809. * @uses sanitize_term() Cleanses the term based on $filter context before returning.
  810. * @see sanitize_term_field() The $context param lists the available values for get_term_by() $filter param.
  811. *
  812. * @param int|object $term If integer, will get from database. If object will apply filters and return $term.
  813. * @param string $taxonomy Taxonomy name that $term is part of.
  814. * @param string $output Constant OBJECT, ARRAY_A, or ARRAY_N
  815. * @param string $filter Optional, default is raw or no WordPress defined filter will applied.
  816. * @return mixed|null|WP_Error Term Row from database. Will return null if $term is empty. If taxonomy does not
  817. * exist then WP_Error will be returned.
  818. */
  819. function get_term($term, $taxonomy, $output = OBJECT, $filter = 'raw') {
  820. global $wpdb;
  821. if ( empty($term) ) {
  822. $error = new WP_Error('invalid_term', __('Empty Term'));
  823. return $error;
  824. }
  825. if ( ! taxonomy_exists($taxonomy) ) {
  826. $error = new WP_Error('invalid_taxonomy', __('Invalid taxonomy'));
  827. return $error;
  828. }
  829. if ( is_object($term) && empty($term->filter) ) {
  830. wp_cache_add($term->term_id, $term, $taxonomy);
  831. $_term = $term;
  832. } else {
  833. if ( is_object($term) )
  834. $term = $term->term_id;
  835. if ( !$term = (int) $term )
  836. return null;
  837. if ( ! $_term = wp_cache_get($term, $taxonomy) ) {
  838. $_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) );
  839. if ( ! $_term )
  840. return null;
  841. wp_cache_add($term, $_term, $taxonomy);
  842. }
  843. }
  844. /**
  845. * Filter a term.
  846. *
  847. * @since 2.3.0
  848. *
  849. * @param int|object $_term Term object or ID.
  850. * @param string $taxonomy The taxonomy slug.
  851. */
  852. $_term = apply_filters( 'get_term', $_term, $taxonomy );
  853. /**
  854. * Filter a taxonomy.
  855. *
  856. * The dynamic portion of the filter name, $taxonomy, refers
  857. * to the taxonomy slug.
  858. *
  859. * @since 2.3.0
  860. *
  861. * @param int|object $_term Term object or ID.
  862. * @param string $taxonomy The taxonomy slug.
  863. */
  864. $_term = apply_filters( "get_$taxonomy", $_term, $taxonomy );
  865. $_term = sanitize_term($_term, $taxonomy, $filter);
  866. if ( $output == OBJECT ) {
  867. return $_term;
  868. } elseif ( $output == ARRAY_A ) {
  869. $__term = get_object_vars($_term);
  870. return $__term;
  871. } elseif ( $output == ARRAY_N ) {
  872. $__term = array_values(get_object_vars($_term));
  873. return $__term;
  874. } else {
  875. return $_term;
  876. }
  877. }
  878. /**
  879. * Get all Term data from database by Term field and data.
  880. *
  881. * Warning: $value is not escaped for 'name' $field. You must do it yourself, if
  882. * required.
  883. *
  884. * The default $field is 'id', therefore it is possible to also use null for
  885. * field, but not recommended that you do so.
  886. *
  887. * If $value does not exist, the return value will be false. If $taxonomy exists
  888. * and $field and $value combinations exist, the Term will be returned.
  889. *
  890. * @since 2.3.0
  891. *
  892. * @uses $wpdb
  893. * @uses sanitize_term() Cleanses the term based on $filter context before returning.
  894. * @see sanitize_term_field() The $context param lists the available values for get_term_by() $filter param.
  895. *
  896. * @param string $field Either 'slug', 'name', 'id' (term_id), or 'term_taxonomy_id'
  897. * @param string|int $value Search for this term value
  898. * @param string $taxonomy Taxonomy Name
  899. * @param string $output Constant OBJECT, ARRAY_A, or ARRAY_N
  900. * @param string $filter Optional, default is raw or no WordPress defined filter will applied.
  901. * @return mixed Term Row from database. Will return false if $taxonomy does not exist or $term was not found.
  902. */
  903. function get_term_by($field, $value, $taxonomy, $output = OBJECT, $filter = 'raw') {
  904. global $wpdb;
  905. if ( ! taxonomy_exists($taxonomy) )
  906. return false;
  907. if ( 'slug' == $field ) {
  908. $field = 't.slug';
  909. $value = sanitize_title($value);
  910. if ( empty($value) )
  911. return false;
  912. } else if ( 'name' == $field ) {
  913. // Assume already escaped
  914. $value = wp_unslash($value);
  915. $field = 't.name';
  916. } else if ( 'term_taxonomy_id' == $field ) {
  917. $value = (int) $value;
  918. $field = 'tt.term_taxonomy_id';
  919. } else {
  920. $term = get_term( (int) $value, $taxonomy, $output, $filter);
  921. if ( is_wp_error( $term ) )
  922. $term = false;
  923. return $term;
  924. }
  925. $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) );
  926. if ( !$term )
  927. return false;
  928. wp_cache_add($term->term_id, $term, $taxonomy);
  929. /** This filter is documented in wp-includes/taxonomy.php */
  930. $term = apply_filters( 'get_term', $term, $taxonomy );
  931. /** This filter is documented in wp-includes/taxonomy.php */
  932. $term = apply_filters( "get_$taxonomy", $term, $taxonomy );
  933. $term = sanitize_term($term, $taxonomy, $filter);
  934. if ( $output == OBJECT ) {
  935. return $term;
  936. } elseif ( $output == ARRAY_A ) {
  937. return get_object_vars($term);
  938. } elseif ( $output == ARRAY_N ) {
  939. return array_values(get_object_vars($term));
  940. } else {
  941. return $term;
  942. }
  943. }
  944. /**
  945. * Merge all term children into a single array of their IDs.
  946. *
  947. * This recursive function will merge all of the children of $term into the same
  948. * array of term IDs. Only useful for taxonomies which are hierarchical.
  949. *
  950. * Will return an empty array if $term does not exist in $taxonomy.
  951. *
  952. * @since 2.3.0
  953. *
  954. * @uses $wpdb
  955. * @uses _get_term_hierarchy()
  956. * @uses get_term_children() Used to get the children of both $taxonomy and the parent $term
  957. *
  958. * @param string $term_id ID of Term to get children
  959. * @param string $taxonomy Taxonomy Name
  960. * @return array|WP_Error List of Term IDs. WP_Error returned if $taxonomy does not exist
  961. */
  962. function get_term_children( $term_id, $taxonomy ) {
  963. if ( ! taxonomy_exists($taxonomy) )
  964. return new WP_Error('invalid_taxonomy', __('Invalid taxonomy'));
  965. $term_id = intval( $term_id );
  966. $terms = _get_term_hierarchy($taxonomy);
  967. if ( ! isset($terms[$term_id]) )
  968. return array();
  969. $children = $terms[$term_id];
  970. foreach ( (array) $terms[$term_id] as $child ) {
  971. if ( $term_id == $child ) {
  972. continue;
  973. }
  974. if ( isset($terms[$child]) )
  975. $children = array_merge($children, get_term_children($child, $taxonomy));
  976. }
  977. return $children;
  978. }
  979. /**
  980. * Get sanitized Term field.
  981. *
  982. * Does checks for $term, based on the $taxonomy. The function is for contextual
  983. * reasons and for simplicity of usage. See sanitize_term_field() for more
  984. * information.
  985. *
  986. * @since 2.3.0
  987. *
  988. * @uses sanitize_term_field() Passes the return value in sanitize_term_field on success.
  989. *
  990. * @param string $field Term field to fetch
  991. * @param int $term Term ID
  992. * @param string $taxonomy Taxonomy Name
  993. * @param string $context Optional, default is display. Look at sanitize_term_field() for available options.
  994. * @return mixed Will return an empty string if $term is not an object or if $field is not set in $term.
  995. */
  996. function get_term_field( $field, $term, $taxonomy, $context = 'display' ) {
  997. $term = (int) $term;
  998. $term = get_term( $term, $taxonomy );
  999. if ( is_wp_error($term) )
  1000. return $term;
  1001. if ( !is_object($term) )
  1002. return '';
  1003. if ( !isset($term->$field) )
  1004. return '';
  1005. return sanitize_term_field($field, $term->$field, $term->term_id, $taxonomy, $context);
  1006. }
  1007. /**
  1008. * Sanitizes Term for editing.
  1009. *
  1010. * Return value is sanitize_term() and usage is for sanitizing the term for
  1011. * editing. Function is for contextual and simplicity.
  1012. *
  1013. * @since 2.3.0
  1014. *
  1015. * @uses sanitize_term() Passes the return value on success
  1016. *
  1017. * @param int|object $id Term ID or Object
  1018. * @param string $taxonomy Taxonomy Name
  1019. * @return mixed|null|WP_Error Will return empty string if $term is not an object.
  1020. */
  1021. function get_term_to_edit( $id, $taxonomy ) {
  1022. $term = get_term( $id, $taxonomy );
  1023. if ( is_wp_error($term) )
  1024. return $term;
  1025. if ( !is_object($term) )
  1026. return '';
  1027. return sanitize_term($term, $taxonomy, 'edit');
  1028. }
  1029. /**
  1030. * Retrieve the terms in a given taxonomy or list of taxonomies.
  1031. *
  1032. * You can fully inject any customizations to the query before it is sent, as
  1033. * well as control the output with a filter.
  1034. *
  1035. * The 'get_terms' filter will be called when the cache has the term and will
  1036. * pass the found term along with the array of $taxonomies and array of $args.
  1037. * This filter is also called before the array of terms is passed and will pass
  1038. * the array of terms, along with the $taxonomies and $args.
  1039. *
  1040. * The 'list_terms_exclusions' filter passes the compiled exclusions along with
  1041. * the $args.
  1042. *
  1043. * The 'get_terms_orderby' filter passes the ORDER BY clause for the query
  1044. * along with the $args array.
  1045. *
  1046. * The 'get_terms_fields' filter passes the fields for the SELECT query
  1047. * along with the $args array.
  1048. *
  1049. * The list of arguments that $args can contain, which will overwrite the defaults:
  1050. *
  1051. * orderby - Default is 'name'. Can be name, count, term_group, slug or nothing
  1052. * (will use term_id), Passing a custom value other than these will cause it to
  1053. * order based on the custom value.
  1054. *
  1055. * order - Default is ASC. Can use DESC.
  1056. *
  1057. * hide_empty - Default is true. Will not return empty terms, which means
  1058. * terms whose count is 0 according to the given taxonomy.
  1059. *
  1060. * exclude - Default is an empty array. An array, comma- or space-delimited string
  1061. * of term ids to exclude from the return array. If 'include' is non-empty,
  1062. * 'exclude' is ignored.
  1063. *
  1064. * exclude_tree - Default is an empty array. An array, comma- or space-delimited
  1065. * string of term ids to exclude from the return array, along with all of their
  1066. * descendant terms according to the primary taxonomy. If 'include' is non-empty,
  1067. * 'exclude_tree' is ignored.
  1068. *
  1069. * include - Default is an empty array. An array, comma- or space-delimited string
  1070. * of term ids to include in the return array.
  1071. *
  1072. * number - The maximum number of terms to return. Default is to return them all.
  1073. *
  1074. * offset - The number by which to offset the terms query.
  1075. *
  1076. * fields - Default is 'all', which returns an array of term objects.
  1077. * If 'fields' is 'ids' or 'names', returns an array of
  1078. * integers or strings, respectively.
  1079. *
  1080. * slug - Returns terms whose "slug" matches this value. Default is empty string.
  1081. *
  1082. * hierarchical - Whether to include terms that have non-empty descendants
  1083. * (even if 'hide_empty' is set to true).
  1084. *
  1085. * search - Returned terms' names will contain the value of 'search',
  1086. * case-insensitive. Default is an empty string.
  1087. *
  1088. * name__like - Returned terms' names will contain the value of 'name__like',
  1089. * case-insensitive. Default is empty string.
  1090. *
  1091. * description__like - Returned terms' descriptions will contain the value of
  1092. * 'description__like', case-insensitive. Default is empty string.
  1093. *
  1094. * The argument 'pad_counts', if set to true will include the quantity of a term's
  1095. * children in the quantity of each term's "count" object variable.
  1096. *
  1097. * The 'get' argument, if set to 'all' instead of its default empty string,
  1098. * returns terms regardless of ancestry or whether the terms are empty.
  1099. *
  1100. * The 'child_of' argument, when used, should be set to the integer of a term ID. Its default
  1101. * is 0. If set to a non-zero value, all returned terms will be descendants
  1102. * of that term according to the given taxonomy. Hence 'child_of' is set to 0
  1103. * if more than one taxonomy is passed in $taxonomies, because multiple taxonomies
  1104. * make term ancestry ambiguous.
  1105. *
  1106. * The 'parent' argument, when used, should be set to the integer of a term ID. Its default is
  1107. * the empty string '', which has a different meaning from the integer 0.
  1108. * If set to an integer value, all returned terms will have as an immediate
  1109. * ancestor the term whose ID is specified by that integer according to the given taxonomy.
  1110. * The 'parent' argument is different from 'child_of' in that a term X is considered a 'parent'
  1111. * of term Y only if term X is the father of term Y, not its grandfather or great-grandfather, etc.
  1112. *
  1113. * The 'cache_domain' argument enables a unique cache key to be produced when this query is stored
  1114. * in object cache. For instance, if you are using one of this function's filters to modify the
  1115. * query (such as 'terms_clauses'), setting 'cache_domain' to a unique value will not overwrite
  1116. * the cache for similar queries. Default value is 'core'.
  1117. *
  1118. * @since 2.3.0
  1119. *
  1120. * @uses $wpdb
  1121. * @uses wp_parse_args() Merges the defaults with those defined by $args and allows for strings.
  1122. *
  1123. * @param string|array $taxonomies Taxonomy name or list of Taxonomy names
  1124. * @param string|array $args The values of what to search for when returning terms
  1125. * @return array|WP_Error List of Term Objects and their children. Will return WP_Error, if any of $taxonomies do not exist.
  1126. */
  1127. function get_terms($taxonomies, $args = '') {
  1128. global $wpdb;
  1129. $empty_array = array();
  1130. $single_taxonomy = ! is_array( $taxonomies ) || 1 === count( $taxonomies );
  1131. if ( ! is_array( $taxonomies ) )
  1132. $taxonomies = array( $taxonomies );
  1133. foreach ( $taxonomies as $taxonomy ) {
  1134. if ( ! taxonomy_exists($taxonomy) ) {
  1135. $error = new WP_Error('invalid_taxonomy', __('Invalid taxonomy'));
  1136. return $error;
  1137. }
  1138. }
  1139. $defaults = array('orderby' => 'name', 'order' => 'ASC',
  1140. 'hide_empty' => true, 'exclude' => array(), 'exclude_tree' => array(), 'include' => array(),
  1141. 'number' => '', 'fields' => 'all', 'slug' => '', 'parent' => '',
  1142. 'hierarchical' => true, 'child_of' => 0, 'get' => '', 'name__like' => '', 'description__like' => '',
  1143. 'pad_counts' => false, 'offset' => '', 'search' => '', 'cache_domain' => 'core' );
  1144. $args = wp_parse_args( $args, $defaults );
  1145. $args['number'] = absint( $args['number'] );
  1146. $args['offset'] = absint( $args['offset'] );
  1147. if ( !$single_taxonomy || ! is_taxonomy_hierarchical( reset( $taxonomies ) ) ||
  1148. ( '' !== $args['parent'] && 0 !== $args['parent'] ) ) {
  1149. $args['child_of'] = 0;
  1150. $args['hierarchical'] = false;
  1151. $args['pad_counts'] = false;
  1152. }
  1153. if ( 'all' == $args['get'] ) {
  1154. $args['child_of'] = 0;
  1155. $args['hide_empty'] = 0;
  1156. $args['hierarchical'] = false;
  1157. $args['pad_counts'] = false;
  1158. }
  1159. /**
  1160. * Filter the terms query arguments.
  1161. *
  1162. * @since 3.1.0
  1163. *
  1164. * @param array $args An array of arguments.
  1165. * @param string|array $taxonomies A taxonomy or array of taxonomies.
  1166. */
  1167. $args = apply_filters( 'get_terms_args', $args, $taxonomies );
  1168. extract($args, EXTR_SKIP);
  1169. if ( $child_of ) {
  1170. $hierarchy = _get_term_hierarchy( reset( $taxonomies ) );
  1171. if ( ! isset( $hierarchy[ $child_of ] ) )
  1172. return $empty_array;
  1173. }
  1174. if ( $parent ) {
  1175. $hierarchy = _get_term_hierarchy( reset( $taxonomies ) );
  1176. if ( ! isset( $hierarchy[ $parent ] ) )
  1177. return $empty_array;
  1178. }
  1179. // $args can be whatever, only use the args defined in defaults to compute the key
  1180. $filter_key = ( has_filter('list_terms_exclusions') ) ? serialize($GLOBALS['wp_filter']['list_terms_exclusions']) : '';
  1181. $key = md5( serialize( compact(array_keys($defaults)) ) . serialize( $taxonomies ) . $filter_key );
  1182. $last_changed = wp_cache_get( 'last_changed', 'terms' );
  1183. if ( ! $last_changed ) {
  1184. $last_changed = microtime();
  1185. wp_cache_set( 'last_changed', $last_changed, 'terms' );
  1186. }
  1187. $cache_key = "get_terms:$key:$last_changed";
  1188. $cache = wp_cache_get( $cache_key, 'terms' );
  1189. if ( false !== $cache ) {
  1190. /**
  1191. * Filter the given taxonomy's terms cache.
  1192. *
  1193. * @since 2.3.0
  1194. *
  1195. * @param array $cache Cached array of terms for the given taxonomy.
  1196. * @param string|array $taxonomies A taxonomy or array of taxonomies.
  1197. * @param array $args An array of arguments to get terms.
  1198. */
  1199. $cache = apply_filters( 'get_terms', $cache, $taxonomies, $args );
  1200. return $cache;
  1201. }
  1202. $_orderby = strtolower($orderby);
  1203. if ( 'count' == $_orderby )
  1204. $orderby = 'tt.count';
  1205. else if ( 'name' == $_orderby )
  1206. $orderby = 't.name';
  1207. else if ( 'slug' == $_orderby )
  1208. $orderby = 't.slug';
  1209. else if ( 'term_group' == $_orderby )
  1210. $orderby = 't.term_group';
  1211. else if ( 'none' == $_orderby )
  1212. $orderby = '';
  1213. elseif ( empty($_orderby) || 'id' == $_orderby )
  1214. $orderby = 't.term_id';
  1215. else
  1216. $orderby = 't.name';
  1217. /**
  1218. * Filter the ORDERBY clause of the terms query.
  1219. *
  1220. * @since 2.8.0
  1221. *
  1222. * @param string $orderby ORDERBY clause of the terms query.
  1223. * @param array $args An array of terms query arguments.
  1224. * @param string|array $taxonomies A taxonomy or array of taxonomies.
  1225. */
  1226. $orderby = apply_filters( 'get_terms_orderby', $orderby, $args, $taxonomies );
  1227. if ( !empty($orderby) )
  1228. $orderby = "ORDER BY $orderby";
  1229. else
  1230. $order = '';
  1231. $order = strtoupper( $order );
  1232. if ( '' !== $order && !in_array( $order, array( 'ASC', 'DESC' ) ) )
  1233. $order = 'ASC';
  1234. $where = "tt.taxonomy IN ('" . implode("', '", $taxonomies) . "')";
  1235. $inclusions = '';
  1236. if ( ! empty( $include ) ) {
  1237. $exclude = '';
  1238. $exclude_tree = '';
  1239. $inclusions = implode( ',', wp_parse_id_list( $include ) );
  1240. }
  1241. if ( ! empty( $inclusions ) ) {
  1242. $inclusions = ' AND t.term_id IN ( ' . $inclusions . ' )';
  1243. $where .= $inclusions;
  1244. }
  1245. $exclusions = '';
  1246. if ( ! empty( $exclude_tree ) ) {
  1247. $exclude_tree = wp_parse_id_list( $exclude_tree );
  1248. $excluded_children = $exclude_tree;
  1249. foreach ( $exclude_tree as $extrunk ) {
  1250. $excluded_children = array_merge(
  1251. $excluded_children,
  1252. (array) get_terms( $taxonomies[0], array( 'child_of' => intval( $extrunk ), 'fields' => 'ids', 'hide_empty' => 0 ) )
  1253. );
  1254. }
  1255. $exclusions = implode( ',', array_map( 'intval', $excluded_children ) );
  1256. }
  1257. if ( ! empty( $exclude ) ) {
  1258. $exterms = wp_parse_id_list( $exclude );
  1259. if ( empty( $exclusions ) )
  1260. $exclusions = implode( ',', $exterms );
  1261. else
  1262. $exclusions .= ', ' . implode( ',', $exterms );
  1263. }
  1264. if ( ! empty( $exclusions ) )
  1265. $exclusions = ' AND t.term_id NOT IN (' . $exclusions . ')';
  1266. /**
  1267. * Filter the terms to exclude from the terms query.
  1268. *
  1269. * @since 2.3.0
  1270. *
  1271. * @param string $exclusions NOT IN clause of the terms query.
  1272. * @param array $args An array of terms query arguments.
  1273. * @param string|array $taxonomies A taxonomy or array of taxonomies.
  1274. */
  1275. $exclusions = apply_filters( 'list_terms_exclusions', $exclusions, $args, $taxonomies );
  1276. if ( ! empty( $exclusions ) )
  1277. $where .= $exclusions;
  1278. if ( !empty($slug) ) {
  1279. $slug = sanitize_title($slug);
  1280. $where .= " AND t.slug = '$slug'";
  1281. }
  1282. if ( !empty($name__like) ) {
  1283. $name__like = like_escape( $name__like );
  1284. $where .= $wpdb->prepare( " AND t.name LIKE %s", '%' . $name__like . '%' );
  1285. }
  1286. if ( ! empty( $description__like ) ) {
  1287. $description__like = like_escape( $description__like );
  1288. $where .= $wpdb->prepare( " AND tt.description LIKE %s", '%' . $description__like . '%' );
  1289. }
  1290. if ( '' !== $parent ) {
  1291. $parent = (int) $parent;
  1292. $where .= " AND tt.parent = '$parent'";
  1293. }
  1294. if ( 'count' == $fields )
  1295. $hierarchical = false;
  1296. if ( $hide_empty && !$hierarchical )
  1297. $where .= ' AND tt.count > 0';
  1298. // don't limit the query results when we have to descend the family tree
  1299. if ( $number && ! $hierarchical && ! $child_of && '' === $parent ) {
  1300. if ( $offset )
  1301. $limits = 'LIMIT ' . $offset . ',' . $number;
  1302. else
  1303. $limits = 'LIMIT ' . $number;
  1304. } else {
  1305. $limits = '';
  1306. }
  1307. if ( ! empty( $search ) ) {
  1308. $search = like_escape( $search );
  1309. $where .= $wpdb->prepare( ' AND ((t.name LIKE %s) OR (t.slug LIKE %s))', '%' . $search . '%', '%' . $search . '%' );
  1310. }
  1311. $selects = array();
  1312. switch ( $fields ) {
  1313. case 'all':
  1314. $selects = array( 't.*', 'tt.…

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