PageRenderTime 69ms CodeModel.GetById 19ms RepoModel.GetById 0ms app.codeStats 1ms

/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
  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.*' );
  1315. break;
  1316. case 'ids':
  1317. case 'id=>parent':
  1318. $selects = array( 't.term_id', 'tt.parent', 'tt.count' );
  1319. break;
  1320. case 'names':
  1321. $selects = array( 't.term_id', 'tt.parent', 'tt.count', 't.name' );
  1322. break;
  1323. case 'count':
  1324. $orderby = '';
  1325. $order = '';
  1326. $selects = array( 'COUNT(*)' );
  1327. break;
  1328. case 'id=>name':
  1329. $selects = array( 't.term_id', 't.name' );
  1330. break;
  1331. case 'id=>slug':
  1332. $selects = array( 't.term_id', 't.slug' );
  1333. break;
  1334. }
  1335. $_fields = $fields;
  1336. /**
  1337. * Filter the fields to select in the terms query.
  1338. *
  1339. * @since 2.8.0
  1340. *
  1341. * @param array $selects An array of fields to select for the terms query.
  1342. * @param array $args An array of term query arguments.
  1343. * @param string|array $taxonomies A taxonomy or array of taxonomies.
  1344. */
  1345. $fields = implode( ', ', apply_filters( 'get_terms_fields', $selects, $args, $taxonomies ) );
  1346. $join = "INNER JOIN $wpdb->term_taxonomy AS tt ON t.term_id = tt.term_id";
  1347. $pieces = array( 'fields', 'join', 'where', 'orderby', 'order', 'limits' );
  1348. /**
  1349. * Filter the terms query SQL clauses.
  1350. *
  1351. * @since 3.1.0
  1352. *
  1353. * @param array $pieces Terms query SQL clauses.
  1354. * @param string|array $taxonomies A taxonomy or array of taxonomies.
  1355. * @param array $args An array of terms query arguments.
  1356. */
  1357. $clauses = apply_filters( 'terms_clauses', compact( $pieces ), $taxonomies, $args );
  1358. foreach ( $pieces as $piece )
  1359. $$piece = isset( $clauses[ $piece ] ) ? $clauses[ $piece ] : '';
  1360. $query = "SELECT $fields FROM $wpdb->terms AS t $join WHERE $where $orderby $order $limits";
  1361. $fields = $_fields;
  1362. if ( 'count' == $fields ) {
  1363. $term_count = $wpdb->get_var($query);
  1364. return $term_count;
  1365. }
  1366. $terms = $wpdb->get_results($query);
  1367. if ( 'all' == $fields ) {
  1368. update_term_cache($terms);
  1369. }
  1370. if ( empty($terms) ) {
  1371. wp_cache_add( $cache_key, array(), 'terms', DAY_IN_SECONDS );
  1372. /** This filter is documented in wp-includes/taxonomy.php */
  1373. $terms = apply_filters( 'get_terms', array(), $taxonomies, $args );
  1374. return $terms;
  1375. }
  1376. if ( $child_of ) {
  1377. $children = _get_term_hierarchy( reset( $taxonomies ) );
  1378. if ( ! empty( $children ) )
  1379. $terms = _get_term_children( $child_of, $terms, reset( $taxonomies ) );
  1380. }
  1381. // Update term counts to include children.
  1382. if ( $pad_counts && 'all' == $fields )
  1383. _pad_term_counts( $terms, reset( $taxonomies ) );
  1384. // Make sure we show empty categories that have children.
  1385. if ( $hierarchical && $hide_empty && is_array( $terms ) ) {
  1386. foreach ( $terms as $k => $term ) {
  1387. if ( ! $term->count ) {
  1388. $children = get_term_children( $term->term_id, reset( $taxonomies ) );
  1389. if ( is_array( $children ) ) {
  1390. foreach ( $children as $child_id ) {
  1391. $child = get_term( $child_id, reset( $taxonomies ) );
  1392. if ( $child->count ) {
  1393. continue 2;
  1394. }
  1395. }
  1396. }
  1397. // It really is empty
  1398. unset($terms[$k]);
  1399. }
  1400. }
  1401. }
  1402. reset( $terms );
  1403. $_terms = array();
  1404. if ( 'id=>parent' == $fields ) {
  1405. while ( $term = array_shift( $terms ) )
  1406. $_terms[$term->term_id] = $term->parent;
  1407. } elseif ( 'ids' == $fields ) {
  1408. while ( $term = array_shift( $terms ) )
  1409. $_terms[] = $term->term_id;
  1410. } elseif ( 'names' == $fields ) {
  1411. while ( $term = array_shift( $terms ) )
  1412. $_terms[] = $term->name;
  1413. } elseif ( 'id=>name' == $fields ) {
  1414. while ( $term = array_shift( $terms ) )
  1415. $_terms[$term->term_id] = $term->name;
  1416. } elseif ( 'id=>slug' == $fields ) {
  1417. while ( $term = array_shift( $terms ) )
  1418. $_terms[$term->term_id] = $term->slug;
  1419. }
  1420. if ( ! empty( $_terms ) )
  1421. $terms = $_terms;
  1422. if ( $number && is_array( $terms ) && count( $terms ) > $number )
  1423. $terms = array_slice( $terms, $offset, $number );
  1424. wp_cache_add( $cache_key, $terms, 'terms', DAY_IN_SECONDS );
  1425. /** This filter is documented in wp-includes/taxonomy */
  1426. $terms = apply_filters( 'get_terms', $terms, $taxonomies, $args );
  1427. return $terms;
  1428. }
  1429. /**
  1430. * Check if Term exists.
  1431. *
  1432. * Formerly is_term(), introduced in 2.3.0.
  1433. *
  1434. * @since 3.0.0
  1435. *
  1436. * @uses $wpdb
  1437. *
  1438. * @param int|string $term The term to check
  1439. * @param string $taxonomy The taxonomy name to use
  1440. * @param int $parent ID of parent term under which to confine the exists search.
  1441. * @return mixed Returns 0 if the term does not exist. Returns the term ID if no taxonomy is specified
  1442. * and the term ID exists. Returns an array of the term ID and the taxonomy if the pairing exists.
  1443. */
  1444. function term_exists($term, $taxonomy = '', $parent = 0) {
  1445. global $wpdb;
  1446. $select = "SELECT term_id FROM $wpdb->terms as t WHERE ";
  1447. $tax_select = "SELECT tt.term_id, tt.term_taxonomy_id FROM $wpdb->terms AS t INNER JOIN $wpdb->term_taxonomy as tt ON tt.term_id = t.term_id WHERE ";
  1448. if ( is_int($term) ) {
  1449. if ( 0 == $term )
  1450. return 0;
  1451. $where = 't.term_id = %d';
  1452. if ( !empty($taxonomy) )
  1453. return $wpdb->get_row( $wpdb->prepare( $tax_select . $where . " AND tt.taxonomy = %s", $term, $taxonomy ), ARRAY_A );
  1454. else
  1455. return $wpdb->get_var( $wpdb->prepare( $select . $where, $term ) );
  1456. }
  1457. $term = trim( wp_unslash( $term ) );
  1458. if ( '' === $slug = sanitize_title($term) )
  1459. return 0;
  1460. $where = 't.slug = %s';
  1461. $else_where = 't.name = %s';
  1462. $where_fields = array($slug);
  1463. $else_where_fields = array($term);
  1464. if ( !empty($taxonomy) ) {
  1465. $parent = (int) $parent;
  1466. if ( $parent > 0 ) {
  1467. $where_fields[] = $parent;
  1468. $else_where_fields[] = $parent;
  1469. $where .= ' AND tt.parent = %d';
  1470. $else_where .= ' AND tt.parent = %d';
  1471. }
  1472. $where_fields[] = $taxonomy;
  1473. $else_where_fields[] = $taxonomy;
  1474. if ( $result = $wpdb->get_row( $wpdb->prepare("SELECT tt.term_id, tt.term_taxonomy_id FROM $wpdb->terms AS t INNER JOIN $wpdb->term_taxonomy as tt ON tt.term_id = t.term_id WHERE $where AND tt.taxonomy = %s", $where_fields), ARRAY_A) )
  1475. return $result;
  1476. return $wpdb->get_row( $wpdb->prepare("SELECT tt.term_id, tt.term_taxonomy_id FROM $wpdb->terms AS t INNER JOIN $wpdb->term_taxonomy as tt ON tt.term_id = t.term_id WHERE $else_where AND tt.taxonomy = %s", $else_where_fields), ARRAY_A);
  1477. }
  1478. if ( $result = $wpdb->get_var( $wpdb->prepare("SELECT term_id FROM $wpdb->terms as t WHERE $where", $where_fields) ) )
  1479. return $result;
  1480. return $wpdb->get_var( $wpdb->prepare("SELECT term_id FROM $wpdb->terms as t WHERE $else_where", $else_where_fields) );
  1481. }
  1482. /**
  1483. * Check if a term is an ancestor of another term.
  1484. *
  1485. * You can use either an id or the term object for both parameters.
  1486. *
  1487. * @since 3.4.0
  1488. *
  1489. * @param int|object $term1 ID or object to check if this is the parent term.
  1490. * @param int|object $term2 The child term.
  1491. * @param string $taxonomy Taxonomy name that $term1 and $term2 belong to.
  1492. * @return bool Whether $term2 is child of $term1
  1493. */
  1494. function term_is_ancestor_of( $term1, $term2, $taxonomy ) {
  1495. if ( ! isset( $term1->term_id ) )
  1496. $term1 = get_term( $term1, $taxonomy );
  1497. if ( ! isset( $term2->parent ) )
  1498. $term2 = get_term( $term2, $taxonomy );
  1499. if ( empty( $term1->term_id ) || empty( $term2->parent ) )
  1500. return false;
  1501. if ( $term2->parent == $term1->term_id )
  1502. return true;
  1503. return term_is_ancestor_of( $term1, get_term( $term2->parent, $taxonomy ), $taxonomy );
  1504. }
  1505. /**
  1506. * Sanitize Term all fields.
  1507. *
  1508. * Relies on sanitize_term_field() to sanitize the term. The difference is that
  1509. * this function will sanitize <strong>all</strong> fields. The context is based
  1510. * on sanitize_term_field().
  1511. *
  1512. * The $term is expected to be either an array or an object.
  1513. *
  1514. * @since 2.3.0
  1515. *
  1516. * @uses sanitize_term_field Used to sanitize all fields in a term
  1517. *
  1518. * @param array|object $term The term to check
  1519. * @param string $taxonomy The taxonomy name to use
  1520. * @param string $context Default is 'display'.
  1521. * @return array|object Term with all fields sanitized
  1522. */
  1523. function sanitize_term($term, $taxonomy, $context = 'display') {
  1524. $fields = array( 'term_id', 'name', 'description', 'slug', 'count', 'parent', 'term_group', 'term_taxonomy_id', 'object_id' );
  1525. $do_object = is_object( $term );
  1526. $term_id = $do_object ? $term->term_id : (isset($term['term_id']) ? $term['term_id'] : 0);
  1527. foreach ( (array) $fields as $field ) {
  1528. if ( $do_object ) {
  1529. if ( isset($term->$field) )
  1530. $term->$field = sanitize_term_field($field, $term->$field, $term_id, $taxonomy, $context);
  1531. } else {
  1532. if ( isset($term[$field]) )
  1533. $term[$field] = sanitize_term_field($field, $term[$field], $term_id, $taxonomy, $context);
  1534. }
  1535. }
  1536. if ( $do_object )
  1537. $term->filter = $context;
  1538. else
  1539. $term['filter'] = $context;
  1540. return $term;
  1541. }
  1542. /**
  1543. * Cleanse the field value in the term based on the context.
  1544. *
  1545. * Passing a term field value through the function should be assumed to have
  1546. * cleansed the value for whatever context the term field is going to be used.
  1547. *
  1548. * If no context or an unsupported context is given, then default filters will
  1549. * be applied.
  1550. *
  1551. * There are enough filters for each context to support a custom filtering
  1552. * without creating your own filter function. Simply create a function that
  1553. * hooks into the filter you need.
  1554. *
  1555. * @since 2.3.0
  1556. *
  1557. * @uses $wpdb
  1558. *
  1559. * @param string $field Term field to sanitize
  1560. * @param string $value Search for this term value
  1561. * @param int $term_id Term ID
  1562. * @param string $taxonomy Taxonomy Name
  1563. * @param string $context Either edit, db, display, attribute, or js.
  1564. * @return mixed sanitized field
  1565. */
  1566. function sanitize_term_field($field, $value, $term_id, $taxonomy, $context) {
  1567. $int_fields = array( 'parent', 'term_id', 'count', 'term_group', 'term_taxonomy_id', 'object_id' );
  1568. if ( in_array( $field, $int_fields ) ) {
  1569. $value = (int) $value;
  1570. if ( $value < 0 )
  1571. $value = 0;
  1572. }
  1573. if ( 'raw' == $context )
  1574. return $value;
  1575. if ( 'edit' == $context ) {
  1576. /**
  1577. * Filter a term field to edit before it is sanitized.
  1578. *
  1579. * The dynamic portion of the filter name, $field, refers to the term field.
  1580. *
  1581. * @since 2.3.0
  1582. *
  1583. * @param mixed $value Value of the term field.
  1584. * @param int $term_id Term ID.
  1585. * @param string $taxonomy Taxonomy slug.
  1586. */
  1587. $value = apply_filters( "edit_term_{$field}", $value, $term_id, $taxonomy );
  1588. /**
  1589. * Filter the taxonomy field to edit before it is sanitized.
  1590. *
  1591. * The dynamic portions of the filter name, $taxonomy, and $field, refer
  1592. * to the taxonomy slug and taxonomy field, respectively.
  1593. *
  1594. * @since 2.3.0
  1595. *
  1596. * @param mixed $value Value of the taxonomy field to edit.
  1597. * @param int $term_id Term ID.
  1598. */
  1599. $value = apply_filters( "edit_{$taxonomy}_{$field}", $value, $term_id );
  1600. if ( 'description' == $field )
  1601. $value = esc_html($value); // textarea_escaped
  1602. else
  1603. $value = esc_attr($value);
  1604. } else if ( 'db' == $context ) {
  1605. /**
  1606. * Filter a term field value before it is sanitized.
  1607. *
  1608. * The dynamic portion of the filter name, $field, refers to the term field.
  1609. *
  1610. * @since 2.3.0
  1611. *
  1612. * @param mixed $value Value of the term field.
  1613. * @param string $taxonomy Taxonomy slug.
  1614. */
  1615. $value = apply_filters( "pre_term_{$field}", $value, $taxonomy );
  1616. /**
  1617. * Filter a taxonomy field before it is sanitized.
  1618. *
  1619. * The dynamic portions of the filter name, $taxonomy, and $field, refer
  1620. * to the taxonomy slug and field name, respectively.
  1621. *
  1622. * @since 2.3.0
  1623. *
  1624. * @param mixed $value Value of the taxonomy field.
  1625. */
  1626. $value = apply_filters( "pre_{$taxonomy}_{$field}", $value );
  1627. // Back compat filters
  1628. if ( 'slug' == $field ) {
  1629. /**
  1630. * Filter the category nicename before it is sanitized.
  1631. *
  1632. * Use the pre_{$taxonomy}_{$field} hook instead.
  1633. *
  1634. * @since 2.0.3
  1635. *
  1636. * @param string $value The category nicename.
  1637. */
  1638. $value = apply_filters( 'pre_category_nicename', $value );
  1639. }
  1640. } else if ( 'rss' == $context ) {
  1641. /**
  1642. * Filter the term field for use in RSS.
  1643. *
  1644. * The dynamic portion of the filter name, $field, refers to the term field.
  1645. *
  1646. * @since 2.3.0
  1647. *
  1648. * @param mixed $value Value of the term field.
  1649. * @param string $taxonomy Taxonomy slug.
  1650. */
  1651. $value = apply_filters( "term_{$field}_rss", $value, $taxonomy );
  1652. /**
  1653. * Filter the taxonomy field for use in RSS.
  1654. *
  1655. * The dynamic portions of the hook name, $taxonomy, and $field, refer
  1656. * to the taxonomy slug and field name, respectively.
  1657. *
  1658. * @since 2.3.0
  1659. *
  1660. * @param mixed $value Value of the taxonomy field.
  1661. */
  1662. $value = apply_filters( "{$taxonomy}_{$field}_rss", $value );
  1663. } else {
  1664. // Use display filters by default.
  1665. /**
  1666. * Filter the term field sanitized for display.
  1667. *
  1668. * The dynamic portion of the filter name, $field, refers to the term field name.
  1669. *
  1670. * @since 2.3.0
  1671. *
  1672. * @param mixed $value Value of the term field.
  1673. * @param int $term_id Term ID.
  1674. * @param string $taxonomy Taxonomy slug.
  1675. * @param string $context Context to retrieve the term field value.
  1676. */
  1677. $value = apply_filters( "term_{$field}", $value, $term_id, $taxonomy, $context );
  1678. /**
  1679. * Filter the taxonomy field sanitized for display.
  1680. *
  1681. * The dynamic portions of the filter name, $taxonomy, and $field, refer
  1682. * to the taxonomy slug and taxonomy field, respectively.
  1683. *
  1684. * @since 2.3.0
  1685. *
  1686. * @param mixed $value Value of the taxonomy field.
  1687. * @param int $term_id Term ID.
  1688. * @param string $context Context to retrieve the taxonomy field value.
  1689. */
  1690. $value = apply_filters( "{$taxonomy}_{$field}", $value, $term_id, $context );
  1691. }
  1692. if ( 'attribute' == $context )
  1693. $value = esc_attr($value);
  1694. else if ( 'js' == $context )
  1695. $value = esc_js($value);
  1696. return $value;
  1697. }
  1698. /**
  1699. * Count how many terms are in Taxonomy.
  1700. *
  1701. * Default $args is 'hide_empty' which can be 'hide_empty=true' or array('hide_empty' => true).
  1702. *
  1703. * @since 2.3.0
  1704. *
  1705. * @uses get_terms()
  1706. * @uses wp_parse_args() Turns strings into arrays and merges defaults into an array.
  1707. *
  1708. * @param string $taxonomy Taxonomy name
  1709. * @param array|string $args Overwrite defaults. See get_terms()
  1710. * @return int|WP_Error How many terms are in $taxonomy. WP_Error if $taxonomy does not exist.
  1711. */
  1712. function wp_count_terms( $taxonomy, $args = array() ) {
  1713. $defaults = array('hide_empty' => false);
  1714. $args = wp_parse_args($args, $defaults);
  1715. // backwards compatibility
  1716. if ( isset($args['ignore_empty']) ) {
  1717. $args['hide_empty'] = $args['ignore_empty'];
  1718. unset($args['ignore_empty']);
  1719. }
  1720. $args['fields'] = 'count';
  1721. return get_terms($taxonomy, $args);
  1722. }
  1723. /**
  1724. * Will unlink the object from the taxonomy or taxonomies.
  1725. *
  1726. * Will remove all relationships between the object and any terms in
  1727. * a particular taxonomy or taxonomies. Does not remove the term or
  1728. * taxonomy itself.
  1729. *
  1730. * @since 2.3.0
  1731. * @uses wp_remove_object_terms()
  1732. *
  1733. * @param int $object_id The term Object Id that refers to the term
  1734. * @param string|array $taxonomies List of Taxonomy Names or single Taxonomy name.
  1735. */
  1736. function wp_delete_object_term_relationships( $object_id, $taxonomies ) {
  1737. $object_id = (int) $object_id;
  1738. if ( !is_array($taxonomies) )
  1739. $taxonomies = array($taxonomies);
  1740. foreach ( (array) $taxonomies as $taxonomy ) {
  1741. $term_ids = wp_get_object_terms( $object_id, $taxonomy, array( 'fields' => 'ids' ) );
  1742. $term_ids = array_map( 'intval', $term_ids );
  1743. wp_remove_object_terms( $object_id, $term_ids, $taxonomy );
  1744. }
  1745. }
  1746. /**
  1747. * Removes a term from the database.
  1748. *
  1749. * If the term is a parent of other terms, then the children will be updated to
  1750. * that term's parent.
  1751. *
  1752. * The $args 'default' will only override the terms found, if there is only one
  1753. * term found. Any other and the found terms are used.
  1754. *
  1755. * The $args 'force_default' will force the term supplied as default to be
  1756. * assigned even if the object was not going to be termless
  1757. *
  1758. * @since 2.3.0
  1759. *
  1760. * @uses $wpdb
  1761. *
  1762. * @param int $term Term ID
  1763. * @param string $taxonomy Taxonomy Name
  1764. * @param array|string $args Optional. Change 'default' term id and override found term ids.
  1765. * @return bool|WP_Error Returns false if not term; true if completes delete action.
  1766. */
  1767. function wp_delete_term( $term, $taxonomy, $args = array() ) {
  1768. global $wpdb;
  1769. $term = (int) $term;
  1770. if ( ! $ids = term_exists($term, $taxonomy) )
  1771. return false;
  1772. if ( is_wp_error( $ids ) )
  1773. return $ids;
  1774. $tt_id = $ids['term_taxonomy_id'];
  1775. $defaults = array();
  1776. if ( 'category' == $taxonomy ) {
  1777. $defaults['default'] = get_option( 'default_category' );
  1778. if ( $defaults['default'] == $term )
  1779. return 0; // Don't delete the default category
  1780. }
  1781. $args = wp_parse_args($args, $defaults);
  1782. extract($args, EXTR_SKIP);
  1783. if ( isset( $default ) ) {
  1784. $default = (int) $default;
  1785. if ( ! term_exists($default, $taxonomy) )
  1786. unset($default);
  1787. }
  1788. // Update children to point to new parent
  1789. if ( is_taxonomy_hierarchical($taxonomy) ) {
  1790. $term_obj = get_term($term, $taxonomy);
  1791. if ( is_wp_error( $term_obj ) )
  1792. return $term_obj;
  1793. $parent = $term_obj->parent;
  1794. $edit_tt_ids = $wpdb->get_col( "SELECT `term_taxonomy_id` FROM $wpdb->term_taxonomy WHERE `parent` = " . (int)$term_obj->term_id );
  1795. /**
  1796. * Fires immediately before a term to delete's children are reassigned a parent.
  1797. *
  1798. * @since 2.9.0
  1799. *
  1800. * @param array $edit_tt_ids An array of term taxonomy IDs for the given term.
  1801. */
  1802. do_action( 'edit_term_taxonomies', $edit_tt_ids );
  1803. $wpdb->update( $wpdb->term_taxonomy, compact( 'parent' ), array( 'parent' => $term_obj->term_id) + compact( 'taxonomy' ) );
  1804. /**
  1805. * Fires immediately after a term to delete's children are reassigned a parent.
  1806. *
  1807. * @since 2.9.0
  1808. *
  1809. * @param array $edit_tt_ids An array of term taxonomy IDs for the given term.
  1810. */
  1811. do_action( 'edited_term_taxonomies', $edit_tt_ids );
  1812. }
  1813. $objects = $wpdb->get_col( $wpdb->prepare( "SELECT object_id FROM $wpdb->term_relationships WHERE term_taxonomy_id = %d", $tt_id ) );
  1814. foreach ( (array) $objects as $object ) {
  1815. $terms = wp_get_object_terms($object, $taxonomy, array('fields' => 'ids', 'orderby' => 'none'));
  1816. if ( 1 == count($terms) && isset($default) ) {
  1817. $terms = array($default);
  1818. } else {
  1819. $terms = array_diff($terms, array($term));
  1820. if (isset($default) && isset($force_default) && $force_default)
  1821. $terms = array_merge($terms, array($default));
  1822. }
  1823. $terms = array_map('intval', $terms);
  1824. wp_set_object_terms($object, $terms, $taxonomy);
  1825. }
  1826. // Clean the relationship caches for all object types using this term
  1827. $tax_object = get_taxonomy( $taxonomy );
  1828. foreach ( $tax_object->object_type as $object_type )
  1829. clean_object_term_cache( $objects, $object_type );
  1830. // Get the object before deletion so we can pass to actions below
  1831. $deleted_term = get_term( $term, $taxonomy );
  1832. /**
  1833. * Fires immediately before a term taxonomy ID is deleted.
  1834. *
  1835. * @since 2.9.0
  1836. *
  1837. * @param int $tt_id Term taxonomy ID.
  1838. */
  1839. do_action( 'delete_term_taxonomy', $tt_id );
  1840. $wpdb->delete( $wpdb->term_taxonomy, array( 'term_taxonomy_id' => $tt_id ) );
  1841. /**
  1842. * Fires immediately after a term taxonomy ID is deleted.
  1843. *
  1844. * @since 2.9.0
  1845. *
  1846. * @param int $tt_id Term taxonomy ID.
  1847. */
  1848. do_action( 'deleted_term_taxonomy', $tt_id );
  1849. // Delete the term if no taxonomies use it.
  1850. if ( !$wpdb->get_var( $wpdb->prepare( "SELECT COUNT(*) FROM $wpdb->term_taxonomy WHERE term_id = %d", $term) ) )
  1851. $wpdb->delete( $wpdb->terms, array( 'term_id' => $term ) );
  1852. clean_term_cache($term, $taxonomy);
  1853. /**
  1854. * Fires after a term is deleted from the database and the cache is cleaned.
  1855. *
  1856. * @since 2.5.0
  1857. *
  1858. * @param int $term Term ID.
  1859. * @param int $tt_id Term taxonomy ID.
  1860. * @param string $taxonomy Taxonomy slug.
  1861. * @param mixed $deleted_term Copy of the already-deleted term, in the form specified
  1862. * by the parent function. WP_Error otherwise.
  1863. */
  1864. do_action( 'delete_term', $term, $tt_id, $taxonomy, $deleted_term );
  1865. /**
  1866. * Fires after a term in a specific taxonomy is deleted.
  1867. *
  1868. * The dynamic portion of the hook name, $taxonomy, refers to the specific
  1869. * taxonomy the term belonged to.
  1870. *
  1871. * @since 2.3.0
  1872. *
  1873. * @param int $term Term ID.
  1874. * @param int $tt_id Term taxonomy ID.
  1875. * @param mixed $deleted_term Copy of the already-deleted term, in the form specified
  1876. * by the parent function. WP_Error otherwise.
  1877. */
  1878. do_action( "delete_$taxonomy", $term, $tt_id, $deleted_term );
  1879. return true;
  1880. }
  1881. /**
  1882. * Deletes one existing category.
  1883. *
  1884. * @since 2.0.0
  1885. * @uses wp_delete_term()
  1886. *
  1887. * @param int $cat_ID
  1888. * @return mixed Returns true if completes delete action; false if term doesn't exist;
  1889. * Zero on attempted deletion of default Category; WP_Error object is also a possibility.
  1890. */
  1891. function wp_delete_category( $cat_ID ) {
  1892. return wp_delete_term( $cat_ID, 'category' );
  1893. }
  1894. /**
  1895. * Retrieves the terms associated with the given object(s), in the supplied taxonomies.
  1896. *
  1897. * The following information has to do the $args parameter and for what can be
  1898. * contained in the string or array of that parameter, if it exists.
  1899. *
  1900. * The first argument is called, 'orderby' and has the default value of 'name'.
  1901. * The other value that is supported is 'count'.
  1902. *
  1903. * The second argument is called, 'order' and has the default value of 'ASC'.
  1904. * The only other value that will be acceptable is 'DESC'.
  1905. *
  1906. * The final argument supported is called, 'fields' and has the default value of
  1907. * 'all'. There are multiple other options that can be used instead. Supported
  1908. * values are as follows: 'all', 'ids', 'names', and finally
  1909. * 'all_with_object_id'.
  1910. *
  1911. * The fields argument also decides what will be returned. If 'all' or
  1912. * 'all_with_object_id' is chosen or the default kept intact, then all matching
  1913. * terms objects will be returned. If either 'ids' or 'names' is used, then an
  1914. * array of all matching term ids or term names will be returned respectively.
  1915. *
  1916. * @since 2.3.0
  1917. * @uses $wpdb
  1918. *
  1919. * @param int|array $object_ids The ID(s) of the object(s) to retrieve.
  1920. * @param string|array $taxonomies The taxonomies to retrieve terms from.
  1921. * @param array|string $args Change what is returned
  1922. * @return array|WP_Error The requested term data or empty array if no terms found. WP_Error if any of the $taxonomies don't exist.
  1923. */
  1924. function wp_get_object_terms($object_ids, $taxonomies, $args = array()) {
  1925. global $wpdb;
  1926. if ( empty( $object_ids ) || empty( $taxonomies ) )
  1927. return array();
  1928. if ( !is_array($taxonomies) )
  1929. $taxonomies = array($taxonomies);
  1930. foreach ( $taxonomies as $taxonomy ) {
  1931. if ( ! taxonomy_exists($taxonomy) )
  1932. return new WP_Error('invalid_taxonomy', __('Invalid taxonomy'));
  1933. }
  1934. if ( !is_array($object_ids) )
  1935. $object_ids = array($object_ids);
  1936. $object_ids = array_map('intval', $object_ids);
  1937. $defaults = array('orderby' => 'name', 'order' => 'ASC', 'fields' => 'all');
  1938. $args = wp_parse_args( $args, $defaults );
  1939. $terms = array();
  1940. if ( count($taxonomies) > 1 ) {
  1941. foreach ( $taxonomies as $index => $taxonomy ) {
  1942. $t = get_taxonomy($taxonomy);
  1943. if ( isset($t->args) && is_array($t->args) && $args != array_merge($args, $t->args) ) {
  1944. unset($taxonomies[$index]);
  1945. $terms = array_merge($terms, wp_get_object_terms($object_ids, $taxonomy, array_merge($args, $t->args)));
  1946. }
  1947. }
  1948. } else {
  1949. $t = get_taxonomy($taxonomies[0]);
  1950. if ( isset($t->args) && is_array($t->args) )
  1951. $args = array_merge($args, $t->args);
  1952. }
  1953. extract($args, EXTR_SKIP);
  1954. if ( 'count' == $orderby )
  1955. $orderby = 'tt.count';
  1956. else if ( 'name' == $orderby )
  1957. $orderby = 't.name';
  1958. else if ( 'slug' == $orderby )
  1959. $orderby = 't.slug';
  1960. else if ( 'term_group' == $orderby )
  1961. $orderby = 't.term_group';
  1962. else if ( 'term_order' == $orderby )
  1963. $orderby = 'tr.term_order';
  1964. else if ( 'none' == $orderby ) {
  1965. $orderby = '';
  1966. $order = '';
  1967. } else {
  1968. $orderby = 't.term_id';
  1969. }
  1970. // tt_ids queries can only be none or tr.term_taxonomy_id
  1971. if ( ('tt_ids' == $fields) && !empty($orderby) )
  1972. $orderby = 'tr.term_taxonomy_id';
  1973. if ( !empty($orderby) )
  1974. $orderby = "ORDER BY $orderby";
  1975. $order = strtoupper( $order );
  1976. if ( '' !== $order && ! in_array( $order, array( 'ASC', 'DESC' ) ) )
  1977. $order = 'ASC';
  1978. $taxonomies = "'" . implode("', '", $taxonomies) . "'";
  1979. $object_ids = implode(', ', $object_ids);
  1980. $select_this = '';
  1981. if ( 'all' == $fields )
  1982. $select_this = 't.*, tt.*';
  1983. else if ( 'ids' == $fields )
  1984. $select_this = 't.term_id';
  1985. else if ( 'names' == $fields )
  1986. $select_this = 't.name';
  1987. else if ( 'slugs' == $fields )
  1988. $select_this = 't.slug';
  1989. else if ( 'all_with_object_id' == $fields )
  1990. $select_this = 't.*, tt.*, tr.object_id';
  1991. $query = "SELECT $select_this FROM $wpdb->terms AS t INNER JOIN $wpdb->term_taxonomy AS tt ON tt.term_id = t.term_id INNER JOIN $wpdb->term_relationships AS tr ON tr.term_taxonomy_id = tt.term_taxonomy_id WHERE tt.taxonomy IN ($taxonomies) AND tr.object_id IN ($object_ids) $orderby $order";
  1992. if ( 'all' == $fields || 'all_with_object_id' == $fields ) {
  1993. $_terms = $wpdb->get_results( $query );
  1994. foreach ( $_terms as $key => $term ) {
  1995. $_terms[$key] = sanitize_term( $term, $taxonomy, 'raw' );
  1996. }
  1997. $terms = array_merge( $terms, $_terms );
  1998. update_term_cache( $terms );
  1999. } else if ( 'ids' == $fields || 'names' == $fields || 'slugs' == $fields ) {
  2000. $_terms = $wpdb->get_col( $query );
  2001. $_field = ( 'ids' == $fields ) ? 'term_id' : 'name';
  2002. foreach ( $_terms as $key => $term ) {
  2003. $_terms[$key] = sanitize_term_field( $_field, $term, $term, $taxonomy, 'raw' );
  2004. }
  2005. $terms = array_merge( $terms, $_terms );
  2006. } else if ( 'tt_ids' == $fields ) {
  2007. $terms = $wpdb->get_col("SELECT tr.term_taxonomy_id FROM $wpdb->term_relationships AS tr INNER JOIN $wpdb->term_taxonomy AS tt ON tr.term_taxonomy_id = tt.term_taxonomy_id WHERE tr.object_id IN ($object_ids) AND tt.taxonomy IN ($taxonomies) $orderby $order");
  2008. foreach ( $terms as $key => $tt_id ) {
  2009. $terms[$key] = sanitize_term_field( 'term_taxonomy_id', $tt_id, 0, $taxonomy, 'raw' ); // 0 should be the term id, however is not needed when using raw context.
  2010. }
  2011. }
  2012. if ( ! $terms )
  2013. $terms = array();
  2014. /**
  2015. * Filter the terms for a given object or objects.
  2016. *
  2017. * @since 2.8.0
  2018. *
  2019. * @param array $terms An array of terms for the given object or objects.
  2020. * @param array|int $object_ids Object ID or array of IDs.
  2021. * @param array|string $taxonomies A taxonomy or array of taxonomies.
  2022. * @param array $args An array of arguments for retrieving terms for
  2023. * the given object(s).
  2024. */
  2025. return apply_filters( 'wp_get_object_terms', $terms, $object_ids, $taxonomies, $args );
  2026. }
  2027. /**
  2028. * Add a new term to the database.
  2029. *
  2030. * A non-existent term is inserted in the following sequence:
  2031. * 1. The term is added to the term table, then related to the taxonomy.
  2032. * 2. If everything is correct, several actions are fired.
  2033. * 3. The 'term_id_filter' is evaluated.
  2034. * 4. The term cache is cleaned.
  2035. * 5. Several more actions are fired.
  2036. * 6. An array is returned containing the term_id and term_taxonomy_id.
  2037. *
  2038. * If the 'slug' argument is not empty, then it is checked to see if the term
  2039. * is invalid. If it is not a valid, existing term, it is added and the term_id
  2040. * is given.
  2041. *
  2042. * If the taxonomy is hierarchical, and the 'parent' argument is not empty,
  2043. * the term is inserted and the term_id will be given.
  2044. * Error handling:
  2045. * If $taxonomy does not exist or $term is empty,
  2046. * a WP_Error object will be returned.
  2047. *
  2048. * If the term already exists on the same hierarchical level,
  2049. * or the term slug and name are not unique, a WP_Error object will be returned.
  2050. *
  2051. * @global wpdb $wpdb The WordPress database object.
  2052. * @since 2.3.0
  2053. *
  2054. * @param string $term The term to add or update.
  2055. * @param string $taxonomy The taxonomy to which to add the term
  2056. * @param array|string $args {
  2057. * Arguments to change values of the inserted term.
  2058. *
  2059. * @type string 'alias_of' Slug of the term to make this term an alias of.
  2060. * Default empty string. Accepts a term slug.
  2061. * @type string 'description' The term description.
  2062. * Default empty string.
  2063. * @type int 'parent' The id of the parent term.
  2064. * Default 0.
  2065. * @type string 'slug' The term slug to use.
  2066. * Default empty string.
  2067. * }
  2068. * @return array|WP_Error An array containing the term_id and term_taxonomy_id, WP_Error otherwise.
  2069. */
  2070. function wp_insert_term( $term, $taxonomy, $args = array() ) {
  2071. global $wpdb;
  2072. if ( ! taxonomy_exists($taxonomy) )
  2073. return new WP_Error('invalid_taxonomy', __('Invalid taxonomy'));
  2074. /**
  2075. * Filter a term before it is sanitized and inserted into the database.
  2076. *
  2077. * @since 3.0.0
  2078. *
  2079. * @param string $term The term to add or update.
  2080. * @param string $taxonomy Taxonomy slug.
  2081. */
  2082. $term = apply_filters( 'pre_insert_term', $term, $taxonomy );
  2083. if ( is_wp_error( $term ) )
  2084. return $term;
  2085. if ( is_int($term) && 0 == $term )
  2086. return new WP_Error('invalid_term_id', __('Invalid term ID'));
  2087. if ( '' == trim($term) )
  2088. return new WP_Error('empty_term_name', __('A name is required for this term'));
  2089. $defaults = array( 'alias_of' => '', 'description' => '', 'parent' => 0, 'slug' => '');
  2090. $args = wp_parse_args($args, $defaults);
  2091. $args['name'] = $term;
  2092. $args['taxonomy'] = $taxonomy;
  2093. $args = sanitize_term($args, $taxonomy, 'db');
  2094. extract($args, EXTR_SKIP);
  2095. // expected_slashed ($name)
  2096. $name = wp_unslash($name);
  2097. $description = wp_unslash($description);
  2098. $slug_provided = ! empty( $slug );
  2099. if ( ! $slug_provided ) {
  2100. $slug = sanitize_title($name);
  2101. }
  2102. $term_group = 0;
  2103. if ( $alias_of ) {
  2104. $alias = $wpdb->get_row( $wpdb->prepare( "SELECT term_id, term_group FROM $wpdb->terms WHERE slug = %s", $alias_of) );
  2105. if ( $alias->term_group ) {
  2106. // The alias we want is already in a group, so let's use that one.
  2107. $term_group = $alias->term_group;
  2108. } else {
  2109. // The alias isn't in a group, so let's create a new one and firstly add the alias term to it.
  2110. $term_group = $wpdb->get_var("SELECT MAX(term_group) FROM $wpdb->terms") + 1;
  2111. /**
  2112. * Fires immediately before the given terms are edited.
  2113. *
  2114. * @since 2.9.0
  2115. *
  2116. * @param int $term_id Term ID.
  2117. * @param string $taxonomy Taxonomy slug.
  2118. */
  2119. do_action( 'edit_terms', $alias->term_id, $taxonomy );
  2120. $wpdb->update($wpdb->terms, compact('term_group'), array('term_id' => $alias->term_id) );
  2121. /**
  2122. * Fires immediately after the given terms are edited.
  2123. *
  2124. * @since 2.9.0
  2125. *
  2126. * @param int $term_id Term ID
  2127. * @param string $taxonomy Taxonomy slug.
  2128. */
  2129. do_action( 'edited_terms', $alias->term_id, $taxonomy );
  2130. }
  2131. }
  2132. if ( $term_id = term_exists($slug) ) {
  2133. $existing_term = $wpdb->get_row( $wpdb->prepare( "SELECT name FROM $wpdb->terms WHERE term_id = %d", $term_id), ARRAY_A );
  2134. // We've got an existing term in the same taxonomy, which matches the name of the new term:
  2135. if ( is_taxonomy_hierarchical($taxonomy) && $existing_term['name'] == $name && $exists = term_exists( (int) $term_id, $taxonomy ) ) {
  2136. // Hierarchical, and it matches an existing term, Do not allow same "name" in the same level.
  2137. $siblings = get_terms($taxonomy, array('fields' => 'names', 'get' => 'all', 'parent' => (int)$parent) );
  2138. if ( in_array($name, $siblings) ) {
  2139. if ( $slug_provided ) {
  2140. return new WP_Error( 'term_exists', __( 'A term with the name and slug provided already exists with this parent.' ), $exists['term_id'] );
  2141. } else {
  2142. return new WP_Error( 'term_exists', __( 'A term with the name provided already exists with this parent.' ), $exists['term_id'] );
  2143. }
  2144. } else {
  2145. $slug = wp_unique_term_slug($slug, (object) $args);
  2146. if ( false === $wpdb->insert( $wpdb->terms, compact( 'name', 'slug', 'term_group' ) ) )
  2147. return new WP_Error('db_insert_error', __('Could not insert term into the database'), $wpdb->last_error);
  2148. $term_id = (int) $wpdb->insert_id;
  2149. }
  2150. } elseif ( $existing_term['name'] != $name ) {
  2151. // We've got an existing term, with a different name, Create the new term.
  2152. $slug = wp_unique_term_slug($slug, (object) $args);
  2153. if ( false === $wpdb->insert( $wpdb->terms, compact( 'name', 'slug', 'term_group' ) ) )
  2154. return new WP_Error('db_insert_error', __('Could not insert term into the database'), $wpdb->last_error);
  2155. $term_id = (int) $wpdb->insert_id;
  2156. } elseif ( $exists = term_exists( (int) $term_id, $taxonomy ) ) {
  2157. // Same name, same slug.
  2158. return new WP_Error( 'term_exists', __( 'A term with the name and slug provided already exists.' ), $exists['term_id'] );
  2159. }
  2160. } else {
  2161. // This term does not exist at all in the database, Create it.
  2162. $slug = wp_unique_term_slug($slug, (object) $args);
  2163. if ( false === $wpdb->insert( $wpdb->terms, compact( 'name', 'slug', 'term_group' ) ) )
  2164. return new WP_Error('db_insert_error', __('Could not insert term into the database'), $wpdb->last_error);
  2165. $term_id = (int) $wpdb->insert_id;
  2166. }
  2167. // Seems unreachable, However, Is used in the case that a term name is provided, which sanitizes to an empty string.
  2168. if ( empty($slug) ) {
  2169. $slug = sanitize_title($slug, $term_id);
  2170. /** This action is documented in wp-includes/taxonomy.php */
  2171. do_action( 'edit_terms', $term_id, $taxonomy );
  2172. $wpdb->update( $wpdb->terms, compact( 'slug' ), compact( 'term_id' ) );
  2173. /** This action is documented in wp-includes/taxonomy.php */
  2174. do_action( 'edited_terms', $term_id, $taxonomy );
  2175. }
  2176. $tt_id = $wpdb->get_var( $wpdb->prepare( "SELECT tt.term_taxonomy_id FROM $wpdb->term_taxonomy AS tt INNER JOIN $wpdb->terms AS t ON tt.term_id = t.term_id WHERE tt.taxonomy = %s AND t.term_id = %d", $taxonomy, $term_id ) );
  2177. if ( !empty($tt_id) )
  2178. return array('term_id' => $term_id, 'term_taxonomy_id' => $tt_id);
  2179. $wpdb->insert( $wpdb->term_taxonomy, compact( 'term_id', 'taxonomy', 'description', 'parent') + array( 'count' => 0 ) );
  2180. $tt_id = (int) $wpdb->insert_id;
  2181. /**
  2182. * Fires immediately after a new term is created, before the term cache is cleaned.
  2183. *
  2184. * @since 2.3.0
  2185. *
  2186. * @param int $term_id Term ID.
  2187. * @param int $tt_id Term taxonomy ID.
  2188. * @param string $taxonomy Taxonomy slug.
  2189. */
  2190. do_action( "create_term", $term_id, $tt_id, $taxonomy );
  2191. /**
  2192. * Fires after a new term is created for a specific taxonomy.
  2193. *
  2194. * The dynamic portion of the hook name, $taxonomy, refers
  2195. * to the slug of the taxonomy the term was created for.
  2196. *
  2197. * @since 2.3.0
  2198. *
  2199. * @param int $term_id Term ID.
  2200. * @param int $tt_id Term taxonomy ID.
  2201. */
  2202. do_action( "create_$taxonomy", $term_id, $tt_id );
  2203. /**
  2204. * Filter the term ID after a new term is created.
  2205. *
  2206. * @since 2.3.0
  2207. *
  2208. * @param int $term_id Term ID.
  2209. * @param int $tt_id Taxonomy term ID.
  2210. */
  2211. $term_id = apply_filters( 'term_id_filter', $term_id, $tt_id );
  2212. clean_term_cache($term_id, $taxonomy);
  2213. /**
  2214. * Fires after a new term is created, and after the term cache has been cleaned.
  2215. *
  2216. * @since 2.3.0
  2217. */
  2218. do_action( "created_term", $term_id, $tt_id, $taxonomy );
  2219. /**
  2220. * Fires after a new term in a specific taxonomy is created, and after the term
  2221. * cache has been cleaned.
  2222. *
  2223. * @since 2.3.0
  2224. *
  2225. * @param int $term_id Term ID.
  2226. * @param int $tt_id Term taxonomy ID.
  2227. */
  2228. do_action( "created_$taxonomy", $term_id, $tt_id );
  2229. return array('term_id' => $term_id, 'term_taxonomy_id' => $tt_id);
  2230. }
  2231. /**
  2232. * Create Term and Taxonomy Relationships.
  2233. *
  2234. * Relates an object (post, link etc) to a term and taxonomy type. Creates the
  2235. * term and taxonomy relationship if it doesn't already exist. Creates a term if
  2236. * it doesn't exist (using the slug).
  2237. *
  2238. * A relationship means that the term is grouped in or belongs to the taxonomy.
  2239. * A term has no meaning until it is given context by defining which taxonomy it
  2240. * exists under.
  2241. *
  2242. * @since 2.3.0
  2243. * @uses wp_remove_object_terms()
  2244. *
  2245. * @param int $object_id The object to relate to.
  2246. * @param array|int|string $terms The slug or id of the term, will replace all existing
  2247. * related terms in this taxonomy.
  2248. * @param array|string $taxonomy The context in which to relate the term to the object.
  2249. * @param bool $append If false will delete difference of terms.
  2250. * @return array|WP_Error Affected Term IDs
  2251. */
  2252. function wp_set_object_terms($object_id, $terms, $taxonomy, $append = false) {
  2253. global $wpdb;
  2254. $object_id = (int) $object_id;
  2255. if ( ! taxonomy_exists($taxonomy) )
  2256. return new WP_Error('invalid_taxonomy', __('Invalid taxonomy'));
  2257. if ( !is_array($terms) )
  2258. $terms = array($terms);
  2259. if ( ! $append )
  2260. $old_tt_ids = wp_get_object_terms($object_id, $taxonomy, array('fields' => 'tt_ids', 'orderby' => 'none'));
  2261. else
  2262. $old_tt_ids = array();
  2263. $tt_ids = array();
  2264. $term_ids = array();
  2265. $new_tt_ids = array();
  2266. foreach ( (array) $terms as $term) {
  2267. if ( !strlen(trim($term)) )
  2268. continue;
  2269. if ( !$term_info = term_exists($term, $taxonomy) ) {
  2270. // Skip if a non-existent term ID is passed.
  2271. if ( is_int($term) )
  2272. continue;
  2273. $term_info = wp_insert_term($term, $taxonomy);
  2274. }
  2275. if ( is_wp_error($term_info) )
  2276. return $term_info;
  2277. $term_ids[] = $term_info['term_id'];
  2278. $tt_id = $term_info['term_taxonomy_id'];
  2279. $tt_ids[] = $tt_id;
  2280. if ( $wpdb->get_var( $wpdb->prepare( "SELECT term_taxonomy_id FROM $wpdb->term_relationships WHERE object_id = %d AND term_taxonomy_id = %d", $object_id, $tt_id ) ) )
  2281. continue;
  2282. /**
  2283. * Fires immediately before an object-term relationship is added.
  2284. *
  2285. * @since 2.9.0
  2286. *
  2287. * @param int $object_id Object ID.
  2288. * @param int $tt_id Term taxonomy ID.
  2289. */
  2290. do_action( 'add_term_relationship', $object_id, $tt_id );
  2291. $wpdb->insert( $wpdb->term_relationships, array( 'object_id' => $object_id, 'term_taxonomy_id' => $tt_id ) );
  2292. /**
  2293. * Fires immediately after an object-term relationship is added.
  2294. *
  2295. * @since 2.9.0
  2296. *
  2297. * @param int $object_id Object ID.
  2298. * @param int $tt_id Term taxonomy ID.
  2299. */
  2300. do_action( 'added_term_relationship', $object_id, $tt_id );
  2301. $new_tt_ids[] = $tt_id;
  2302. }
  2303. if ( $new_tt_ids )
  2304. wp_update_term_count( $new_tt_ids, $taxonomy );
  2305. if ( ! $append ) {
  2306. $delete_tt_ids = array_diff( $old_tt_ids, $tt_ids );
  2307. if ( $delete_tt_ids ) {
  2308. $in_delete_tt_ids = "'" . implode( "', '", $delete_tt_ids ) . "'";
  2309. $delete_term_ids = $wpdb->get_col( $wpdb->prepare( "SELECT tt.term_id FROM $wpdb->term_taxonomy AS tt WHERE tt.taxonomy = %s AND tt.term_taxonomy_id IN ($in_delete_tt_ids)", $taxonomy ) );
  2310. $delete_term_ids = array_map( 'intval', $delete_term_ids );
  2311. $remove = wp_remove_object_terms( $object_id, $delete_term_ids, $taxonomy );
  2312. if ( is_wp_error( $remove ) ) {
  2313. return $remove;
  2314. }
  2315. }
  2316. }
  2317. $t = get_taxonomy($taxonomy);
  2318. if ( ! $append && isset($t->sort) && $t->sort ) {
  2319. $values = array();
  2320. $term_order = 0;
  2321. $final_tt_ids = wp_get_object_terms($object_id, $taxonomy, array('fields' => 'tt_ids'));
  2322. foreach ( $tt_ids as $tt_id )
  2323. if ( in_array($tt_id, $final_tt_ids) )
  2324. $values[] = $wpdb->prepare( "(%d, %d, %d)", $object_id, $tt_id, ++$term_order);
  2325. if ( $values )
  2326. if ( false === $wpdb->query( "INSERT INTO $wpdb->term_relationships (object_id, term_taxonomy_id, term_order) VALUES " . join( ',', $values ) . " ON DUPLICATE KEY UPDATE term_order = VALUES(term_order)" ) )
  2327. return new WP_Error( 'db_insert_error', __( 'Could not insert term relationship into the database' ), $wpdb->last_error );
  2328. }
  2329. wp_cache_delete( $object_id, $taxonomy . '_relationships' );
  2330. /**
  2331. * Fires after an object's terms have been set.
  2332. *
  2333. * @since 2.8.0
  2334. *
  2335. * @param int $object_id Object ID.
  2336. * @param array $terms An array of object terms.
  2337. * @param array $tt_ids An array of term taxonomy IDs.
  2338. * @param string $taxonomy Taxonomy slug.
  2339. * @param bool $append Whether to append new terms to the old terms.
  2340. * @param array $old_tt_ids Old array of term taxonomy IDs.
  2341. */
  2342. do_action( 'set_object_terms', $object_id, $terms, $tt_ids, $taxonomy, $append, $old_tt_ids );
  2343. return $tt_ids;
  2344. }
  2345. /**
  2346. * Add term(s) associated with a given object.
  2347. *
  2348. * @since 3.6.0
  2349. * @uses wp_set_object_terms()
  2350. *
  2351. * @param int $object_id The ID of the object to which the terms will be added.
  2352. * @param array|int|string $terms The slug(s) or ID(s) of the term(s) to add.
  2353. * @param array|string $taxonomy Taxonomy name.
  2354. * @return array|WP_Error Affected Term IDs
  2355. */
  2356. function wp_add_object_terms( $object_id, $terms, $taxonomy ) {
  2357. return wp_set_object_terms( $object_id, $terms, $taxonomy, true );
  2358. }
  2359. /**
  2360. * Remove term(s) associated with a given object.
  2361. *
  2362. * @since 3.6.0
  2363. * @uses $wpdb
  2364. *
  2365. * @param int $object_id The ID of the object from which the terms will be removed.
  2366. * @param array|int|string $terms The slug(s) or ID(s) of the term(s) to remove.
  2367. * @param array|string $taxonomy Taxonomy name.
  2368. * @return bool|WP_Error True on success, false or WP_Error on failure.
  2369. */
  2370. function wp_remove_object_terms( $object_id, $terms, $taxonomy ) {
  2371. global $wpdb;
  2372. $object_id = (int) $object_id;
  2373. if ( ! taxonomy_exists( $taxonomy ) ) {
  2374. return new WP_Error( 'invalid_taxonomy', __( 'Invalid Taxonomy' ) );
  2375. }
  2376. if ( ! is_array( $terms ) ) {
  2377. $terms = array( $terms );
  2378. }
  2379. $tt_ids = array();
  2380. foreach ( (array) $terms as $term ) {
  2381. if ( ! strlen( trim( $term ) ) ) {
  2382. continue;
  2383. }
  2384. if ( ! $term_info = term_exists( $term, $taxonomy ) ) {
  2385. // Skip if a non-existent term ID is passed.
  2386. if ( is_int( $term ) ) {
  2387. continue;
  2388. }
  2389. }
  2390. if ( is_wp_error( $term_info ) ) {
  2391. return $term_info;
  2392. }
  2393. $tt_ids[] = $term_info['term_taxonomy_id'];
  2394. }
  2395. if ( $tt_ids ) {
  2396. $in_tt_ids = "'" . implode( "', '", $tt_ids ) . "'";
  2397. /**
  2398. * Fires immediately before an object-term relationship is deleted.
  2399. *
  2400. * @since 2.9.0
  2401. *
  2402. * @param int $object_id Object ID.
  2403. * @param array $tt_ids An array of term taxonomy IDs.
  2404. */
  2405. do_action( 'delete_term_relationships', $object_id, $tt_ids );
  2406. $deleted = $wpdb->query( $wpdb->prepare( "DELETE FROM $wpdb->term_relationships WHERE object_id = %d AND term_taxonomy_id IN ($in_tt_ids)", $object_id ) );
  2407. /**
  2408. * Fires immediately after an object-term relationship is deleted.
  2409. *
  2410. * @since 2.9.0
  2411. *
  2412. * @param int $object_id Object ID.
  2413. * @param array $tt_ids An array of term taxonomy IDs.
  2414. */
  2415. do_action( 'deleted_term_relationships', $object_id, $tt_ids );
  2416. wp_update_term_count( $tt_ids, $taxonomy );
  2417. return (bool) $deleted;
  2418. }
  2419. return false;
  2420. }
  2421. /**
  2422. * Will make slug unique, if it isn't already.
  2423. *
  2424. * The $slug has to be unique global to every taxonomy, meaning that one
  2425. * taxonomy term can't have a matching slug with another taxonomy term. Each
  2426. * slug has to be globally unique for every taxonomy.
  2427. *
  2428. * The way this works is that if the taxonomy that the term belongs to is
  2429. * hierarchical and has a parent, it will append that parent to the $slug.
  2430. *
  2431. * If that still doesn't return an unique slug, then it try to append a number
  2432. * until it finds a number that is truly unique.
  2433. *
  2434. * The only purpose for $term is for appending a parent, if one exists.
  2435. *
  2436. * @since 2.3.0
  2437. * @uses $wpdb
  2438. *
  2439. * @param string $slug The string that will be tried for a unique slug
  2440. * @param object $term The term object that the $slug will belong too
  2441. * @return string Will return a true unique slug.
  2442. */
  2443. function wp_unique_term_slug($slug, $term) {
  2444. global $wpdb;
  2445. if ( ! term_exists( $slug ) )
  2446. return $slug;
  2447. // If the taxonomy supports hierarchy and the term has a parent, make the slug unique
  2448. // by incorporating parent slugs.
  2449. if ( is_taxonomy_hierarchical($term->taxonomy) && !empty($term->parent) ) {
  2450. $the_parent = $term->parent;
  2451. while ( ! empty($the_parent) ) {
  2452. $parent_term = get_term($the_parent, $term->taxonomy);
  2453. if ( is_wp_error($parent_term) || empty($parent_term) )
  2454. break;
  2455. $slug .= '-' . $parent_term->slug;
  2456. if ( ! term_exists( $slug ) )
  2457. return $slug;
  2458. if ( empty($parent_term->parent) )
  2459. break;
  2460. $the_parent = $parent_term->parent;
  2461. }
  2462. }
  2463. // If we didn't get a unique slug, try appending a number to make it unique.
  2464. if ( ! empty( $term->term_id ) )
  2465. $query = $wpdb->prepare( "SELECT slug FROM $wpdb->terms WHERE slug = %s AND term_id != %d", $slug, $term->term_id );
  2466. else
  2467. $query = $wpdb->prepare( "SELECT slug FROM $wpdb->terms WHERE slug = %s", $slug );
  2468. if ( $wpdb->get_var( $query ) ) {
  2469. $num = 2;
  2470. do {
  2471. $alt_slug = $slug . "-$num";
  2472. $num++;
  2473. $slug_check = $wpdb->get_var( $wpdb->prepare( "SELECT slug FROM $wpdb->terms WHERE slug = %s", $alt_slug ) );
  2474. } while ( $slug_check );
  2475. $slug = $alt_slug;
  2476. }
  2477. return $slug;
  2478. }
  2479. /**
  2480. * Update term based on arguments provided.
  2481. *
  2482. * The $args will indiscriminately override all values with the same field name.
  2483. * Care must be taken to not override important information need to update or
  2484. * update will fail (or perhaps create a new term, neither would be acceptable).
  2485. *
  2486. * Defaults will set 'alias_of', 'description', 'parent', and 'slug' if not
  2487. * defined in $args already.
  2488. *
  2489. * 'alias_of' will create a term group, if it doesn't already exist, and update
  2490. * it for the $term.
  2491. *
  2492. * If the 'slug' argument in $args is missing, then the 'name' in $args will be
  2493. * used. It should also be noted that if you set 'slug' and it isn't unique then
  2494. * a WP_Error will be passed back. If you don't pass any slug, then a unique one
  2495. * will be created for you.
  2496. *
  2497. * For what can be overrode in $args, check the term scheme can contain and stay
  2498. * away from the term keys.
  2499. *
  2500. * @since 2.3.0
  2501. *
  2502. * @uses $wpdb
  2503. *
  2504. * @param int $term_id The ID of the term
  2505. * @param string $taxonomy The context in which to relate the term to the object.
  2506. * @param array|string $args Overwrite term field values
  2507. * @return array|WP_Error Returns Term ID and Taxonomy Term ID
  2508. */
  2509. function wp_update_term( $term_id, $taxonomy, $args = array() ) {
  2510. global $wpdb;
  2511. if ( ! taxonomy_exists($taxonomy) )
  2512. return new WP_Error('invalid_taxonomy', __('Invalid taxonomy'));
  2513. $term_id = (int) $term_id;
  2514. // First, get all of the original args
  2515. $term = get_term ($term_id, $taxonomy, ARRAY_A);
  2516. if ( is_wp_error( $term ) )
  2517. return $term;
  2518. // Escape data pulled from DB.
  2519. $term = wp_slash($term);
  2520. // Merge old and new args with new args overwriting old ones.
  2521. $args = array_merge($term, $args);
  2522. $defaults = array( 'alias_of' => '', 'description' => '', 'parent' => 0, 'slug' => '');
  2523. $args = wp_parse_args($args, $defaults);
  2524. $args = sanitize_term($args, $taxonomy, 'db');
  2525. extract($args, EXTR_SKIP);
  2526. // expected_slashed ($name)
  2527. $name = wp_unslash($name);
  2528. $description = wp_unslash($description);
  2529. if ( '' == trim($name) )
  2530. return new WP_Error('empty_term_name', __('A name is required for this term'));
  2531. $empty_slug = false;
  2532. if ( empty($slug) ) {
  2533. $empty_slug = true;
  2534. $slug = sanitize_title($name);
  2535. }
  2536. if ( $alias_of ) {
  2537. $alias = $wpdb->get_row( $wpdb->prepare( "SELECT term_id, term_group FROM $wpdb->terms WHERE slug = %s", $alias_of) );
  2538. if ( $alias->term_group ) {
  2539. // The alias we want is already in a group, so let's use that one.
  2540. $term_group = $alias->term_group;
  2541. } else {
  2542. // The alias isn't in a group, so let's create a new one and firstly add the alias term to it.
  2543. $term_group = $wpdb->get_var("SELECT MAX(term_group) FROM $wpdb->terms") + 1;
  2544. /** This action is documented in wp-includes/taxonomy.php */
  2545. do_action( 'edit_terms', $alias->term_id, $taxonomy );
  2546. $wpdb->update( $wpdb->terms, compact('term_group'), array( 'term_id' => $alias->term_id ) );
  2547. /** This action is documented in wp-includes/taxonomy.php */
  2548. do_action( 'edited_terms', $alias->term_id, $taxonomy );
  2549. }
  2550. }
  2551. /**
  2552. * Filter the term parent.
  2553. *
  2554. * Hook to this filter to see if it will cause a hierarchy loop.
  2555. *
  2556. * @since 3.1.0
  2557. *
  2558. * @param int $parent ID of the parent term.
  2559. * @param int $term_id Term ID.
  2560. * @param string $taxonomy Taxonomy slug.
  2561. * @param array $args Compacted array of update arguments for the given term.
  2562. * @param array $args An array of update arguments for the given term.
  2563. */
  2564. $parent = apply_filters( 'wp_update_term_parent', $parent, $term_id, $taxonomy, compact( array_keys( $args ) ), $args );
  2565. // Check for duplicate slug
  2566. $id = $wpdb->get_var( $wpdb->prepare( "SELECT term_id FROM $wpdb->terms WHERE slug = %s", $slug ) );
  2567. if ( $id && ($id != $term_id) ) {
  2568. // If an empty slug was passed or the parent changed, reset the slug to something unique.
  2569. // Otherwise, bail.
  2570. if ( $empty_slug || ( $parent != $term['parent']) )
  2571. $slug = wp_unique_term_slug($slug, (object) $args);
  2572. else
  2573. return new WP_Error('duplicate_term_slug', sprintf(__('The slug &#8220;%s&#8221; is already in use by another term'), $slug));
  2574. }
  2575. /** This action is documented in wp-includes/taxonomy.php */
  2576. do_action( 'edit_terms', $term_id, $taxonomy );
  2577. $wpdb->update($wpdb->terms, compact( 'name', 'slug', 'term_group' ), compact( 'term_id' ) );
  2578. if ( empty($slug) ) {
  2579. $slug = sanitize_title($name, $term_id);
  2580. $wpdb->update( $wpdb->terms, compact( 'slug' ), compact( 'term_id' ) );
  2581. }
  2582. /** This action is documented in wp-includes/taxonomy.php */
  2583. do_action( 'edited_terms', $term_id, $taxonomy );
  2584. $tt_id = $wpdb->get_var( $wpdb->prepare( "SELECT tt.term_taxonomy_id FROM $wpdb->term_taxonomy AS tt INNER JOIN $wpdb->terms AS t ON tt.term_id = t.term_id WHERE tt.taxonomy = %s AND t.term_id = %d", $taxonomy, $term_id) );
  2585. /**
  2586. * Fires immediate before a term-taxonomy relationship is updated.
  2587. *
  2588. * @since 2.9.0
  2589. *
  2590. * @param int $tt_id Term taxonomy ID.
  2591. * @param string $taxonomy Taxonomy slug.
  2592. */
  2593. do_action( 'edit_term_taxonomy', $tt_id, $taxonomy );
  2594. $wpdb->update( $wpdb->term_taxonomy, compact( 'term_id', 'taxonomy', 'description', 'parent' ), array( 'term_taxonomy_id' => $tt_id ) );
  2595. /**
  2596. * Fires immediately after a term-taxonomy relationship is updated.
  2597. *
  2598. * @since 2.9.0
  2599. *
  2600. * @param int $tt_id Term taxonomy ID.
  2601. * @param string $taxonomy Taxonomy slug.
  2602. */
  2603. do_action( 'edited_term_taxonomy', $tt_id, $taxonomy );
  2604. // Clean the relationship caches for all object types using this term
  2605. $objects = $wpdb->get_col( $wpdb->prepare( "SELECT object_id FROM $wpdb->term_relationships WHERE term_taxonomy_id = %d", $tt_id ) );
  2606. $tax_object = get_taxonomy( $taxonomy );
  2607. foreach ( $tax_object->object_type as $object_type ) {
  2608. clean_object_term_cache( $objects, $object_type );
  2609. }
  2610. /**
  2611. * Fires after a term has been updated, but before the term cache has been cleaned.
  2612. *
  2613. * @since 2.3.0
  2614. *
  2615. * @param int $term_id Term ID.
  2616. * @param int $tt_id Term taxonomy ID.
  2617. * @param string $taxonomy Taxonomy slug.
  2618. */
  2619. do_action( "edit_term", $term_id, $tt_id, $taxonomy );
  2620. /**
  2621. * Fires after a term in a specific taxonomy has been updated, but before the term
  2622. * cache has been cleaned.
  2623. *
  2624. * The dynamic portion of the hook name, $taxonomy, refers to the taxonomy slug.
  2625. *
  2626. * @since 2.3.0
  2627. *
  2628. * @param int $term_id Term ID.
  2629. * @param int $tt_id Term taxonomy ID.
  2630. */
  2631. do_action( "edit_$taxonomy", $term_id, $tt_id );
  2632. /** This filter is documented in wp-includes/taxonomy.php */
  2633. $term_id = apply_filters( 'term_id_filter', $term_id, $tt_id );
  2634. clean_term_cache($term_id, $taxonomy);
  2635. /**
  2636. * Fires after a term has been updated, and the term cache has been cleaned.
  2637. *
  2638. * @since 2.3.0
  2639. *
  2640. * @param int $term_id Term ID.
  2641. * @param int $tt_id Term taxonomy ID.
  2642. * @param string $taxonomy Taxonomy slug.
  2643. */
  2644. do_action( "edited_term", $term_id, $tt_id, $taxonomy );
  2645. /**
  2646. * Fires after a term for a specific taxonomy has been updated, and the term
  2647. * cache has been cleaned.
  2648. *
  2649. * The dynamic portion of the hook name, $taxonomy, refers to the taxonomy slug.
  2650. *
  2651. * @since 2.3.0
  2652. *
  2653. * @param int $term_id Term ID.
  2654. * @param int $tt_id Term taxonomy ID.
  2655. */
  2656. do_action( "edited_$taxonomy", $term_id, $tt_id );
  2657. return array('term_id' => $term_id, 'term_taxonomy_id' => $tt_id);
  2658. }
  2659. /**
  2660. * Enable or disable term counting.
  2661. *
  2662. * @since 2.5.0
  2663. *
  2664. * @param bool $defer Optional. Enable if true, disable if false.
  2665. * @return bool Whether term counting is enabled or disabled.
  2666. */
  2667. function wp_defer_term_counting($defer=null) {
  2668. static $_defer = false;
  2669. if ( is_bool($defer) ) {
  2670. $_defer = $defer;
  2671. // flush any deferred counts
  2672. if ( !$defer )
  2673. wp_update_term_count( null, null, true );
  2674. }
  2675. return $_defer;
  2676. }
  2677. /**
  2678. * Updates the amount of terms in taxonomy.
  2679. *
  2680. * If there is a taxonomy callback applied, then it will be called for updating
  2681. * the count.
  2682. *
  2683. * The default action is to count what the amount of terms have the relationship
  2684. * of term ID. Once that is done, then update the database.
  2685. *
  2686. * @since 2.3.0
  2687. * @uses $wpdb
  2688. *
  2689. * @param int|array $terms The term_taxonomy_id of the terms
  2690. * @param string $taxonomy The context of the term.
  2691. * @return bool If no terms will return false, and if successful will return true.
  2692. */
  2693. function wp_update_term_count( $terms, $taxonomy, $do_deferred=false ) {
  2694. static $_deferred = array();
  2695. if ( $do_deferred ) {
  2696. foreach ( (array) array_keys($_deferred) as $tax ) {
  2697. wp_update_term_count_now( $_deferred[$tax], $tax );
  2698. unset( $_deferred[$tax] );
  2699. }
  2700. }
  2701. if ( empty($terms) )
  2702. return false;
  2703. if ( !is_array($terms) )
  2704. $terms = array($terms);
  2705. if ( wp_defer_term_counting() ) {
  2706. if ( !isset($_deferred[$taxonomy]) )
  2707. $_deferred[$taxonomy] = array();
  2708. $_deferred[$taxonomy] = array_unique( array_merge($_deferred[$taxonomy], $terms) );
  2709. return true;
  2710. }
  2711. return wp_update_term_count_now( $terms, $taxonomy );
  2712. }
  2713. /**
  2714. * Perform term count update immediately.
  2715. *
  2716. * @since 2.5.0
  2717. *
  2718. * @param array $terms The term_taxonomy_id of terms to update.
  2719. * @param string $taxonomy The context of the term.
  2720. * @return bool Always true when complete.
  2721. */
  2722. function wp_update_term_count_now( $terms, $taxonomy ) {
  2723. global $wpdb;
  2724. $terms = array_map('intval', $terms);
  2725. $taxonomy = get_taxonomy($taxonomy);
  2726. if ( !empty($taxonomy->update_count_callback) ) {
  2727. call_user_func($taxonomy->update_count_callback, $terms, $taxonomy);
  2728. } else {
  2729. $object_types = (array) $taxonomy->object_type;
  2730. foreach ( $object_types as &$object_type ) {
  2731. if ( 0 === strpos( $object_type, 'attachment:' ) )
  2732. list( $object_type ) = explode( ':', $object_type );
  2733. }
  2734. if ( $object_types == array_filter( $object_types, 'post_type_exists' ) ) {
  2735. // Only post types are attached to this taxonomy
  2736. _update_post_term_count( $terms, $taxonomy );
  2737. } else {
  2738. // Default count updater
  2739. _update_generic_term_count( $terms, $taxonomy );
  2740. }
  2741. }
  2742. clean_term_cache($terms, '', false);
  2743. return true;
  2744. }
  2745. //
  2746. // Cache
  2747. //
  2748. /**
  2749. * Removes the taxonomy relationship to terms from the cache.
  2750. *
  2751. * Will remove the entire taxonomy relationship containing term $object_id. The
  2752. * term IDs have to exist within the taxonomy $object_type for the deletion to
  2753. * take place.
  2754. *
  2755. * @since 2.3.0
  2756. *
  2757. * @see get_object_taxonomies() for more on $object_type
  2758. *
  2759. * @param int|array $object_ids Single or list of term object ID(s)
  2760. * @param array|string $object_type The taxonomy object type
  2761. */
  2762. function clean_object_term_cache($object_ids, $object_type) {
  2763. if ( !is_array($object_ids) )
  2764. $object_ids = array($object_ids);
  2765. $taxonomies = get_object_taxonomies( $object_type );
  2766. foreach ( $object_ids as $id ) {
  2767. foreach ( $taxonomies as $taxonomy ) {
  2768. wp_cache_delete($id, "{$taxonomy}_relationships");
  2769. }
  2770. }
  2771. /**
  2772. * Fires after the object term cache has been cleaned.
  2773. *
  2774. * @since 2.5.0
  2775. *
  2776. * @param array $object_ids An array of object IDs.
  2777. * @param string $objet_type Object type.
  2778. */
  2779. do_action( 'clean_object_term_cache', $object_ids, $object_type );
  2780. }
  2781. /**
  2782. * Will remove all of the term ids from the cache.
  2783. *
  2784. * @since 2.3.0
  2785. * @uses $wpdb
  2786. *
  2787. * @param int|array $ids Single or list of Term IDs
  2788. * @param string $taxonomy Can be empty and will assume tt_ids, else will use for context.
  2789. * @param bool $clean_taxonomy Whether to clean taxonomy wide caches (true), or just individual term object caches (false). Default is true.
  2790. */
  2791. function clean_term_cache($ids, $taxonomy = '', $clean_taxonomy = true) {
  2792. global $wpdb;
  2793. if ( !is_array($ids) )
  2794. $ids = array($ids);
  2795. $taxonomies = array();
  2796. // If no taxonomy, assume tt_ids.
  2797. if ( empty($taxonomy) ) {
  2798. $tt_ids = array_map('intval', $ids);
  2799. $tt_ids = implode(', ', $tt_ids);
  2800. $terms = $wpdb->get_results("SELECT term_id, taxonomy FROM $wpdb->term_taxonomy WHERE term_taxonomy_id IN ($tt_ids)");
  2801. $ids = array();
  2802. foreach ( (array) $terms as $term ) {
  2803. $taxonomies[] = $term->taxonomy;
  2804. $ids[] = $term->term_id;
  2805. wp_cache_delete($term->term_id, $term->taxonomy);
  2806. }
  2807. $taxonomies = array_unique($taxonomies);
  2808. } else {
  2809. $taxonomies = array($taxonomy);
  2810. foreach ( $taxonomies as $taxonomy ) {
  2811. foreach ( $ids as $id ) {
  2812. wp_cache_delete($id, $taxonomy);
  2813. }
  2814. }
  2815. }
  2816. foreach ( $taxonomies as $taxonomy ) {
  2817. if ( $clean_taxonomy ) {
  2818. wp_cache_delete('all_ids', $taxonomy);
  2819. wp_cache_delete('get', $taxonomy);
  2820. delete_option("{$taxonomy}_children");
  2821. // Regenerate {$taxonomy}_children
  2822. _get_term_hierarchy($taxonomy);
  2823. }
  2824. /**
  2825. * Fires once after each taxonomy's term cache has been cleaned.
  2826. *
  2827. * @since 2.5.0
  2828. *
  2829. * @param array $ids An array of term IDs.
  2830. * @param string $taxonomy Taxonomy slug.
  2831. */
  2832. do_action( 'clean_term_cache', $ids, $taxonomy );
  2833. }
  2834. wp_cache_set( 'last_changed', microtime(), 'terms' );
  2835. }
  2836. /**
  2837. * Retrieves the taxonomy relationship to the term object id.
  2838. *
  2839. * @since 2.3.0
  2840. *
  2841. * @uses wp_cache_get() Retrieves taxonomy relationship from cache
  2842. *
  2843. * @param int|array $id Term object ID
  2844. * @param string $taxonomy Taxonomy Name
  2845. * @return bool|array Empty array if $terms found, but not $taxonomy. False if nothing is in cache for $taxonomy and $id.
  2846. */
  2847. function get_object_term_cache($id, $taxonomy) {
  2848. $cache = wp_cache_get($id, "{$taxonomy}_relationships");
  2849. return $cache;
  2850. }
  2851. /**
  2852. * Updates the cache for Term ID(s).
  2853. *
  2854. * Will only update the cache for terms not already cached.
  2855. *
  2856. * The $object_ids expects that the ids be separated by commas, if it is a
  2857. * string.
  2858. *
  2859. * It should be noted that update_object_term_cache() is very time extensive. It
  2860. * is advised that the function is not called very often or at least not for a
  2861. * lot of terms that exist in a lot of taxonomies. The amount of time increases
  2862. * for each term and it also increases for each taxonomy the term belongs to.
  2863. *
  2864. * @since 2.3.0
  2865. * @uses wp_get_object_terms() Used to get terms from the database to update
  2866. *
  2867. * @param string|array $object_ids Single or list of term object ID(s)
  2868. * @param array|string $object_type The taxonomy object type
  2869. * @return null|bool Null value is given with empty $object_ids. False if
  2870. */
  2871. function update_object_term_cache($object_ids, $object_type) {
  2872. if ( empty($object_ids) )
  2873. return;
  2874. if ( !is_array($object_ids) )
  2875. $object_ids = explode(',', $object_ids);
  2876. $object_ids = array_map('intval', $object_ids);
  2877. $taxonomies = get_object_taxonomies($object_type);
  2878. $ids = array();
  2879. foreach ( (array) $object_ids as $id ) {
  2880. foreach ( $taxonomies as $taxonomy ) {
  2881. if ( false === wp_cache_get($id, "{$taxonomy}_relationships") ) {
  2882. $ids[] = $id;
  2883. break;
  2884. }
  2885. }
  2886. }
  2887. if ( empty( $ids ) )
  2888. return false;
  2889. $terms = wp_get_object_terms($ids, $taxonomies, array('fields' => 'all_with_object_id'));
  2890. $object_terms = array();
  2891. foreach ( (array) $terms as $term )
  2892. $object_terms[$term->object_id][$term->taxonomy][$term->term_id] = $term;
  2893. foreach ( $ids as $id ) {
  2894. foreach ( $taxonomies as $taxonomy ) {
  2895. if ( ! isset($object_terms[$id][$taxonomy]) ) {
  2896. if ( !isset($object_terms[$id]) )
  2897. $object_terms[$id] = array();
  2898. $object_terms[$id][$taxonomy] = array();
  2899. }
  2900. }
  2901. }
  2902. foreach ( $object_terms as $id => $value ) {
  2903. foreach ( $value as $taxonomy => $terms ) {
  2904. wp_cache_add( $id, $terms, "{$taxonomy}_relationships" );
  2905. }
  2906. }
  2907. }
  2908. /**
  2909. * Updates Terms to Taxonomy in cache.
  2910. *
  2911. * @since 2.3.0
  2912. *
  2913. * @param array $terms List of Term objects to change
  2914. * @param string $taxonomy Optional. Update Term to this taxonomy in cache
  2915. */
  2916. function update_term_cache($terms, $taxonomy = '') {
  2917. foreach ( (array) $terms as $term ) {
  2918. $term_taxonomy = $taxonomy;
  2919. if ( empty($term_taxonomy) )
  2920. $term_taxonomy = $term->taxonomy;
  2921. wp_cache_add($term->term_id, $term, $term_taxonomy);
  2922. }
  2923. }
  2924. //
  2925. // Private
  2926. //
  2927. /**
  2928. * Retrieves children of taxonomy as Term IDs.
  2929. *
  2930. * @access private
  2931. * @since 2.3.0
  2932. *
  2933. * @uses update_option() Stores all of the children in "$taxonomy_children"
  2934. * option. That is the name of the taxonomy, immediately followed by '_children'.
  2935. *
  2936. * @param string $taxonomy Taxonomy Name
  2937. * @return array Empty if $taxonomy isn't hierarchical or returns children as Term IDs.
  2938. */
  2939. function _get_term_hierarchy($taxonomy) {
  2940. if ( !is_taxonomy_hierarchical($taxonomy) )
  2941. return array();
  2942. $children = get_option("{$taxonomy}_children");
  2943. if ( is_array($children) )
  2944. return $children;
  2945. $children = array();
  2946. $terms = get_terms($taxonomy, array('get' => 'all', 'orderby' => 'id', 'fields' => 'id=>parent'));
  2947. foreach ( $terms as $term_id => $parent ) {
  2948. if ( $parent > 0 )
  2949. $children[$parent][] = $term_id;
  2950. }
  2951. update_option("{$taxonomy}_children", $children);
  2952. return $children;
  2953. }
  2954. /**
  2955. * Get the subset of $terms that are descendants of $term_id.
  2956. *
  2957. * If $terms is an array of objects, then _get_term_children returns an array of objects.
  2958. * If $terms is an array of IDs, then _get_term_children returns an array of IDs.
  2959. *
  2960. * @access private
  2961. * @since 2.3.0
  2962. *
  2963. * @param int $term_id The ancestor term: all returned terms should be descendants of $term_id.
  2964. * @param array $terms The set of terms---either an array of term objects or term IDs---from which those that are descendants of $term_id will be chosen.
  2965. * @param string $taxonomy The taxonomy which determines the hierarchy of the terms.
  2966. * @return array The subset of $terms that are descendants of $term_id.
  2967. */
  2968. function _get_term_children($term_id, $terms, $taxonomy) {
  2969. $empty_array = array();
  2970. if ( empty($terms) )
  2971. return $empty_array;
  2972. $term_list = array();
  2973. $has_children = _get_term_hierarchy($taxonomy);
  2974. if ( ( 0 != $term_id ) && ! isset($has_children[$term_id]) )
  2975. return $empty_array;
  2976. foreach ( (array) $terms as $term ) {
  2977. $use_id = false;
  2978. if ( !is_object($term) ) {
  2979. $term = get_term($term, $taxonomy);
  2980. if ( is_wp_error( $term ) )
  2981. return $term;
  2982. $use_id = true;
  2983. }
  2984. if ( $term->term_id == $term_id ) {
  2985. continue;
  2986. }
  2987. if ( $term->parent == $term_id ) {
  2988. if ( $use_id )
  2989. $term_list[] = $term->term_id;
  2990. else
  2991. $term_list[] = $term;
  2992. if ( !isset($has_children[$term->term_id]) )
  2993. continue;
  2994. if ( $children = _get_term_children($term->term_id, $terms, $taxonomy) )
  2995. $term_list = array_merge($term_list, $children);
  2996. }
  2997. }
  2998. return $term_list;
  2999. }
  3000. /**
  3001. * Add count of children to parent count.
  3002. *
  3003. * Recalculates term counts by including items from child terms. Assumes all
  3004. * relevant children are already in the $terms argument.
  3005. *
  3006. * @access private
  3007. * @since 2.3.0
  3008. * @uses $wpdb
  3009. *
  3010. * @param array $terms List of Term IDs
  3011. * @param string $taxonomy Term Context
  3012. * @return null Will break from function if conditions are not met.
  3013. */
  3014. function _pad_term_counts(&$terms, $taxonomy) {
  3015. global $wpdb;
  3016. // This function only works for hierarchical taxonomies like post categories.
  3017. if ( !is_taxonomy_hierarchical( $taxonomy ) )
  3018. return;
  3019. $term_hier = _get_term_hierarchy($taxonomy);
  3020. if ( empty($term_hier) )
  3021. return;
  3022. $term_items = array();
  3023. foreach ( (array) $terms as $key => $term ) {
  3024. $terms_by_id[$term->term_id] = & $terms[$key];
  3025. $term_ids[$term->term_taxonomy_id] = $term->term_id;
  3026. }
  3027. // Get the object and term ids and stick them in a lookup table
  3028. $tax_obj = get_taxonomy($taxonomy);
  3029. $object_types = esc_sql($tax_obj->object_type);
  3030. $results = $wpdb->get_results("SELECT object_id, term_taxonomy_id FROM $wpdb->term_relationships INNER JOIN $wpdb->posts ON object_id = ID WHERE term_taxonomy_id IN (" . implode(',', array_keys($term_ids)) . ") AND post_type IN ('" . implode("', '", $object_types) . "') AND post_status = 'publish'");
  3031. foreach ( $results as $row ) {
  3032. $id = $term_ids[$row->term_taxonomy_id];
  3033. $term_items[$id][$row->object_id] = isset($term_items[$id][$row->object_id]) ? ++$term_items[$id][$row->object_id] : 1;
  3034. }
  3035. // Touch every ancestor's lookup row for each post in each term
  3036. foreach ( $term_ids as $term_id ) {
  3037. $child = $term_id;
  3038. while ( !empty( $terms_by_id[$child] ) && $parent = $terms_by_id[$child]->parent ) {
  3039. if ( !empty( $term_items[$term_id] ) )
  3040. foreach ( $term_items[$term_id] as $item_id => $touches ) {
  3041. $term_items[$parent][$item_id] = isset($term_items[$parent][$item_id]) ? ++$term_items[$parent][$item_id]: 1;
  3042. }
  3043. $child = $parent;
  3044. }
  3045. }
  3046. // Transfer the touched cells
  3047. foreach ( (array) $term_items as $id => $items )
  3048. if ( isset($terms_by_id[$id]) )
  3049. $terms_by_id[$id]->count = count($items);
  3050. }
  3051. //
  3052. // Default callbacks
  3053. //
  3054. /**
  3055. * Will update term count based on object types of the current taxonomy.
  3056. *
  3057. * Private function for the default callback for post_tag and category
  3058. * taxonomies.
  3059. *
  3060. * @access private
  3061. * @since 2.3.0
  3062. * @uses $wpdb
  3063. *
  3064. * @param array $terms List of Term taxonomy IDs
  3065. * @param object $taxonomy Current taxonomy object of terms
  3066. */
  3067. function _update_post_term_count( $terms, $taxonomy ) {
  3068. global $wpdb;
  3069. $object_types = (array) $taxonomy->object_type;
  3070. foreach ( $object_types as &$object_type )
  3071. list( $object_type ) = explode( ':', $object_type );
  3072. $object_types = array_unique( $object_types );
  3073. if ( false !== ( $check_attachments = array_search( 'attachment', $object_types ) ) ) {
  3074. unset( $object_types[ $check_attachments ] );
  3075. $check_attachments = true;
  3076. }
  3077. if ( $object_types )
  3078. $object_types = esc_sql( array_filter( $object_types, 'post_type_exists' ) );
  3079. foreach ( (array) $terms as $term ) {
  3080. $count = 0;
  3081. // Attachments can be 'inherit' status, we need to base count off the parent's status if so
  3082. if ( $check_attachments )
  3083. $count += (int) $wpdb->get_var( $wpdb->prepare( "SELECT COUNT(*) FROM $wpdb->term_relationships, $wpdb->posts p1 WHERE p1.ID = $wpdb->term_relationships.object_id AND ( post_status = 'publish' OR ( post_status = 'inherit' AND post_parent > 0 AND ( SELECT post_status FROM $wpdb->posts WHERE ID = p1.post_parent ) = 'publish' ) ) AND post_type = 'attachment' AND term_taxonomy_id = %d", $term ) );
  3084. if ( $object_types )
  3085. $count += (int) $wpdb->get_var( $wpdb->prepare( "SELECT COUNT(*) FROM $wpdb->term_relationships, $wpdb->posts WHERE $wpdb->posts.ID = $wpdb->term_relationships.object_id AND post_status = 'publish' AND post_type IN ('" . implode("', '", $object_types ) . "') AND term_taxonomy_id = %d", $term ) );
  3086. /** This action is documented in wp-includes/taxonomy.php */
  3087. do_action( 'edit_term_taxonomy', $term, $taxonomy );
  3088. $wpdb->update( $wpdb->term_taxonomy, compact( 'count' ), array( 'term_taxonomy_id' => $term ) );
  3089. /** This action is documented in wp-includes/taxonomy.php */
  3090. do_action( 'edited_term_taxonomy', $term, $taxonomy );
  3091. }
  3092. }
  3093. /**
  3094. * Will update term count based on number of objects.
  3095. *
  3096. * Default callback for the link_category taxonomy.
  3097. *
  3098. * @since 3.3.0
  3099. * @uses $wpdb
  3100. *
  3101. * @param array $terms List of Term taxonomy IDs
  3102. * @param object $taxonomy Current taxonomy object of terms
  3103. */
  3104. function _update_generic_term_count( $terms, $taxonomy ) {
  3105. global $wpdb;
  3106. foreach ( (array) $terms as $term ) {
  3107. $count = $wpdb->get_var( $wpdb->prepare( "SELECT COUNT(*) FROM $wpdb->term_relationships WHERE term_taxonomy_id = %d", $term ) );
  3108. /** This action is documented in wp-includes/taxonomy.php */
  3109. do_action( 'edit_term_taxonomy', $term, $taxonomy );
  3110. $wpdb->update( $wpdb->term_taxonomy, compact( 'count' ), array( 'term_taxonomy_id' => $term ) );
  3111. /** This action is documented in wp-includes/taxonomy.php */
  3112. do_action( 'edited_term_taxonomy', $term, $taxonomy );
  3113. }
  3114. }
  3115. /**
  3116. * Generates a permalink for a taxonomy term archive.
  3117. *
  3118. * @since 2.5.0
  3119. *
  3120. * @param object|int|string $term
  3121. * @param string $taxonomy (optional if $term is object)
  3122. * @return string|WP_Error HTML link to taxonomy term archive on success, WP_Error if term does not exist.
  3123. */
  3124. function get_term_link( $term, $taxonomy = '') {
  3125. global $wp_rewrite;
  3126. if ( !is_object($term) ) {
  3127. if ( is_int($term) ) {
  3128. $term = get_term($term, $taxonomy);
  3129. } else {
  3130. $term = get_term_by('slug', $term, $taxonomy);
  3131. }
  3132. }
  3133. if ( !is_object($term) )
  3134. $term = new WP_Error('invalid_term', __('Empty Term'));
  3135. if ( is_wp_error( $term ) )
  3136. return $term;
  3137. $taxonomy = $term->taxonomy;
  3138. $termlink = $wp_rewrite->get_extra_permastruct($taxonomy);
  3139. $slug = $term->slug;
  3140. $t = get_taxonomy($taxonomy);
  3141. if ( empty($termlink) ) {
  3142. if ( 'category' == $taxonomy )
  3143. $termlink = '?cat=' . $term->term_id;
  3144. elseif ( $t->query_var )
  3145. $termlink = "?$t->query_var=$slug";
  3146. else
  3147. $termlink = "?taxonomy=$taxonomy&term=$slug";
  3148. $termlink = home_url($termlink);
  3149. } else {
  3150. if ( $t->rewrite['hierarchical'] ) {
  3151. $hierarchical_slugs = array();
  3152. $ancestors = get_ancestors($term->term_id, $taxonomy);
  3153. foreach ( (array)$ancestors as $ancestor ) {
  3154. $ancestor_term = get_term($ancestor, $taxonomy);
  3155. $hierarchical_slugs[] = $ancestor_term->slug;
  3156. }
  3157. $hierarchical_slugs = array_reverse($hierarchical_slugs);
  3158. $hierarchical_slugs[] = $slug;
  3159. $termlink = str_replace("%$taxonomy%", implode('/', $hierarchical_slugs), $termlink);
  3160. } else {
  3161. $termlink = str_replace("%$taxonomy%", $slug, $termlink);
  3162. }
  3163. $termlink = home_url( user_trailingslashit($termlink, 'category') );
  3164. }
  3165. // Back Compat filters.
  3166. if ( 'post_tag' == $taxonomy ) {
  3167. /**
  3168. * Filter the tag link.
  3169. *
  3170. * @since 2.3.0
  3171. * @deprecated 2.5.0 Use 'term_link' instead.
  3172. *
  3173. * @param string $termlink Tag link URL.
  3174. * @param int $term_id Term ID.
  3175. */
  3176. $termlink = apply_filters( 'tag_link', $termlink, $term->term_id );
  3177. } elseif ( 'category' == $taxonomy ) {
  3178. /**
  3179. * Filter the category link.
  3180. *
  3181. * @since 1.5.0
  3182. * @deprecated 2.5.0 Use 'term_link' instead.
  3183. *
  3184. * @param string $termlink Category link URL.
  3185. * @param int $term_id Term ID.
  3186. */
  3187. $termlink = apply_filters( 'category_link', $termlink, $term->term_id );
  3188. }
  3189. /**
  3190. * Filter the term link.
  3191. *
  3192. * @since 2.5.0
  3193. *
  3194. * @param string $termlink Term link URL.
  3195. * @param object $term Term object.
  3196. * @param string $taxonomy Taxonomy slug.
  3197. */
  3198. return apply_filters( 'term_link', $termlink, $term, $taxonomy );
  3199. }
  3200. /**
  3201. * Display the taxonomies of a post with available options.
  3202. *
  3203. * This function can be used within the loop to display the taxonomies for a
  3204. * post without specifying the Post ID. You can also use it outside the Loop to
  3205. * display the taxonomies for a specific post.
  3206. *
  3207. * The available defaults are:
  3208. * 'post' : default is 0. The post ID to get taxonomies of.
  3209. * 'before' : default is empty string. Display before taxonomies list.
  3210. * 'sep' : default is empty string. Separate every taxonomy with value in this.
  3211. * 'after' : default is empty string. Display this after the taxonomies list.
  3212. * 'template' : The template to use for displaying the taxonomy terms.
  3213. *
  3214. * @since 2.5.0
  3215. * @uses get_the_taxonomies()
  3216. *
  3217. * @param array $args Override the defaults.
  3218. */
  3219. function the_taxonomies($args = array()) {
  3220. $defaults = array(
  3221. 'post' => 0,
  3222. 'before' => '',
  3223. 'sep' => ' ',
  3224. 'after' => '',
  3225. 'template' => '%s: %l.'
  3226. );
  3227. $r = wp_parse_args( $args, $defaults );
  3228. extract( $r, EXTR_SKIP );
  3229. echo $before . join($sep, get_the_taxonomies($post, $r)) . $after;
  3230. }
  3231. /**
  3232. * Retrieve all taxonomies associated with a post.
  3233. *
  3234. * This function can be used within the loop. It will also return an array of
  3235. * the taxonomies with links to the taxonomy and name.
  3236. *
  3237. * @since 2.5.0
  3238. *
  3239. * @param int|WP_Post $post Optional. Post ID or post object.
  3240. * @param array $args Override the defaults.
  3241. * @return array
  3242. */
  3243. function get_the_taxonomies($post = 0, $args = array() ) {
  3244. $post = get_post( $post );
  3245. $args = wp_parse_args( $args, array(
  3246. 'template' => '%s: %l.',
  3247. ) );
  3248. extract( $args, EXTR_SKIP );
  3249. $taxonomies = array();
  3250. if ( !$post )
  3251. return $taxonomies;
  3252. foreach ( get_object_taxonomies($post) as $taxonomy ) {
  3253. $t = (array) get_taxonomy($taxonomy);
  3254. if ( empty($t['label']) )
  3255. $t['label'] = $taxonomy;
  3256. if ( empty($t['args']) )
  3257. $t['args'] = array();
  3258. if ( empty($t['template']) )
  3259. $t['template'] = $template;
  3260. $terms = get_object_term_cache($post->ID, $taxonomy);
  3261. if ( false === $terms )
  3262. $terms = wp_get_object_terms($post->ID, $taxonomy, $t['args']);
  3263. $links = array();
  3264. foreach ( $terms as $term )
  3265. $links[] = "<a href='" . esc_attr( get_term_link($term) ) . "'>$term->name</a>";
  3266. if ( $links )
  3267. $taxonomies[$taxonomy] = wp_sprintf($t['template'], $t['label'], $links, $terms);
  3268. }
  3269. return $taxonomies;
  3270. }
  3271. /**
  3272. * Retrieve all taxonomies of a post with just the names.
  3273. *
  3274. * @since 2.5.0
  3275. * @uses get_object_taxonomies()
  3276. *
  3277. * @param int|WP_Post $post Optional. Post ID or post object.
  3278. * @return array
  3279. */
  3280. function get_post_taxonomies($post = 0) {
  3281. $post = get_post( $post );
  3282. return get_object_taxonomies($post);
  3283. }
  3284. /**
  3285. * Determine if the given object is associated with any of the given terms.
  3286. *
  3287. * The given terms are checked against the object's terms' term_ids, names and slugs.
  3288. * Terms given as integers will only be checked against the object's terms' term_ids.
  3289. * If no terms are given, determines if object is associated with any terms in the given taxonomy.
  3290. *
  3291. * @since 2.7.0
  3292. * @uses get_object_term_cache()
  3293. * @uses wp_get_object_terms()
  3294. *
  3295. * @param int $object_id ID of the object (post ID, link ID, ...)
  3296. * @param string $taxonomy Single taxonomy name
  3297. * @param int|string|array $terms Optional. Term term_id, name, slug or array of said
  3298. * @return bool|WP_Error. WP_Error on input error.
  3299. */
  3300. function is_object_in_term( $object_id, $taxonomy, $terms = null ) {
  3301. if ( !$object_id = (int) $object_id )
  3302. return new WP_Error( 'invalid_object', __( 'Invalid object ID' ) );
  3303. $object_terms = get_object_term_cache( $object_id, $taxonomy );
  3304. if ( false === $object_terms )
  3305. $object_terms = wp_get_object_terms( $object_id, $taxonomy );
  3306. if ( is_wp_error( $object_terms ) )
  3307. return $object_terms;
  3308. if ( empty( $object_terms ) )
  3309. return false;
  3310. if ( empty( $terms ) )
  3311. return ( !empty( $object_terms ) );
  3312. $terms = (array) $terms;
  3313. if ( $ints = array_filter( $terms, 'is_int' ) )
  3314. $strs = array_diff( $terms, $ints );
  3315. else
  3316. $strs =& $terms;
  3317. foreach ( $object_terms as $object_term ) {
  3318. if ( $ints && in_array( $object_term->term_id, $ints ) ) return true; // If int, check against term_id
  3319. if ( $strs ) {
  3320. if ( in_array( $object_term->term_id, $strs ) ) return true;
  3321. if ( in_array( $object_term->name, $strs ) ) return true;
  3322. if ( in_array( $object_term->slug, $strs ) ) return true;
  3323. }
  3324. }
  3325. return false;
  3326. }
  3327. /**
  3328. * Determine if the given object type is associated with the given taxonomy.
  3329. *
  3330. * @since 3.0.0
  3331. * @uses get_object_taxonomies()
  3332. *
  3333. * @param string $object_type Object type string
  3334. * @param string $taxonomy Single taxonomy name
  3335. * @return bool True if object is associated with the taxonomy, otherwise false.
  3336. */
  3337. function is_object_in_taxonomy($object_type, $taxonomy) {
  3338. $taxonomies = get_object_taxonomies($object_type);
  3339. if ( empty($taxonomies) )
  3340. return false;
  3341. if ( in_array($taxonomy, $taxonomies) )
  3342. return true;
  3343. return false;
  3344. }
  3345. /**
  3346. * Get an array of ancestor IDs for a given object.
  3347. *
  3348. * @param int $object_id The ID of the object
  3349. * @param string $object_type The type of object for which we'll be retrieving ancestors.
  3350. * @return array of ancestors from lowest to highest in the hierarchy.
  3351. */
  3352. function get_ancestors($object_id = 0, $object_type = '') {
  3353. $object_id = (int) $object_id;
  3354. $ancestors = array();
  3355. if ( empty( $object_id ) ) {
  3356. /** This filter is documented in wp-includes/taxonomy.php */
  3357. return apply_filters( 'get_ancestors', $ancestors, $object_id, $object_type );
  3358. }
  3359. if ( is_taxonomy_hierarchical( $object_type ) ) {
  3360. $term = get_term($object_id, $object_type);
  3361. while ( ! is_wp_error($term) && ! empty( $term->parent ) && ! in_array( $term->parent, $ancestors ) ) {
  3362. $ancestors[] = (int) $term->parent;
  3363. $term = get_term($term->parent, $object_type);
  3364. }
  3365. } elseif ( post_type_exists( $object_type ) ) {
  3366. $ancestors = get_post_ancestors($object_id);
  3367. }
  3368. /**
  3369. * Filter a given object's ancestors.
  3370. *
  3371. * @since 3.1.0
  3372. *
  3373. * @param array $ancestors An array of object ancestors.
  3374. * @param int $object_id Object ID.
  3375. * @param string $object_type Type of object.
  3376. */
  3377. return apply_filters( 'get_ancestors', $ancestors, $object_id, $object_type );
  3378. }
  3379. /**
  3380. * Returns the term's parent's term_ID
  3381. *
  3382. * @since 3.1.0
  3383. *
  3384. * @param int $term_id
  3385. * @param string $taxonomy
  3386. *
  3387. * @return int|bool false on error
  3388. */
  3389. function wp_get_term_taxonomy_parent_id( $term_id, $taxonomy ) {
  3390. $term = get_term( $term_id, $taxonomy );
  3391. if ( !$term || is_wp_error( $term ) )
  3392. return false;
  3393. return (int) $term->parent;
  3394. }
  3395. /**
  3396. * Checks the given subset of the term hierarchy for hierarchy loops.
  3397. * Prevents loops from forming and breaks those that it finds.
  3398. *
  3399. * Attached to the wp_update_term_parent filter.
  3400. *
  3401. * @since 3.1.0
  3402. * @uses wp_find_hierarchy_loop()
  3403. *
  3404. * @param int $parent term_id of the parent for the term we're checking.
  3405. * @param int $term_id The term we're checking.
  3406. * @param string $taxonomy The taxonomy of the term we're checking.
  3407. *
  3408. * @return int The new parent for the term.
  3409. */
  3410. function wp_check_term_hierarchy_for_loops( $parent, $term_id, $taxonomy ) {
  3411. // Nothing fancy here - bail
  3412. if ( !$parent )
  3413. return 0;
  3414. // Can't be its own parent
  3415. if ( $parent == $term_id )
  3416. return 0;
  3417. // Now look for larger loops
  3418. if ( !$loop = wp_find_hierarchy_loop( 'wp_get_term_taxonomy_parent_id', $term_id, $parent, array( $taxonomy ) ) )
  3419. return $parent; // No loop
  3420. // Setting $parent to the given value causes a loop
  3421. if ( isset( $loop[$term_id] ) )
  3422. return 0;
  3423. // There's a loop, but it doesn't contain $term_id. Break the loop.
  3424. foreach ( array_keys( $loop ) as $loop_member )
  3425. wp_update_term( $loop_member, $taxonomy, array( 'parent' => 0 ) );
  3426. return $parent;
  3427. }