PageRenderTime 40ms CodeModel.GetById 22ms RepoModel.GetById 1ms app.codeStats 1ms

/wp-includes/taxonomy.php

https://github.com/webgefrickel/frckl-init-wordpress
PHP | 3453 lines | 1738 code | 463 blank | 1252 comment | 516 complexity | 3c481d816403a8e62a0b0107b634e8db MD5 | raw file
Possible License(s): LGPL-3.0, LGPL-2.1, GPL-2.0
  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. $post_format_base = apply_filters( 'post_format_rewrite_base', 'type' );
  25. $rewrite = array(
  26. 'category' => array(
  27. 'hierarchical' => true,
  28. 'slug' => get_option('category_base') ? get_option('category_base') : 'category',
  29. 'with_front' => ! get_option('category_base') || $wp_rewrite->using_index_permalinks(),
  30. 'ep_mask' => EP_CATEGORIES,
  31. ),
  32. 'post_tag' => array(
  33. 'slug' => get_option('tag_base') ? get_option('tag_base') : 'tag',
  34. 'with_front' => ! get_option('tag_base') || $wp_rewrite->using_index_permalinks(),
  35. 'ep_mask' => EP_TAGS,
  36. ),
  37. 'post_format' => $post_format_base ? array( 'slug' => $post_format_base ) : false,
  38. );
  39. }
  40. register_taxonomy( 'category', 'post', array(
  41. 'hierarchical' => true,
  42. 'query_var' => 'category_name',
  43. 'rewrite' => $rewrite['category'],
  44. 'public' => true,
  45. 'show_ui' => true,
  46. 'show_admin_column' => true,
  47. '_builtin' => true,
  48. ) );
  49. register_taxonomy( 'post_tag', 'post', array(
  50. 'hierarchical' => false,
  51. 'query_var' => 'tag',
  52. 'rewrite' => $rewrite['post_tag'],
  53. 'public' => true,
  54. 'show_ui' => true,
  55. 'show_admin_column' => true,
  56. '_builtin' => true,
  57. ) );
  58. register_taxonomy( 'nav_menu', 'nav_menu_item', array(
  59. 'public' => false,
  60. 'hierarchical' => false,
  61. 'labels' => array(
  62. 'name' => __( 'Navigation Menus' ),
  63. 'singular_name' => __( 'Navigation Menu' ),
  64. ),
  65. 'query_var' => false,
  66. 'rewrite' => false,
  67. 'show_ui' => false,
  68. '_builtin' => true,
  69. 'show_in_nav_menus' => false,
  70. ) );
  71. register_taxonomy( 'link_category', 'link', array(
  72. 'hierarchical' => false,
  73. 'labels' => array(
  74. 'name' => __( 'Link Categories' ),
  75. 'singular_name' => __( 'Link Category' ),
  76. 'search_items' => __( 'Search Link Categories' ),
  77. 'popular_items' => null,
  78. 'all_items' => __( 'All Link Categories' ),
  79. 'edit_item' => __( 'Edit Link Category' ),
  80. 'update_item' => __( 'Update Link Category' ),
  81. 'add_new_item' => __( 'Add New Link Category' ),
  82. 'new_item_name' => __( 'New Link Category Name' ),
  83. 'separate_items_with_commas' => null,
  84. 'add_or_remove_items' => null,
  85. 'choose_from_most_used' => null,
  86. ),
  87. 'capabilities' => array(
  88. 'manage_terms' => 'manage_links',
  89. 'edit_terms' => 'manage_links',
  90. 'delete_terms' => 'manage_links',
  91. 'assign_terms' => 'manage_links',
  92. ),
  93. 'query_var' => false,
  94. 'rewrite' => false,
  95. 'public' => false,
  96. 'show_ui' => false,
  97. '_builtin' => true,
  98. ) );
  99. register_taxonomy( 'post_format', 'post', array(
  100. 'public' => true,
  101. 'hierarchical' => false,
  102. 'labels' => array(
  103. 'name' => _x( 'Format', 'post format' ),
  104. 'singular_name' => _x( 'Format', 'post format' ),
  105. ),
  106. 'query_var' => true,
  107. 'rewrite' => $rewrite['post_format'],
  108. 'show_ui' => false,
  109. '_builtin' => true,
  110. 'show_in_nav_menus' => current_theme_supports( 'post-formats' ),
  111. ) );
  112. }
  113. add_action( 'init', 'create_initial_taxonomies', 0 ); // highest priority
  114. /**
  115. * Get a list of registered taxonomy objects.
  116. *
  117. * @package WordPress
  118. * @subpackage Taxonomy
  119. * @since 3.0.0
  120. * @uses $wp_taxonomies
  121. * @see register_taxonomy
  122. *
  123. * @param array $args An array of key => value arguments to match against the taxonomy objects.
  124. * @param string $output The type of output to return, either taxonomy 'names' or 'objects'. 'names' is the default.
  125. * @param string $operator The logical operation to perform. 'or' means only one element
  126. * from the array needs to match; 'and' means all elements must match. The default is 'and'.
  127. * @return array A list of taxonomy names or objects
  128. */
  129. function get_taxonomies( $args = array(), $output = 'names', $operator = 'and' ) {
  130. global $wp_taxonomies;
  131. $field = ('names' == $output) ? 'name' : false;
  132. return wp_filter_object_list($wp_taxonomies, $args, $operator, $field);
  133. }
  134. /**
  135. * Return all of the taxonomy names that are of $object_type.
  136. *
  137. * It appears that this function can be used to find all of the names inside of
  138. * $wp_taxonomies global variable.
  139. *
  140. * <code><?php $taxonomies = get_object_taxonomies('post'); ?></code> Should
  141. * result in <code>Array('category', 'post_tag')</code>
  142. *
  143. * @package WordPress
  144. * @subpackage Taxonomy
  145. * @since 2.3.0
  146. *
  147. * @uses $wp_taxonomies
  148. *
  149. * @param array|string|object $object Name of the type of taxonomy object, or an object (row from posts)
  150. * @param string $output The type of output to return, either taxonomy 'names' or 'objects'. 'names' is the default.
  151. * @return array The names of all taxonomy of $object_type.
  152. */
  153. function get_object_taxonomies($object, $output = 'names') {
  154. global $wp_taxonomies;
  155. if ( is_object($object) ) {
  156. if ( $object->post_type == 'attachment' )
  157. return get_attachment_taxonomies($object);
  158. $object = $object->post_type;
  159. }
  160. $object = (array) $object;
  161. $taxonomies = array();
  162. foreach ( (array) $wp_taxonomies as $tax_name => $tax_obj ) {
  163. if ( array_intersect($object, (array) $tax_obj->object_type) ) {
  164. if ( 'names' == $output )
  165. $taxonomies[] = $tax_name;
  166. else
  167. $taxonomies[ $tax_name ] = $tax_obj;
  168. }
  169. }
  170. return $taxonomies;
  171. }
  172. /**
  173. * Retrieves the taxonomy object of $taxonomy.
  174. *
  175. * The get_taxonomy function will first check that the parameter string given
  176. * is a taxonomy object and if it is, it will return it.
  177. *
  178. * @package WordPress
  179. * @subpackage Taxonomy
  180. * @since 2.3.0
  181. *
  182. * @uses $wp_taxonomies
  183. * @uses taxonomy_exists() Checks whether taxonomy exists
  184. *
  185. * @param string $taxonomy Name of taxonomy object to return
  186. * @return object|bool The Taxonomy Object or false if $taxonomy doesn't exist
  187. */
  188. function get_taxonomy( $taxonomy ) {
  189. global $wp_taxonomies;
  190. if ( ! taxonomy_exists( $taxonomy ) )
  191. return false;
  192. return $wp_taxonomies[$taxonomy];
  193. }
  194. /**
  195. * Checks that the taxonomy name exists.
  196. *
  197. * Formerly is_taxonomy(), introduced in 2.3.0.
  198. *
  199. * @package WordPress
  200. * @subpackage Taxonomy
  201. * @since 3.0.0
  202. *
  203. * @uses $wp_taxonomies
  204. *
  205. * @param string $taxonomy Name of taxonomy object
  206. * @return bool Whether the taxonomy exists.
  207. */
  208. function taxonomy_exists( $taxonomy ) {
  209. global $wp_taxonomies;
  210. return isset( $wp_taxonomies[$taxonomy] );
  211. }
  212. /**
  213. * Whether the taxonomy object is hierarchical.
  214. *
  215. * Checks to make sure that the taxonomy is an object first. Then Gets the
  216. * object, and finally returns the hierarchical value in the object.
  217. *
  218. * A false return value might also mean that the taxonomy does not exist.
  219. *
  220. * @package WordPress
  221. * @subpackage Taxonomy
  222. * @since 2.3.0
  223. *
  224. * @uses taxonomy_exists() Checks whether taxonomy exists
  225. * @uses get_taxonomy() Used to get the taxonomy object
  226. *
  227. * @param string $taxonomy Name of taxonomy object
  228. * @return bool Whether the taxonomy is hierarchical
  229. */
  230. function is_taxonomy_hierarchical($taxonomy) {
  231. if ( ! taxonomy_exists($taxonomy) )
  232. return false;
  233. $taxonomy = get_taxonomy($taxonomy);
  234. return $taxonomy->hierarchical;
  235. }
  236. /**
  237. * Create or modify a taxonomy object. Do not use before init.
  238. *
  239. * A simple function for creating or modifying a taxonomy object based on the
  240. * parameters given. The function will accept an array (third optional
  241. * parameter), along with strings for the taxonomy name and another string for
  242. * the object type.
  243. *
  244. * Nothing is returned, so expect error maybe or use taxonomy_exists() to check
  245. * whether taxonomy exists.
  246. *
  247. * Optional $args contents:
  248. *
  249. * - label - Name of the taxonomy shown in the menu. Usually plural. If not set, labels['name'] will be used.
  250. * - labels - An array of labels for this taxonomy.
  251. * * By default tag labels are used for non-hierarchical types and category labels for hierarchical ones.
  252. * * You can see accepted values in {@link get_taxonomy_labels()}.
  253. * - description - A short descriptive summary of what the taxonomy is for. Defaults to blank.
  254. * - public - If the taxonomy should be publicly queryable; //@TODO not implemented.
  255. * * Defaults to true.
  256. * - hierarchical - Whether the taxonomy is hierarchical (e.g. category). Defaults to false.
  257. * - show_ui -Whether to generate a default UI for managing this taxonomy in the admin.
  258. * * If not set, the default is inherited from public.
  259. * - show_in_menu - Where to show the taxonomy in the admin menu.
  260. * * If true, the taxonomy is shown as a submenu of the object type menu.
  261. * * If false, no menu is shown.
  262. * * show_ui must be true.
  263. * * If not set, the default is inherited from show_ui.
  264. * - show_in_nav_menus - Makes this taxonomy available for selection in navigation menus.
  265. * * If not set, the default is inherited from public.
  266. * - show_tagcloud - Whether to list the taxonomy in the Tag Cloud Widget.
  267. * * If not set, the default is inherited from show_ui.
  268. * - meta_box_cb - Provide a callback function for the meta box display. Defaults to
  269. * post_categories_meta_box for hierarchical taxonomies and post_tags_meta_box for non-hierarchical.
  270. * - capabilities - Array of capabilities for this taxonomy.
  271. * * You can see accepted values in this function.
  272. * - rewrite - Triggers the handling of rewrites for this taxonomy. Defaults to true, using $taxonomy as slug.
  273. * * To prevent rewrite, set to false.
  274. * * To specify rewrite rules, an array can be passed with any of these keys
  275. * * 'slug' => string Customize the permastruct slug. Defaults to $taxonomy key
  276. * * 'with_front' => bool Should the permastruct be prepended with WP_Rewrite::$front. Defaults to true.
  277. * * 'hierarchical' => bool Either hierarchical rewrite tag or not. Defaults to false.
  278. * * 'ep_mask' => const Assign an endpoint mask.
  279. * * If not specified, defaults to EP_NONE.
  280. * - query_var - Sets the query_var key for this taxonomy. Defaults to $taxonomy key
  281. * * If false, a taxonomy cannot be loaded at ?{query_var}={term_slug}
  282. * * If specified as a string, the query ?{query_var_string}={term_slug} will be valid.
  283. * - update_count_callback - Works much like a hook, in that it will be called when the count is updated.
  284. * * Defaults to _update_post_term_count() for taxonomies attached to post types, which then confirms
  285. * that the objects are published before counting them.
  286. * * Defaults to _update_generic_term_count() for taxonomies attached to other object types, such as links.
  287. * - _builtin - true if this taxonomy is a native or "built-in" taxonomy. THIS IS FOR INTERNAL USE ONLY!
  288. *
  289. * @since 2.3.0
  290. * @uses $wp_taxonomies Inserts new taxonomy object into the list
  291. * @uses $wp Adds query vars
  292. *
  293. * @param string $taxonomy Taxonomy key, must not exceed 32 characters.
  294. * @param array|string $object_type Name of the object type for the taxonomy object.
  295. * @param array|string $args See optional args description above.
  296. * @return null|WP_Error WP_Error if errors, otherwise null.
  297. */
  298. function register_taxonomy( $taxonomy, $object_type, $args = array() ) {
  299. global $wp_taxonomies, $wp;
  300. if ( ! is_array( $wp_taxonomies ) )
  301. $wp_taxonomies = array();
  302. $defaults = array(
  303. 'labels' => array(),
  304. 'description' => '',
  305. 'public' => true,
  306. 'hierarchical' => false,
  307. 'show_ui' => null,
  308. 'show_in_menu' => null,
  309. 'show_in_nav_menus' => null,
  310. 'show_tagcloud' => null,
  311. 'meta_box_cb' => null,
  312. 'capabilities' => array(),
  313. 'rewrite' => true,
  314. 'query_var' => $taxonomy,
  315. 'update_count_callback' => '',
  316. '_builtin' => false,
  317. );
  318. $args = wp_parse_args( $args, $defaults );
  319. if ( strlen( $taxonomy ) > 32 )
  320. return new WP_Error( 'taxonomy_too_long', __( 'Taxonomies cannot exceed 32 characters in length' ) );
  321. if ( false !== $args['query_var'] && ! empty( $wp ) ) {
  322. if ( true === $args['query_var'] )
  323. $args['query_var'] = $taxonomy;
  324. else
  325. $args['query_var'] = sanitize_title_with_dashes( $args['query_var'] );
  326. $wp->add_query_var( $args['query_var'] );
  327. }
  328. if ( false !== $args['rewrite'] && ( is_admin() || '' != get_option( 'permalink_structure' ) ) ) {
  329. $args['rewrite'] = wp_parse_args( $args['rewrite'], array(
  330. 'with_front' => true,
  331. 'hierarchical' => false,
  332. 'ep_mask' => EP_NONE,
  333. ) );
  334. if ( empty( $args['rewrite']['slug'] ) )
  335. $args['rewrite']['slug'] = sanitize_title_with_dashes( $taxonomy );
  336. if ( $args['hierarchical'] && $args['rewrite']['hierarchical'] )
  337. $tag = '(.+?)';
  338. else
  339. $tag = '([^/]+)';
  340. add_rewrite_tag( "%$taxonomy%", $tag, $args['query_var'] ? "{$args['query_var']}=" : "taxonomy=$taxonomy&term=" );
  341. add_permastruct( $taxonomy, "{$args['rewrite']['slug']}/%$taxonomy%", $args['rewrite'] );
  342. }
  343. // If not set, default to the setting for public.
  344. if ( null === $args['show_ui'] )
  345. $args['show_ui'] = $args['public'];
  346. // If not set, default to the setting for show_ui.
  347. if ( null === $args['show_in_menu' ] || ! $args['show_ui'] )
  348. $args['show_in_menu' ] = $args['show_ui'];
  349. // If not set, default to the setting for public.
  350. if ( null === $args['show_in_nav_menus'] )
  351. $args['show_in_nav_menus'] = $args['public'];
  352. // If not set, default to the setting for show_ui.
  353. if ( null === $args['show_tagcloud'] )
  354. $args['show_tagcloud'] = $args['show_ui'];
  355. $default_caps = array(
  356. 'manage_terms' => 'manage_categories',
  357. 'edit_terms' => 'manage_categories',
  358. 'delete_terms' => 'manage_categories',
  359. 'assign_terms' => 'edit_posts',
  360. );
  361. $args['cap'] = (object) array_merge( $default_caps, $args['capabilities'] );
  362. unset( $args['capabilities'] );
  363. $args['name'] = $taxonomy;
  364. $args['object_type'] = array_unique( (array) $object_type );
  365. $args['labels'] = get_taxonomy_labels( (object) $args );
  366. $args['label'] = $args['labels']->name;
  367. // If not set, use the default meta box
  368. if ( null === $args['meta_box_cb'] ) {
  369. if ( $args['hierarchical'] )
  370. $args['meta_box_cb'] = 'post_categories_meta_box';
  371. else
  372. $args['meta_box_cb'] = 'post_tags_meta_box';
  373. }
  374. $wp_taxonomies[ $taxonomy ] = (object) $args;
  375. // register callback handling for metabox
  376. add_filter( 'wp_ajax_add-' . $taxonomy, '_wp_ajax_add_hierarchical_term' );
  377. do_action( 'registered_taxonomy', $taxonomy, $object_type, $args );
  378. }
  379. /**
  380. * Builds an object with all taxonomy labels out of a taxonomy object
  381. *
  382. * Accepted keys of the label array in the taxonomy object:
  383. * - name - general name for the taxonomy, usually plural. The same as and overridden by $tax->label. Default is Tags/Categories
  384. * - singular_name - name for one object of this taxonomy. Default is Tag/Category
  385. * - search_items - Default is Search Tags/Search Categories
  386. * - popular_items - This string isn't used on hierarchical taxonomies. Default is Popular Tags
  387. * - all_items - Default is All Tags/All Categories
  388. * - parent_item - This string isn't used on non-hierarchical taxonomies. In hierarchical ones the default is Parent Category
  389. * - parent_item_colon - The same as <code>parent_item</code>, but with colon <code>:</code> in the end
  390. * - edit_item - Default is Edit Tag/Edit Category
  391. * - view_item - Default is View Tag/View Category
  392. * - update_item - Default is Update Tag/Update Category
  393. * - add_new_item - Default is Add New Tag/Add New Category
  394. * - new_item_name - Default is New Tag Name/New Category Name
  395. * - separate_items_with_commas - This string isn't used on hierarchical taxonomies. Default is "Separate tags with commas", used in the meta box.
  396. * - 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.
  397. * - 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.
  398. * - not_found - This string isn't used on hierarchical taxonomies. Default is "No tags found", used in the meta box.
  399. *
  400. * Above, the first default value is for non-hierarchical taxonomies (like tags) and the second one is for hierarchical taxonomies (like categories).
  401. *
  402. * @since 3.0.0
  403. * @param object $tax Taxonomy object
  404. * @return object object with all the labels as member variables
  405. */
  406. function get_taxonomy_labels( $tax ) {
  407. $tax->labels = (array) $tax->labels;
  408. if ( isset( $tax->helps ) && empty( $tax->labels['separate_items_with_commas'] ) )
  409. $tax->labels['separate_items_with_commas'] = $tax->helps;
  410. if ( isset( $tax->no_tagcloud ) && empty( $tax->labels['not_found'] ) )
  411. $tax->labels['not_found'] = $tax->no_tagcloud;
  412. $nohier_vs_hier_defaults = array(
  413. 'name' => array( _x( 'Tags', 'taxonomy general name' ), _x( 'Categories', 'taxonomy general name' ) ),
  414. 'singular_name' => array( _x( 'Tag', 'taxonomy singular name' ), _x( 'Category', 'taxonomy singular name' ) ),
  415. 'search_items' => array( __( 'Search Tags' ), __( 'Search Categories' ) ),
  416. 'popular_items' => array( __( 'Popular Tags' ), null ),
  417. 'all_items' => array( __( 'All Tags' ), __( 'All Categories' ) ),
  418. 'parent_item' => array( null, __( 'Parent Category' ) ),
  419. 'parent_item_colon' => array( null, __( 'Parent Category:' ) ),
  420. 'edit_item' => array( __( 'Edit Tag' ), __( 'Edit Category' ) ),
  421. 'view_item' => array( __( 'View Tag' ), __( 'View Category' ) ),
  422. 'update_item' => array( __( 'Update Tag' ), __( 'Update Category' ) ),
  423. 'add_new_item' => array( __( 'Add New Tag' ), __( 'Add New Category' ) ),
  424. 'new_item_name' => array( __( 'New Tag Name' ), __( 'New Category Name' ) ),
  425. 'separate_items_with_commas' => array( __( 'Separate tags with commas' ), null ),
  426. 'add_or_remove_items' => array( __( 'Add or remove tags' ), null ),
  427. 'choose_from_most_used' => array( __( 'Choose from the most used tags' ), null ),
  428. 'not_found' => array( __( 'No tags found.' ), null ),
  429. );
  430. $nohier_vs_hier_defaults['menu_name'] = $nohier_vs_hier_defaults['name'];
  431. return _get_custom_object_labels( $tax, $nohier_vs_hier_defaults );
  432. }
  433. /**
  434. * Add an already registered taxonomy to an object type.
  435. *
  436. * @package WordPress
  437. * @subpackage Taxonomy
  438. * @since 3.0.0
  439. * @uses $wp_taxonomies Modifies taxonomy object
  440. *
  441. * @param string $taxonomy Name of taxonomy object
  442. * @param string $object_type Name of the object type
  443. * @return bool True if successful, false if not
  444. */
  445. function register_taxonomy_for_object_type( $taxonomy, $object_type) {
  446. global $wp_taxonomies;
  447. if ( !isset($wp_taxonomies[$taxonomy]) )
  448. return false;
  449. if ( ! get_post_type_object($object_type) )
  450. return false;
  451. if ( ! in_array( $object_type, $wp_taxonomies[$taxonomy]->object_type ) )
  452. $wp_taxonomies[$taxonomy]->object_type[] = $object_type;
  453. return true;
  454. }
  455. /**
  456. * Remove an already registered taxonomy from an object type.
  457. *
  458. * @since 3.7.0
  459. *
  460. * @param string $taxonomy Name of taxonomy object.
  461. * @param string $object_type Name of the object type.
  462. * @return bool True if successful, false if not.
  463. */
  464. function unregister_taxonomy_for_object_type( $taxonomy, $object_type ) {
  465. global $wp_taxonomies;
  466. if ( ! isset( $wp_taxonomies[ $taxonomy ] ) )
  467. return false;
  468. if ( ! get_post_type_object( $object_type ) )
  469. return false;
  470. $key = array_search( $object_type, $wp_taxonomies[ $taxonomy ]->object_type, true );
  471. if ( false === $key )
  472. return false;
  473. unset( $wp_taxonomies[ $taxonomy ]->object_type[ $key ] );
  474. return true;
  475. }
  476. //
  477. // Term API
  478. //
  479. /**
  480. * Retrieve object_ids of valid taxonomy and term.
  481. *
  482. * The strings of $taxonomies must exist before this function will continue. On
  483. * failure of finding a valid taxonomy, it will return an WP_Error class, kind
  484. * of like Exceptions in PHP 5, except you can't catch them. Even so, you can
  485. * still test for the WP_Error class and get the error message.
  486. *
  487. * The $terms aren't checked the same as $taxonomies, but still need to exist
  488. * for $object_ids to be returned.
  489. *
  490. * It is possible to change the order that object_ids is returned by either
  491. * using PHP sort family functions or using the database by using $args with
  492. * either ASC or DESC array. The value should be in the key named 'order'.
  493. *
  494. * @package WordPress
  495. * @subpackage Taxonomy
  496. * @since 2.3.0
  497. *
  498. * @uses $wpdb
  499. * @uses wp_parse_args() Creates an array from string $args.
  500. *
  501. * @param int|array $term_ids Term id or array of term ids of terms that will be used
  502. * @param string|array $taxonomies String of taxonomy name or Array of string values of taxonomy names
  503. * @param array|string $args Change the order of the object_ids, either ASC or DESC
  504. * @return WP_Error|array If the taxonomy does not exist, then WP_Error will be returned. On success
  505. * the array can be empty meaning that there are no $object_ids found or it will return the $object_ids found.
  506. */
  507. function get_objects_in_term( $term_ids, $taxonomies, $args = array() ) {
  508. global $wpdb;
  509. if ( ! is_array( $term_ids ) )
  510. $term_ids = array( $term_ids );
  511. if ( ! is_array( $taxonomies ) )
  512. $taxonomies = array( $taxonomies );
  513. foreach ( (array) $taxonomies as $taxonomy ) {
  514. if ( ! taxonomy_exists( $taxonomy ) )
  515. return new WP_Error( 'invalid_taxonomy', __( 'Invalid taxonomy' ) );
  516. }
  517. $defaults = array( 'order' => 'ASC' );
  518. $args = wp_parse_args( $args, $defaults );
  519. extract( $args, EXTR_SKIP );
  520. $order = ( 'desc' == strtolower( $order ) ) ? 'DESC' : 'ASC';
  521. $term_ids = array_map('intval', $term_ids );
  522. $taxonomies = "'" . implode( "', '", $taxonomies ) . "'";
  523. $term_ids = "'" . implode( "', '", $term_ids ) . "'";
  524. $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");
  525. if ( ! $object_ids )
  526. return array();
  527. return $object_ids;
  528. }
  529. /**
  530. * Given a taxonomy query, generates SQL to be appended to a main query.
  531. *
  532. * @since 3.1.0
  533. *
  534. * @see WP_Tax_Query
  535. *
  536. * @param array $tax_query A compact tax query
  537. * @param string $primary_table
  538. * @param string $primary_id_column
  539. * @return array
  540. */
  541. function get_tax_sql( $tax_query, $primary_table, $primary_id_column ) {
  542. $tax_query_obj = new WP_Tax_Query( $tax_query );
  543. return $tax_query_obj->get_sql( $primary_table, $primary_id_column );
  544. }
  545. /**
  546. * Container class for a multiple taxonomy query.
  547. *
  548. * @since 3.1.0
  549. */
  550. class WP_Tax_Query {
  551. /**
  552. * List of taxonomy queries. A single taxonomy query is an associative array:
  553. * - 'taxonomy' string The taxonomy being queried
  554. * - 'terms' string|array The list of terms
  555. * - 'field' string (optional) Which term field is being used.
  556. * Possible values: 'term_id', 'slug' or 'name'
  557. * Default: 'term_id'
  558. * - 'operator' string (optional)
  559. * Possible values: 'AND', 'IN' or 'NOT IN'.
  560. * Default: 'IN'
  561. * - 'include_children' bool (optional) Whether to include child terms.
  562. * Default: true
  563. *
  564. * @since 3.1.0
  565. * @access public
  566. * @var array
  567. */
  568. public $queries = array();
  569. /**
  570. * The relation between the queries. Can be one of 'AND' or 'OR'.
  571. *
  572. * @since 3.1.0
  573. * @access public
  574. * @var string
  575. */
  576. public $relation;
  577. /**
  578. * Standard response when the query should not return any rows.
  579. *
  580. * @since 3.2.0
  581. * @access private
  582. * @var string
  583. */
  584. private static $no_results = array( 'join' => '', 'where' => ' AND 0 = 1' );
  585. /**
  586. * Constructor.
  587. *
  588. * Parses a compact tax query and sets defaults.
  589. *
  590. * @since 3.1.0
  591. * @access public
  592. *
  593. * @param array $tax_query A compact tax query:
  594. * array(
  595. * 'relation' => 'OR',
  596. * array(
  597. * 'taxonomy' => 'tax1',
  598. * 'terms' => array( 'term1', 'term2' ),
  599. * 'field' => 'slug',
  600. * ),
  601. * array(
  602. * 'taxonomy' => 'tax2',
  603. * 'terms' => array( 'term-a', 'term-b' ),
  604. * 'field' => 'slug',
  605. * ),
  606. * )
  607. */
  608. public function __construct( $tax_query ) {
  609. if ( isset( $tax_query['relation'] ) && strtoupper( $tax_query['relation'] ) == 'OR' ) {
  610. $this->relation = 'OR';
  611. } else {
  612. $this->relation = 'AND';
  613. }
  614. $defaults = array(
  615. 'taxonomy' => '',
  616. 'terms' => array(),
  617. 'include_children' => true,
  618. 'field' => 'term_id',
  619. 'operator' => 'IN',
  620. );
  621. foreach ( $tax_query as $query ) {
  622. if ( ! is_array( $query ) )
  623. continue;
  624. $query = array_merge( $defaults, $query );
  625. $query['terms'] = (array) $query['terms'];
  626. $this->queries[] = $query;
  627. }
  628. }
  629. /**
  630. * Generates SQL clauses to be appended to a main query.
  631. *
  632. * @since 3.1.0
  633. * @access public
  634. *
  635. * @param string $primary_table
  636. * @param string $primary_id_column
  637. * @return array
  638. */
  639. public function get_sql( $primary_table, $primary_id_column ) {
  640. global $wpdb;
  641. $join = '';
  642. $where = array();
  643. $i = 0;
  644. $count = count( $this->queries );
  645. foreach ( $this->queries as $index => $query ) {
  646. $this->clean_query( $query );
  647. if ( is_wp_error( $query ) )
  648. return self::$no_results;
  649. extract( $query );
  650. if ( 'IN' == $operator ) {
  651. if ( empty( $terms ) ) {
  652. if ( 'OR' == $this->relation ) {
  653. if ( ( $index + 1 === $count ) && empty( $where ) )
  654. return self::$no_results;
  655. continue;
  656. } else {
  657. return self::$no_results;
  658. }
  659. }
  660. $terms = implode( ',', $terms );
  661. $alias = $i ? 'tt' . $i : $wpdb->term_relationships;
  662. $join .= " INNER JOIN $wpdb->term_relationships";
  663. $join .= $i ? " AS $alias" : '';
  664. $join .= " ON ($primary_table.$primary_id_column = $alias.object_id)";
  665. $where[] = "$alias.term_taxonomy_id $operator ($terms)";
  666. } elseif ( 'NOT IN' == $operator ) {
  667. if ( empty( $terms ) )
  668. continue;
  669. $terms = implode( ',', $terms );
  670. $where[] = "$primary_table.$primary_id_column NOT IN (
  671. SELECT object_id
  672. FROM $wpdb->term_relationships
  673. WHERE term_taxonomy_id IN ($terms)
  674. )";
  675. } elseif ( 'AND' == $operator ) {
  676. if ( empty( $terms ) )
  677. continue;
  678. $num_terms = count( $terms );
  679. $terms = implode( ',', $terms );
  680. $where[] = "(
  681. SELECT COUNT(1)
  682. FROM $wpdb->term_relationships
  683. WHERE term_taxonomy_id IN ($terms)
  684. AND object_id = $primary_table.$primary_id_column
  685. ) = $num_terms";
  686. }
  687. $i++;
  688. }
  689. if ( ! empty( $where ) )
  690. $where = ' AND ( ' . implode( " $this->relation ", $where ) . ' )';
  691. else
  692. $where = '';
  693. return compact( 'join', 'where' );
  694. }
  695. /**
  696. * Validates a single query.
  697. *
  698. * @since 3.2.0
  699. * @access private
  700. *
  701. * @param array &$query The single query
  702. */
  703. private function clean_query( &$query ) {
  704. if ( ! taxonomy_exists( $query['taxonomy'] ) ) {
  705. $query = new WP_Error( 'Invalid taxonomy' );
  706. return;
  707. }
  708. $query['terms'] = array_unique( (array) $query['terms'] );
  709. if ( is_taxonomy_hierarchical( $query['taxonomy'] ) && $query['include_children'] ) {
  710. $this->transform_query( $query, 'term_id' );
  711. if ( is_wp_error( $query ) )
  712. return;
  713. $children = array();
  714. foreach ( $query['terms'] as $term ) {
  715. $children = array_merge( $children, get_term_children( $term, $query['taxonomy'] ) );
  716. $children[] = $term;
  717. }
  718. $query['terms'] = $children;
  719. }
  720. $this->transform_query( $query, 'term_taxonomy_id' );
  721. }
  722. /**
  723. * Transforms a single query, from one field to another.
  724. *
  725. * @since 3.2.0
  726. *
  727. * @param array &$query The single query
  728. * @param string $resulting_field The resulting field
  729. */
  730. public function transform_query( &$query, $resulting_field ) {
  731. global $wpdb;
  732. if ( empty( $query['terms'] ) )
  733. return;
  734. if ( $query['field'] == $resulting_field )
  735. return;
  736. $resulting_field = sanitize_key( $resulting_field );
  737. switch ( $query['field'] ) {
  738. case 'slug':
  739. case 'name':
  740. $terms = "'" . implode( "','", array_map( 'sanitize_title_for_query', $query['terms'] ) ) . "'";
  741. $terms = $wpdb->get_col( "
  742. SELECT $wpdb->term_taxonomy.$resulting_field
  743. FROM $wpdb->term_taxonomy
  744. INNER JOIN $wpdb->terms USING (term_id)
  745. WHERE taxonomy = '{$query['taxonomy']}'
  746. AND $wpdb->terms.{$query['field']} IN ($terms)
  747. " );
  748. break;
  749. case 'term_taxonomy_id':
  750. $terms = implode( ',', array_map( 'intval', $query['terms'] ) );
  751. $terms = $wpdb->get_col( "
  752. SELECT $resulting_field
  753. FROM $wpdb->term_taxonomy
  754. WHERE term_taxonomy_id IN ($terms)
  755. " );
  756. break;
  757. default:
  758. $terms = implode( ',', array_map( 'intval', $query['terms'] ) );
  759. $terms = $wpdb->get_col( "
  760. SELECT $resulting_field
  761. FROM $wpdb->term_taxonomy
  762. WHERE taxonomy = '{$query['taxonomy']}'
  763. AND term_id IN ($terms)
  764. " );
  765. }
  766. if ( 'AND' == $query['operator'] && count( $terms ) < count( $query['terms'] ) ) {
  767. $query = new WP_Error( 'Inexistent terms' );
  768. return;
  769. }
  770. $query['terms'] = $terms;
  771. $query['field'] = $resulting_field;
  772. }
  773. }
  774. /**
  775. * Get all Term data from database by Term ID.
  776. *
  777. * The usage of the get_term function is to apply filters to a term object. It
  778. * is possible to get a term object from the database before applying the
  779. * filters.
  780. *
  781. * $term ID must be part of $taxonomy, to get from the database. Failure, might
  782. * be able to be captured by the hooks. Failure would be the same value as $wpdb
  783. * returns for the get_row method.
  784. *
  785. * There are two hooks, one is specifically for each term, named 'get_term', and
  786. * the second is for the taxonomy name, 'term_$taxonomy'. Both hooks gets the
  787. * term object, and the taxonomy name as parameters. Both hooks are expected to
  788. * return a Term object.
  789. *
  790. * 'get_term' hook - Takes two parameters the term Object and the taxonomy name.
  791. * Must return term object. Used in get_term() as a catch-all filter for every
  792. * $term.
  793. *
  794. * 'get_$taxonomy' hook - Takes two parameters the term Object and the taxonomy
  795. * name. Must return term object. $taxonomy will be the taxonomy name, so for
  796. * example, if 'category', it would be 'get_category' as the filter name. Useful
  797. * for custom taxonomies or plugging into default taxonomies.
  798. *
  799. * @package WordPress
  800. * @subpackage Taxonomy
  801. * @since 2.3.0
  802. *
  803. * @uses $wpdb
  804. * @uses sanitize_term() Cleanses the term based on $filter context before returning.
  805. * @see sanitize_term_field() The $context param lists the available values for get_term_by() $filter param.
  806. *
  807. * @param int|object $term If integer, will get from database. If object will apply filters and return $term.
  808. * @param string $taxonomy Taxonomy name that $term is part of.
  809. * @param string $output Constant OBJECT, ARRAY_A, or ARRAY_N
  810. * @param string $filter Optional, default is raw or no WordPress defined filter will applied.
  811. * @return mixed|null|WP_Error Term Row from database. Will return null if $term is empty. If taxonomy does not
  812. * exist then WP_Error will be returned.
  813. */
  814. function get_term($term, $taxonomy, $output = OBJECT, $filter = 'raw') {
  815. global $wpdb;
  816. $null = null;
  817. if ( empty($term) ) {
  818. $error = new WP_Error('invalid_term', __('Empty Term'));
  819. return $error;
  820. }
  821. if ( ! taxonomy_exists($taxonomy) ) {
  822. $error = new WP_Error('invalid_taxonomy', __('Invalid taxonomy'));
  823. return $error;
  824. }
  825. if ( is_object($term) && empty($term->filter) ) {
  826. wp_cache_add($term->term_id, $term, $taxonomy);
  827. $_term = $term;
  828. } else {
  829. if ( is_object($term) )
  830. $term = $term->term_id;
  831. if ( !$term = (int) $term )
  832. return $null;
  833. if ( ! $_term = wp_cache_get($term, $taxonomy) ) {
  834. $_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) );
  835. if ( ! $_term )
  836. return $null;
  837. wp_cache_add($term, $_term, $taxonomy);
  838. }
  839. }
  840. $_term = apply_filters('get_term', $_term, $taxonomy);
  841. $_term = apply_filters("get_$taxonomy", $_term, $taxonomy);
  842. $_term = sanitize_term($_term, $taxonomy, $filter);
  843. if ( $output == OBJECT ) {
  844. return $_term;
  845. } elseif ( $output == ARRAY_A ) {
  846. $__term = get_object_vars($_term);
  847. return $__term;
  848. } elseif ( $output == ARRAY_N ) {
  849. $__term = array_values(get_object_vars($_term));
  850. return $__term;
  851. } else {
  852. return $_term;
  853. }
  854. }
  855. /**
  856. * Get all Term data from database by Term field and data.
  857. *
  858. * Warning: $value is not escaped for 'name' $field. You must do it yourself, if
  859. * required.
  860. *
  861. * The default $field is 'id', therefore it is possible to also use null for
  862. * field, but not recommended that you do so.
  863. *
  864. * If $value does not exist, the return value will be false. If $taxonomy exists
  865. * and $field and $value combinations exist, the Term will be returned.
  866. *
  867. * @package WordPress
  868. * @subpackage Taxonomy
  869. * @since 2.3.0
  870. *
  871. * @uses $wpdb
  872. * @uses sanitize_term() Cleanses the term based on $filter context before returning.
  873. * @see sanitize_term_field() The $context param lists the available values for get_term_by() $filter param.
  874. *
  875. * @param string $field Either 'slug', 'name', 'id' (term_id), or 'term_taxonomy_id'
  876. * @param string|int $value Search for this term value
  877. * @param string $taxonomy Taxonomy Name
  878. * @param string $output Constant OBJECT, ARRAY_A, or ARRAY_N
  879. * @param string $filter Optional, default is raw or no WordPress defined filter will applied.
  880. * @return mixed Term Row from database. Will return false if $taxonomy does not exist or $term was not found.
  881. */
  882. function get_term_by($field, $value, $taxonomy, $output = OBJECT, $filter = 'raw') {
  883. global $wpdb;
  884. if ( ! taxonomy_exists($taxonomy) )
  885. return false;
  886. if ( 'slug' == $field ) {
  887. $field = 't.slug';
  888. $value = sanitize_title($value);
  889. if ( empty($value) )
  890. return false;
  891. } else if ( 'name' == $field ) {
  892. // Assume already escaped
  893. $value = wp_unslash($value);
  894. $field = 't.name';
  895. } else if ( 'term_taxonomy_id' == $field ) {
  896. $value = (int) $value;
  897. $field = 'tt.term_taxonomy_id';
  898. } else {
  899. $term = get_term( (int) $value, $taxonomy, $output, $filter);
  900. if ( is_wp_error( $term ) )
  901. $term = false;
  902. return $term;
  903. }
  904. $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) );
  905. if ( !$term )
  906. return false;
  907. wp_cache_add($term->term_id, $term, $taxonomy);
  908. $term = apply_filters('get_term', $term, $taxonomy);
  909. $term = apply_filters("get_$taxonomy", $term, $taxonomy);
  910. $term = sanitize_term($term, $taxonomy, $filter);
  911. if ( $output == OBJECT ) {
  912. return $term;
  913. } elseif ( $output == ARRAY_A ) {
  914. return get_object_vars($term);
  915. } elseif ( $output == ARRAY_N ) {
  916. return array_values(get_object_vars($term));
  917. } else {
  918. return $term;
  919. }
  920. }
  921. /**
  922. * Merge all term children into a single array of their IDs.
  923. *
  924. * This recursive function will merge all of the children of $term into the same
  925. * array of term IDs. Only useful for taxonomies which are hierarchical.
  926. *
  927. * Will return an empty array if $term does not exist in $taxonomy.
  928. *
  929. * @package WordPress
  930. * @subpackage Taxonomy
  931. * @since 2.3.0
  932. *
  933. * @uses $wpdb
  934. * @uses _get_term_hierarchy()
  935. * @uses get_term_children() Used to get the children of both $taxonomy and the parent $term
  936. *
  937. * @param string $term_id ID of Term to get children
  938. * @param string $taxonomy Taxonomy Name
  939. * @return array|WP_Error List of Term Objects. WP_Error returned if $taxonomy does not exist
  940. */
  941. function get_term_children( $term_id, $taxonomy ) {
  942. if ( ! taxonomy_exists($taxonomy) )
  943. return new WP_Error('invalid_taxonomy', __('Invalid taxonomy'));
  944. $term_id = intval( $term_id );
  945. $terms = _get_term_hierarchy($taxonomy);
  946. if ( ! isset($terms[$term_id]) )
  947. return array();
  948. $children = $terms[$term_id];
  949. foreach ( (array) $terms[$term_id] as $child ) {
  950. if ( isset($terms[$child]) )
  951. $children = array_merge($children, get_term_children($child, $taxonomy));
  952. }
  953. return $children;
  954. }
  955. /**
  956. * Get sanitized Term field.
  957. *
  958. * Does checks for $term, based on the $taxonomy. The function is for contextual
  959. * reasons and for simplicity of usage. See sanitize_term_field() for more
  960. * information.
  961. *
  962. * @package WordPress
  963. * @subpackage Taxonomy
  964. * @since 2.3.0
  965. *
  966. * @uses sanitize_term_field() Passes the return value in sanitize_term_field on success.
  967. *
  968. * @param string $field Term field to fetch
  969. * @param int $term Term ID
  970. * @param string $taxonomy Taxonomy Name
  971. * @param string $context Optional, default is display. Look at sanitize_term_field() for available options.
  972. * @return mixed Will return an empty string if $term is not an object or if $field is not set in $term.
  973. */
  974. function get_term_field( $field, $term, $taxonomy, $context = 'display' ) {
  975. $term = (int) $term;
  976. $term = get_term( $term, $taxonomy );
  977. if ( is_wp_error($term) )
  978. return $term;
  979. if ( !is_object($term) )
  980. return '';
  981. if ( !isset($term->$field) )
  982. return '';
  983. return sanitize_term_field($field, $term->$field, $term->term_id, $taxonomy, $context);
  984. }
  985. /**
  986. * Sanitizes Term for editing.
  987. *
  988. * Return value is sanitize_term() and usage is for sanitizing the term for
  989. * editing. Function is for contextual and simplicity.
  990. *
  991. * @package WordPress
  992. * @subpackage Taxonomy
  993. * @since 2.3.0
  994. *
  995. * @uses sanitize_term() Passes the return value on success
  996. *
  997. * @param int|object $id Term ID or Object
  998. * @param string $taxonomy Taxonomy Name
  999. * @return mixed|null|WP_Error Will return empty string if $term is not an object.
  1000. */
  1001. function get_term_to_edit( $id, $taxonomy ) {
  1002. $term = get_term( $id, $taxonomy );
  1003. if ( is_wp_error($term) )
  1004. return $term;
  1005. if ( !is_object($term) )
  1006. return '';
  1007. return sanitize_term($term, $taxonomy, 'edit');
  1008. }
  1009. /**
  1010. * Retrieve the terms in a given taxonomy or list of taxonomies.
  1011. *
  1012. * You can fully inject any customizations to the query before it is sent, as
  1013. * well as control the output with a filter.
  1014. *
  1015. * The 'get_terms' filter will be called when the cache has the term and will
  1016. * pass the found term along with the array of $taxonomies and array of $args.
  1017. * This filter is also called before the array of terms is passed and will pass
  1018. * the array of terms, along with the $taxonomies and $args.
  1019. *
  1020. * The 'list_terms_exclusions' filter passes the compiled exclusions along with
  1021. * the $args.
  1022. *
  1023. * The 'get_terms_orderby' filter passes the ORDER BY clause for the query
  1024. * along with the $args array.
  1025. *
  1026. * The 'get_terms_fields' filter passes the fields for the SELECT query
  1027. * along with the $args array.
  1028. *
  1029. * The list of arguments that $args can contain, which will overwrite the defaults:
  1030. *
  1031. * orderby - Default is 'name'. Can be name, count, term_group, slug or nothing
  1032. * (will use term_id), Passing a custom value other than these will cause it to
  1033. * order based on the custom value.
  1034. *
  1035. * order - Default is ASC. Can use DESC.
  1036. *
  1037. * hide_empty - Default is true. Will not return empty terms, which means
  1038. * terms whose count is 0 according to the given taxonomy.
  1039. *
  1040. * exclude - Default is an empty array. An array, comma- or space-delimited string
  1041. * of term ids to exclude from the return array. If 'include' is non-empty,
  1042. * 'exclude' is ignored.
  1043. *
  1044. * exclude_tree - Default is an empty array. An array, comma- or space-delimited
  1045. * string of term ids to exclude from the return array, along with all of their
  1046. * descendant terms according to the primary taxonomy. If 'include' is non-empty,
  1047. * 'exclude_tree' is ignored.
  1048. *
  1049. * include - Default is an empty array. An array, comma- or space-delimited string
  1050. * of term ids to include in the return array.
  1051. *
  1052. * number - The maximum number of terms to return. Default is to return them all.
  1053. *
  1054. * offset - The number by which to offset the terms query.
  1055. *
  1056. * fields - Default is 'all', which returns an array of term objects.
  1057. * If 'fields' is 'ids' or 'names', returns an array of
  1058. * integers or strings, respectively.
  1059. *
  1060. * slug - Returns terms whose "slug" matches this value. Default is empty string.
  1061. *
  1062. * hierarchical - Whether to include terms that have non-empty descendants
  1063. * (even if 'hide_empty' is set to true).
  1064. *
  1065. * search - Returned terms' names will contain the value of 'search',
  1066. * case-insensitive. Default is an empty string.
  1067. *
  1068. * name__like - Returned terms' names will contain the value of 'name__like',
  1069. * case-insensitive. Default is empty string.
  1070. *
  1071. * description__like - Returned terms' descriptions will contain the value of
  1072. * 'description__like', case-insensitive. Default is empty string.
  1073. *
  1074. * The argument 'pad_counts', if set to true will include the quantity of a term's
  1075. * children in the quantity of each term's "count" object variable.
  1076. *
  1077. * The 'get' argument, if set to 'all' instead of its default empty string,
  1078. * returns terms regardless of ancestry or whether the terms are empty.
  1079. *
  1080. * The 'child_of' argument, when used, should be set to the integer of a term ID. Its default
  1081. * is 0. If set to a non-zero value, all returned terms will be descendants
  1082. * of that term according to the given taxonomy. Hence 'child_of' is set to 0
  1083. * if more than one taxonomy is passed in $taxonomies, because multiple taxonomies
  1084. * make term ancestry ambiguous.
  1085. *
  1086. * The 'parent' argument, when used, should be set to the integer of a term ID. Its default is
  1087. * the empty string '', which has a different meaning from the integer 0.
  1088. * If set to an integer value, all returned terms will have as an immediate
  1089. * ancestor the term whose ID is specified by that integer according to the given taxonomy.
  1090. * The 'parent' argument is different from 'child_of' in that a term X is considered a 'parent'
  1091. * of term Y only if term X is the father of term Y, not its grandfather or great-grandfather, etc.
  1092. *
  1093. * The 'cache_domain' argument enables a unique cache key to be produced when this query is stored
  1094. * in object cache. For instance, if you are using one of this function's filters to modify the
  1095. * query (such as 'terms_clauses'), setting 'cache_domain' to a unique value will not overwrite
  1096. * the cache for similar queries. Default value is 'core'.
  1097. *
  1098. * @package WordPress
  1099. * @subpackage Taxonomy
  1100. * @since 2.3.0
  1101. *
  1102. * @uses $wpdb
  1103. * @uses wp_parse_args() Merges the defaults with those defined by $args and allows for strings.
  1104. *
  1105. * @param string|array $taxonomies Taxonomy name or list of Taxonomy names
  1106. * @param string|array $args The values of what to search for when returning terms
  1107. * @return array|WP_Error List of Term Objects and their children. Will return WP_Error, if any of $taxonomies do not exist.
  1108. */
  1109. function get_terms($taxonomies, $args = '') {
  1110. global $wpdb;
  1111. $empty_array = array();
  1112. $single_taxonomy = ! is_array( $taxonomies ) || 1 === count( $taxonomies );
  1113. if ( ! is_array( $taxonomies ) )
  1114. $taxonomies = array( $taxonomies );
  1115. foreach ( $taxonomies as $taxonomy ) {
  1116. if ( ! taxonomy_exists($taxonomy) ) {
  1117. $error = new WP_Error('invalid_taxonomy', __('Invalid taxonomy'));
  1118. return $error;
  1119. }
  1120. }
  1121. $defaults = array('orderby' => 'name', 'order' => 'ASC',
  1122. 'hide_empty' => true, 'exclude' => array(), 'exclude_tree' => array(), 'include' => array(),
  1123. 'number' => '', 'fields' => 'all', 'slug' => '', 'parent' => '',
  1124. 'hierarchical' => true, 'child_of' => 0, 'get' => '', 'name__like' => '', 'description__like' => '',
  1125. 'pad_counts' => false, 'offset' => '', 'search' => '', 'cache_domain' => 'core' );
  1126. $args = wp_parse_args( $args, $defaults );
  1127. $args['number'] = absint( $args['number'] );
  1128. $args['offset'] = absint( $args['offset'] );
  1129. if ( !$single_taxonomy || ! is_taxonomy_hierarchical( reset( $taxonomies ) ) ||
  1130. '' !== $args['parent'] ) {
  1131. $args['child_of'] = 0;
  1132. $args['hierarchical'] = false;
  1133. $args['pad_counts'] = false;
  1134. }
  1135. if ( 'all' == $args['get'] ) {
  1136. $args['child_of'] = 0;
  1137. $args['hide_empty'] = 0;
  1138. $args['hierarchical'] = false;
  1139. $args['pad_counts'] = false;
  1140. }
  1141. $args = apply_filters( 'get_terms_args', $args, $taxonomies );
  1142. extract($args, EXTR_SKIP);
  1143. if ( $child_of ) {
  1144. $hierarchy = _get_term_hierarchy( reset( $taxonomies ) );
  1145. if ( ! isset( $hierarchy[ $child_of ] ) )
  1146. return $empty_array;
  1147. }
  1148. if ( $parent ) {
  1149. $hierarchy = _get_term_hierarchy( reset( $taxonomies ) );
  1150. if ( ! isset( $hierarchy[ $parent ] ) )
  1151. return $empty_array;
  1152. }
  1153. // $args can be whatever, only use the args defined in defaults to compute the key
  1154. $filter_key = ( has_filter('list_terms_exclusions') ) ? serialize($GLOBALS['wp_filter']['list_terms_exclusions']) : '';
  1155. $key = md5( serialize( compact(array_keys($defaults)) ) . serialize( $taxonomies ) . $filter_key );
  1156. $last_changed = wp_cache_get( 'last_changed', 'terms' );
  1157. if ( ! $last_changed ) {
  1158. $last_changed = microtime();
  1159. wp_cache_set( 'last_changed', $last_changed, 'terms' );
  1160. }
  1161. $cache_key = "get_terms:$key:$last_changed";
  1162. $cache = wp_cache_get( $cache_key, 'terms' );
  1163. if ( false !== $cache ) {
  1164. $cache = apply_filters('get_terms', $cache, $taxonomies, $args);
  1165. return $cache;
  1166. }
  1167. $_orderby = strtolower($orderby);
  1168. if ( 'count' == $_orderby )
  1169. $orderby = 'tt.count';
  1170. else if ( 'name' == $_orderby )
  1171. $orderby = 't.name';
  1172. else if ( 'slug' == $_orderby )
  1173. $orderby = 't.slug';
  1174. else if ( 'term_group' == $_orderby )
  1175. $orderby = 't.term_group';
  1176. else if ( 'none' == $_orderby )
  1177. $orderby = '';
  1178. elseif ( empty($_orderby) || 'id' == $_orderby )
  1179. $orderby = 't.term_id';
  1180. else
  1181. $orderby = 't.name';
  1182. $orderby = apply_filters( 'get_terms_orderby', $orderby, $args, $taxonomies );
  1183. if ( !empty($orderby) )
  1184. $orderby = "ORDER BY $orderby";
  1185. else
  1186. $order = '';
  1187. $order = strtoupper( $order );
  1188. if ( '' !== $order && !in_array( $order, array( 'ASC', 'DESC' ) ) )
  1189. $order = 'ASC';
  1190. $where = "tt.taxonomy IN ('" . implode("', '", $taxonomies) . "')";
  1191. $inclusions = '';
  1192. if ( ! empty( $include ) ) {
  1193. $exclude = '';
  1194. $exclude_tree = '';
  1195. $inclusions = implode( ',', wp_parse_id_list( $include ) );
  1196. }
  1197. if ( ! empty( $inclusions ) ) {
  1198. $inclusions = ' AND t.term_id IN ( ' . $inclusions . ' )';
  1199. $where .= $inclusions;
  1200. }
  1201. $exclusions = '';
  1202. if ( ! empty( $exclude_tree ) ) {
  1203. $exclude_tree = wp_parse_id_list( $exclude_tree );
  1204. $excluded_children = $exclude_tree;
  1205. foreach ( $exclude_tree as $extrunk ) {
  1206. $excluded_children = array_merge(
  1207. $excluded_children,
  1208. (array) get_terms( $taxonomies[0], array( 'child_of' => intval( $extrunk ), 'fields' => 'ids', 'hide_empty' => 0 ) )
  1209. );
  1210. }
  1211. $exclusions = implode( ',', array_map( 'intval', $excluded_children ) );
  1212. }
  1213. if ( ! empty( $exclude ) ) {
  1214. $exterms = wp_parse_id_list( $exclude );
  1215. if ( empty( $exclusions ) )
  1216. $exclusions = implode( ',', $exterms );
  1217. else
  1218. $exclusions .= ', ' . implode( ',', $exterms );
  1219. }
  1220. if ( ! empty( $exclusions ) )
  1221. $exclusions = ' AND t.term_id NOT IN (' . $exclusions . ')';
  1222. $exclusions = apply_filters( 'list_terms_exclusions', $exclusions, $args, $taxonomies );
  1223. if ( ! empty( $exclusions ) )
  1224. $where .= $exclusions;
  1225. if ( !empty($slug) ) {
  1226. $slug = sanitize_title($slug);
  1227. $where .= " AND t.slug = '$slug'";
  1228. }
  1229. if ( !empty($name__like) ) {
  1230. $name__like = like_escape( $name__like );
  1231. $where .= $wpdb->prepare( " AND t.name LIKE %s", '%' . $name__like . '%' );
  1232. }
  1233. if ( ! empty( $description__like ) ) {
  1234. $description__like = like_escape( $description__like );
  1235. $where .= $wpdb->prepare( " AND tt.description LIKE %s", '%' . $description__like . '%' );
  1236. }
  1237. if ( '' !== $parent ) {
  1238. $parent = (int) $parent;
  1239. $where .= " AND tt.parent = '$parent'";
  1240. }
  1241. if ( 'count' == $fields )
  1242. $hierarchical = false;
  1243. if ( $hide_empty && !$hierarchical )
  1244. $where .= ' AND tt.count > 0';
  1245. // don't limit the query results when we have to descend the family tree
  1246. if ( $number && ! $hierarchical && ! $child_of && '' === $parent ) {
  1247. if ( $offset )
  1248. $limits = 'LIMIT ' . $offset . ',' . $number;
  1249. else
  1250. $limits = 'LIMIT ' . $number;
  1251. } else {
  1252. $limits = '';
  1253. }
  1254. if ( ! empty( $search ) ) {
  1255. $search = like_escape( $search );
  1256. $where .= $wpdb->prepare( ' AND ((t.name LIKE %s) OR (t.slug LIKE %s))', '%' . $search . '%', '%' . $search . '%' );
  1257. }
  1258. $selects = array();
  1259. switch ( $fields ) {
  1260. case 'all':
  1261. $selects = array( 't.*', 'tt.*' );
  1262. break;
  1263. case 'ids':
  1264. case 'id=>parent':
  1265. $selects = array( 't.term_id', 'tt.parent', 'tt.count' );
  1266. break;
  1267. case 'names':
  1268. $selects = array( 't.term_id', 'tt.parent', 'tt.count', 't.name' );
  1269. break;
  1270. case 'count':
  1271. $orderby = '';
  1272. $order = '';
  1273. $selects = array( 'COUNT(*)' );
  1274. break;
  1275. case 'id=>name':
  1276. $selects = array( 't.term_id', 't.name' );
  1277. break;
  1278. case 'id=>slug':
  1279. $selects = array( 't.term_id', 't.slug' );
  1280. break;
  1281. }
  1282. $_fields = $fields;
  1283. $fields = implode( ', ', apply_filters( 'get_terms_fields', $selects, $args, $taxonomies ) );
  1284. $join = "INNER JOIN $wpdb->term_taxonomy AS tt ON t.term_id = tt.term_id";
  1285. $pieces = array( 'fields', 'join', 'where', 'orderby', 'order', 'limits' );
  1286. $clauses = apply_filters( 'terms_clauses', compact( $pieces ), $taxonomies, $args );
  1287. foreach ( $pieces as $piece )
  1288. $$piece = isset( $clauses[ $piece ] ) ? $clauses[ $piece ] : '';
  1289. $query = "SELECT $fields FROM $wpdb->terms AS t $join WHERE $where $orderby $order $limits";
  1290. $fields = $_fields;
  1291. if ( 'count' == $fields ) {
  1292. $term_count = $wpdb->get_var($query);
  1293. return $term_count;
  1294. }
  1295. $terms = $wpdb->get_results($query);
  1296. if ( 'all' == $fields ) {
  1297. update_term_cache($terms);
  1298. }
  1299. if ( empty($terms) ) {
  1300. wp_cache_add( $cache_key, array(), 'terms', DAY_IN_SECONDS );
  1301. $terms = apply_filters('get_terms', array(), $taxonomies, $args);
  1302. return $terms;
  1303. }
  1304. if ( $child_of ) {
  1305. $children = _get_term_hierarchy( reset( $taxonomies ) );
  1306. if ( ! empty( $children ) )
  1307. $terms = _get_term_children( $child_of, $terms, reset( $taxonomies ) );
  1308. }
  1309. // Update term counts to include children.
  1310. if ( $pad_counts && 'all' == $fields )
  1311. _pad_term_counts( $terms, reset( $taxonomies ) );
  1312. // Make sure we show empty categories that have children.
  1313. if ( $hierarchical && $hide_empty && is_array( $terms ) ) {
  1314. foreach ( $terms as $k => $term ) {
  1315. if ( ! $term->count ) {
  1316. $children = _get_term_children( $term->term_id, $terms, reset( $taxonomies ) );
  1317. if ( is_array( $children ) )
  1318. foreach ( $children as $child )
  1319. if ( $child->count )
  1320. continue 2;
  1321. // It really is empty
  1322. unset($terms[$k]);
  1323. }
  1324. }
  1325. }
  1326. reset( $terms );
  1327. $_terms = array();
  1328. if ( 'id=>parent' == $fields ) {
  1329. while ( $term = array_shift( $terms ) )
  1330. $_terms[$term->term_id] = $term->parent;
  1331. } elseif ( 'ids' == $fields ) {
  1332. while ( $term = array_shift( $terms ) )
  1333. $_terms[] = $term->term_id;
  1334. } elseif ( 'names' == $fields ) {
  1335. while ( $term = array_shift( $terms ) )
  1336. $_terms[] = $term->name;
  1337. } elseif ( 'id=>name' == $fields ) {
  1338. while ( $term = array_shift( $terms ) )
  1339. $_terms[$term->term_id] = $term->name;
  1340. } elseif ( 'id=>slug' == $fields ) {
  1341. while ( $term = array_shift( $terms ) )
  1342. $_terms[$term->term_id] = $term->slug;
  1343. }
  1344. if ( ! empty( $_terms ) )
  1345. $terms = $_terms;
  1346. if ( $number && is_array( $terms ) && count( $terms ) > $number )
  1347. $terms = array_slice( $terms, $offset, $number );
  1348. wp_cache_add( $cache_key, $terms, 'terms', DAY_IN_SECONDS );
  1349. $terms = apply_filters( 'get_terms', $terms, $taxonomies, $args );
  1350. return $terms;
  1351. }
  1352. /**
  1353. * Check if Term exists.
  1354. *
  1355. * Formerly is_term(), introduced in 2.3.0.
  1356. *
  1357. * @package WordPress
  1358. * @subpackage Taxonomy
  1359. * @since 3.0.0
  1360. *
  1361. * @uses $wpdb
  1362. *
  1363. * @param int|string $term The term to check
  1364. * @param string $taxonomy The taxonomy name to use
  1365. * @param int $parent ID of parent term under which to confine the exists search.
  1366. * @return mixed Returns 0 if the term does not exist. Returns the term ID if no taxonomy is specified
  1367. * and the term ID exists. Returns an array of the term ID and the taxonomy if the pairing exists.
  1368. */
  1369. function term_exists($term, $taxonomy = '', $parent = 0) {
  1370. global $wpdb;
  1371. $select = "SELECT term_id FROM $wpdb->terms as t WHERE ";
  1372. $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 ";
  1373. if ( is_int($term) ) {
  1374. if ( 0 == $term )
  1375. return 0;
  1376. $where = 't.term_id = %d';
  1377. if ( !empty($taxonomy) )
  1378. return $wpdb->get_row( $wpdb->prepare( $tax_select . $where . " AND tt.taxonomy = %s", $term, $taxonomy ), ARRAY_A );
  1379. else
  1380. return $wpdb->get_var( $wpdb->prepare( $select . $where, $term ) );
  1381. }
  1382. $term = trim( wp_unslash( $term ) );
  1383. if ( '' === $slug = sanitize_title($term) )
  1384. return 0;
  1385. $where = 't.slug = %s';
  1386. $else_where = 't.name = %s';
  1387. $where_fields = array($slug);
  1388. $else_where_fields = array($term);
  1389. if ( !empty($taxonomy) ) {
  1390. $parent = (int) $parent;
  1391. if ( $parent > 0 ) {
  1392. $where_fields[] = $parent;
  1393. $else_where_fields[] = $parent;
  1394. $where .= ' AND tt.parent = %d';
  1395. $else_where .= ' AND tt.parent = %d';
  1396. }
  1397. $where_fields[] = $taxonomy;
  1398. $else_where_fields[] = $taxonomy;
  1399. 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) )
  1400. return $result;
  1401. 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);
  1402. }
  1403. if ( $result = $wpdb->get_var( $wpdb->prepare("SELECT term_id FROM $wpdb->terms as t WHERE $where", $where_fields) ) )
  1404. return $result;
  1405. return $wpdb->get_var( $wpdb->prepare("SELECT term_id FROM $wpdb->terms as t WHERE $else_where", $else_where_fields) );
  1406. }
  1407. /**
  1408. * Check if a term is an ancestor of another term.
  1409. *
  1410. * You can use either an id or the term object for both parameters.
  1411. *
  1412. * @since 3.4.0
  1413. *
  1414. * @param int|object $term1 ID or object to check if this is the parent term.
  1415. * @param int|object $term2 The child term.
  1416. * @param string $taxonomy Taxonomy name that $term1 and $term2 belong to.
  1417. * @return bool Whether $term2 is child of $term1
  1418. */
  1419. function term_is_ancestor_of( $term1, $term2, $taxonomy ) {
  1420. if ( ! isset( $term1->term_id ) )
  1421. $term1 = get_term( $term1, $taxonomy );
  1422. if ( ! isset( $term2->parent ) )
  1423. $term2 = get_term( $term2, $taxonomy );
  1424. if ( empty( $term1->term_id ) || empty( $term2->parent ) )
  1425. return false;
  1426. if ( $term2->parent == $term1->term_id )
  1427. return true;
  1428. return term_is_ancestor_of( $term1, get_term( $term2->parent, $taxonomy ), $taxonomy );
  1429. }
  1430. /**
  1431. * Sanitize Term all fields.
  1432. *
  1433. * Relies on sanitize_term_field() to sanitize the term. The difference is that
  1434. * this function will sanitize <strong>all</strong> fields. The context is based
  1435. * on sanitize_term_field().
  1436. *
  1437. * The $term is expected to be either an array or an object.
  1438. *
  1439. * @package WordPress
  1440. * @subpackage Taxonomy
  1441. * @since 2.3.0
  1442. *
  1443. * @uses sanitize_term_field Used to sanitize all fields in a term
  1444. *
  1445. * @param array|object $term The term to check
  1446. * @param string $taxonomy The taxonomy name to use
  1447. * @param string $context Default is 'display'.
  1448. * @return array|object Term with all fields sanitized
  1449. */
  1450. function sanitize_term($term, $taxonomy, $context = 'display') {
  1451. if ( 'raw' == $context )
  1452. return $term;
  1453. $fields = array('term_id', 'name', 'description', 'slug', 'count', 'parent', 'term_group');
  1454. $do_object = false;
  1455. if ( is_object($term) )
  1456. $do_object = true;
  1457. $term_id = $do_object ? $term->term_id : (isset($term['term_id']) ? $term['term_id'] : 0);
  1458. foreach ( (array) $fields as $field ) {
  1459. if ( $do_object ) {
  1460. if ( isset($term->$field) )
  1461. $term->$field = sanitize_term_field($field, $term->$field, $term_id, $taxonomy, $context);
  1462. } else {
  1463. if ( isset($term[$field]) )
  1464. $term[$field] = sanitize_term_field($field, $term[$field], $term_id, $taxonomy, $context);
  1465. }
  1466. }
  1467. if ( $do_object )
  1468. $term->filter = $context;
  1469. else
  1470. $term['filter'] = $context;
  1471. return $term;
  1472. }
  1473. /**
  1474. * Cleanse the field value in the term based on the context.
  1475. *
  1476. * Passing a term field value through the function should be assumed to have
  1477. * cleansed the value for whatever context the term field is going to be used.
  1478. *
  1479. * If no context or an unsupported context is given, then default filters will
  1480. * be applied.
  1481. *
  1482. * There are enough filters for each context to support a custom filtering
  1483. * without creating your own filter function. Simply create a function that
  1484. * hooks into the filter you need.
  1485. *
  1486. * @package WordPress
  1487. * @subpackage Taxonomy
  1488. * @since 2.3.0
  1489. *
  1490. * @uses $wpdb
  1491. *
  1492. * @param string $field Term field to sanitize
  1493. * @param string $value Search for this term value
  1494. * @param int $term_id Term ID
  1495. * @param string $taxonomy Taxonomy Name
  1496. * @param string $context Either edit, db, display, attribute, or js.
  1497. * @return mixed sanitized field
  1498. */
  1499. function sanitize_term_field($field, $value, $term_id, $taxonomy, $context) {
  1500. if ( 'parent' == $field || 'term_id' == $field || 'count' == $field || 'term_group' == $field ) {
  1501. $value = (int) $value;
  1502. if ( $value < 0 )
  1503. $value = 0;
  1504. }
  1505. if ( 'raw' == $context )
  1506. return $value;
  1507. if ( 'edit' == $context ) {
  1508. $value = apply_filters("edit_term_{$field}", $value, $term_id, $taxonomy);
  1509. $value = apply_filters("edit_{$taxonomy}_{$field}", $value, $term_id);
  1510. if ( 'description' == $field )
  1511. $value = esc_html($value); // textarea_escaped
  1512. else
  1513. $value = esc_attr($value);
  1514. } else if ( 'db' == $context ) {
  1515. $value = apply_filters("pre_term_{$field}", $value, $taxonomy);
  1516. $value = apply_filters("pre_{$taxonomy}_{$field}", $value);
  1517. // Back compat filters
  1518. if ( 'slug' == $field )
  1519. $value = apply_filters('pre_category_nicename', $value);
  1520. } else if ( 'rss' == $context ) {
  1521. $value = apply_filters("term_{$field}_rss", $value, $taxonomy);
  1522. $value = apply_filters("{$taxonomy}_{$field}_rss", $value);
  1523. } else {
  1524. // Use display filters by default.
  1525. $value = apply_filters("term_{$field}", $value, $term_id, $taxonomy, $context);
  1526. $value = apply_filters("{$taxonomy}_{$field}", $value, $term_id, $context);
  1527. }
  1528. if ( 'attribute' == $context )
  1529. $value = esc_attr($value);
  1530. else if ( 'js' == $context )
  1531. $value = esc_js($value);
  1532. return $value;
  1533. }
  1534. /**
  1535. * Count how many terms are in Taxonomy.
  1536. *
  1537. * Default $args is 'hide_empty' which can be 'hide_empty=true' or array('hide_empty' => true).
  1538. *
  1539. * @package WordPress
  1540. * @subpackage Taxonomy
  1541. * @since 2.3.0
  1542. *
  1543. * @uses get_terms()
  1544. * @uses wp_parse_args() Turns strings into arrays and merges defaults into an array.
  1545. *
  1546. * @param string $taxonomy Taxonomy name
  1547. * @param array|string $args Overwrite defaults. See get_terms()
  1548. * @return int|WP_Error How many terms are in $taxonomy. WP_Error if $taxonomy does not exist.
  1549. */
  1550. function wp_count_terms( $taxonomy, $args = array() ) {
  1551. $defaults = array('hide_empty' => false);
  1552. $args = wp_parse_args($args, $defaults);
  1553. // backwards compatibility
  1554. if ( isset($args['ignore_empty']) ) {
  1555. $args['hide_empty'] = $args['ignore_empty'];
  1556. unset($args['ignore_empty']);
  1557. }
  1558. $args['fields'] = 'count';
  1559. return get_terms($taxonomy, $args);
  1560. }
  1561. /**
  1562. * Will unlink the object from the taxonomy or taxonomies.
  1563. *
  1564. * Will remove all relationships between the object and any terms in
  1565. * a particular taxonomy or taxonomies. Does not remove the term or
  1566. * taxonomy itself.
  1567. *
  1568. * @package WordPress
  1569. * @subpackage Taxonomy
  1570. * @since 2.3.0
  1571. * @uses wp_remove_object_terms()
  1572. *
  1573. * @param int $object_id The term Object Id that refers to the term
  1574. * @param string|array $taxonomies List of Taxonomy Names or single Taxonomy name.
  1575. */
  1576. function wp_delete_object_term_relationships( $object_id, $taxonomies ) {
  1577. $object_id = (int) $object_id;
  1578. if ( !is_array($taxonomies) )
  1579. $taxonomies = array($taxonomies);
  1580. foreach ( (array) $taxonomies as $taxonomy ) {
  1581. $term_ids = wp_get_object_terms( $object_id, $taxonomy, array( 'fields' => 'ids' ) );
  1582. $term_ids = array_map( 'intval', $term_ids );
  1583. wp_remove_object_terms( $object_id, $term_ids, $taxonomy );
  1584. }
  1585. }
  1586. /**
  1587. * Removes a term from the database.
  1588. *
  1589. * If the term is a parent of other terms, then the children will be updated to
  1590. * that term's parent.
  1591. *
  1592. * The $args 'default' will only override the terms found, if there is only one
  1593. * term found. Any other and the found terms are used.
  1594. *
  1595. * The $args 'force_default' will force the term supplied as default to be
  1596. * assigned even if the object was not going to be termless
  1597. * @package WordPress
  1598. * @subpackage Taxonomy
  1599. * @since 2.3.0
  1600. *
  1601. * @uses $wpdb
  1602. * @uses do_action() Calls both 'delete_term' and 'delete_$taxonomy' action
  1603. * hooks, passing term ID, term taxonomy ID, and deleted term object. 'delete_term'
  1604. * also gets taxonomy as the third parameter.
  1605. *
  1606. * @param int $term Term ID
  1607. * @param string $taxonomy Taxonomy Name
  1608. * @param array|string $args Optional. Change 'default' term id and override found term ids.
  1609. * @return bool|WP_Error Returns false if not term; true if completes delete action.
  1610. */
  1611. function wp_delete_term( $term, $taxonomy, $args = array() ) {
  1612. global $wpdb;
  1613. $term = (int) $term;
  1614. if ( ! $ids = term_exists($term, $taxonomy) )
  1615. return false;
  1616. if ( is_wp_error( $ids ) )
  1617. return $ids;
  1618. $tt_id = $ids['term_taxonomy_id'];
  1619. $defaults = array();
  1620. if ( 'category' == $taxonomy ) {
  1621. $defaults['default'] = get_option( 'default_category' );
  1622. if ( $defaults['default'] == $term )
  1623. return 0; // Don't delete the default category
  1624. }
  1625. $args = wp_parse_args($args, $defaults);
  1626. extract($args, EXTR_SKIP);
  1627. if ( isset( $default ) ) {
  1628. $default = (int) $default;
  1629. if ( ! term_exists($default, $taxonomy) )
  1630. unset($default);
  1631. }
  1632. // Update children to point to new parent
  1633. if ( is_taxonomy_hierarchical($taxonomy) ) {
  1634. $term_obj = get_term($term, $taxonomy);
  1635. if ( is_wp_error( $term_obj ) )
  1636. return $term_obj;
  1637. $parent = $term_obj->parent;
  1638. $edit_tt_ids = $wpdb->get_col( "SELECT `term_taxonomy_id` FROM $wpdb->term_taxonomy WHERE `parent` = " . (int)$term_obj->term_id );
  1639. do_action( 'edit_term_taxonomies', $edit_tt_ids );
  1640. $wpdb->update( $wpdb->term_taxonomy, compact( 'parent' ), array( 'parent' => $term_obj->term_id) + compact( 'taxonomy' ) );
  1641. do_action( 'edited_term_taxonomies', $edit_tt_ids );
  1642. }
  1643. $objects = $wpdb->get_col( $wpdb->prepare( "SELECT object_id FROM $wpdb->term_relationships WHERE term_taxonomy_id = %d", $tt_id ) );
  1644. foreach ( (array) $objects as $object ) {
  1645. $terms = wp_get_object_terms($object, $taxonomy, array('fields' => 'ids', 'orderby' => 'none'));
  1646. if ( 1 == count($terms) && isset($default) ) {
  1647. $terms = array($default);
  1648. } else {
  1649. $terms = array_diff($terms, array($term));
  1650. if (isset($default) && isset($force_default) && $force_default)
  1651. $terms = array_merge($terms, array($default));
  1652. }
  1653. $terms = array_map('intval', $terms);
  1654. wp_set_object_terms($object, $terms, $taxonomy);
  1655. }
  1656. // Clean the relationship caches for all object types using this term
  1657. $tax_object = get_taxonomy( $taxonomy );
  1658. foreach ( $tax_object->object_type as $object_type )
  1659. clean_object_term_cache( $objects, $object_type );
  1660. // Get the object before deletion so we can pass to actions below
  1661. $deleted_term = get_term( $term, $taxonomy );
  1662. do_action( 'delete_term_taxonomy', $tt_id );
  1663. $wpdb->delete( $wpdb->term_taxonomy, array( 'term_taxonomy_id' => $tt_id ) );
  1664. do_action( 'deleted_term_taxonomy', $tt_id );
  1665. // Delete the term if no taxonomies use it.
  1666. if ( !$wpdb->get_var( $wpdb->prepare( "SELECT COUNT(*) FROM $wpdb->term_taxonomy WHERE term_id = %d", $term) ) )
  1667. $wpdb->delete( $wpdb->terms, array( 'term_id' => $term ) );
  1668. clean_term_cache($term, $taxonomy);
  1669. do_action( 'delete_term', $term, $tt_id, $taxonomy, $deleted_term );
  1670. do_action( "delete_$taxonomy", $term, $tt_id, $deleted_term );
  1671. return true;
  1672. }
  1673. /**
  1674. * Deletes one existing category.
  1675. *
  1676. * @since 2.0.0
  1677. * @uses wp_delete_term()
  1678. *
  1679. * @param int $cat_ID
  1680. * @return mixed Returns true if completes delete action; false if term doesn't exist;
  1681. * Zero on attempted deletion of default Category; WP_Error object is also a possibility.
  1682. */
  1683. function wp_delete_category( $cat_ID ) {
  1684. return wp_delete_term( $cat_ID, 'category' );
  1685. }
  1686. /**
  1687. * Retrieves the terms associated with the given object(s), in the supplied taxonomies.
  1688. *
  1689. * The following information has to do the $args parameter and for what can be
  1690. * contained in the string or array of that parameter, if it exists.
  1691. *
  1692. * The first argument is called, 'orderby' and has the default value of 'name'.
  1693. * The other value that is supported is 'count'.
  1694. *
  1695. * The second argument is called, 'order' and has the default value of 'ASC'.
  1696. * The only other value that will be acceptable is 'DESC'.
  1697. *
  1698. * The final argument supported is called, 'fields' and has the default value of
  1699. * 'all'. There are multiple other options that can be used instead. Supported
  1700. * values are as follows: 'all', 'ids', 'names', and finally
  1701. * 'all_with_object_id'.
  1702. *
  1703. * The fields argument also decides what will be returned. If 'all' or
  1704. * 'all_with_object_id' is chosen or the default kept intact, then all matching
  1705. * terms objects will be returned. If either 'ids' or 'names' is used, then an
  1706. * array of all matching term ids or term names will be returned respectively.
  1707. *
  1708. * @package WordPress
  1709. * @subpackage Taxonomy
  1710. * @since 2.3.0
  1711. * @uses $wpdb
  1712. *
  1713. * @param int|array $object_ids The ID(s) of the object(s) to retrieve.
  1714. * @param string|array $taxonomies The taxonomies to retrieve terms from.
  1715. * @param array|string $args Change what is returned
  1716. * @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.
  1717. */
  1718. function wp_get_object_terms($object_ids, $taxonomies, $args = array()) {
  1719. global $wpdb;
  1720. if ( empty( $object_ids ) || empty( $taxonomies ) )
  1721. return array();
  1722. if ( !is_array($taxonomies) )
  1723. $taxonomies = array($taxonomies);
  1724. foreach ( (array) $taxonomies as $taxonomy ) {
  1725. if ( ! taxonomy_exists($taxonomy) )
  1726. return new WP_Error('invalid_taxonomy', __('Invalid taxonomy'));
  1727. }
  1728. if ( !is_array($object_ids) )
  1729. $object_ids = array($object_ids);
  1730. $object_ids = array_map('intval', $object_ids);
  1731. $defaults = array('orderby' => 'name', 'order' => 'ASC', 'fields' => 'all');
  1732. $args = wp_parse_args( $args, $defaults );
  1733. $terms = array();
  1734. if ( count($taxonomies) > 1 ) {
  1735. foreach ( $taxonomies as $index => $taxonomy ) {
  1736. $t = get_taxonomy($taxonomy);
  1737. if ( isset($t->args) && is_array($t->args) && $args != array_merge($args, $t->args) ) {
  1738. unset($taxonomies[$index]);
  1739. $terms = array_merge($terms, wp_get_object_terms($object_ids, $taxonomy, array_merge($args, $t->args)));
  1740. }
  1741. }
  1742. } else {
  1743. $t = get_taxonomy($taxonomies[0]);
  1744. if ( isset($t->args) && is_array($t->args) )
  1745. $args = array_merge($args, $t->args);
  1746. }
  1747. extract($args, EXTR_SKIP);
  1748. if ( 'count' == $orderby )
  1749. $orderby = 'tt.count';
  1750. else if ( 'name' == $orderby )
  1751. $orderby = 't.name';
  1752. else if ( 'slug' == $orderby )
  1753. $orderby = 't.slug';
  1754. else if ( 'term_group' == $orderby )
  1755. $orderby = 't.term_group';
  1756. else if ( 'term_order' == $orderby )
  1757. $orderby = 'tr.term_order';
  1758. else if ( 'none' == $orderby ) {
  1759. $orderby = '';
  1760. $order = '';
  1761. } else {
  1762. $orderby = 't.term_id';
  1763. }
  1764. // tt_ids queries can only be none or tr.term_taxonomy_id
  1765. if ( ('tt_ids' == $fields) && !empty($orderby) )
  1766. $orderby = 'tr.term_taxonomy_id';
  1767. if ( !empty($orderby) )
  1768. $orderby = "ORDER BY $orderby";
  1769. $order = strtoupper( $order );
  1770. if ( '' !== $order && ! in_array( $order, array( 'ASC', 'DESC' ) ) )
  1771. $order = 'ASC';
  1772. $taxonomies = "'" . implode("', '", $taxonomies) . "'";
  1773. $object_ids = implode(', ', $object_ids);
  1774. $select_this = '';
  1775. if ( 'all' == $fields )
  1776. $select_this = 't.*, tt.*';
  1777. else if ( 'ids' == $fields )
  1778. $select_this = 't.term_id';
  1779. else if ( 'names' == $fields )
  1780. $select_this = 't.name';
  1781. else if ( 'slugs' == $fields )
  1782. $select_this = 't.slug';
  1783. else if ( 'all_with_object_id' == $fields )
  1784. $select_this = 't.*, tt.*, tr.object_id';
  1785. $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";
  1786. if ( 'all' == $fields || 'all_with_object_id' == $fields ) {
  1787. $terms = array_merge($terms, $wpdb->get_results($query));
  1788. update_term_cache($terms);
  1789. } else if ( 'ids' == $fields || 'names' == $fields || 'slugs' == $fields ) {
  1790. $terms = array_merge($terms, $wpdb->get_col($query));
  1791. } else if ( 'tt_ids' == $fields ) {
  1792. $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");
  1793. }
  1794. if ( ! $terms )
  1795. $terms = array();
  1796. return apply_filters('wp_get_object_terms', $terms, $object_ids, $taxonomies, $args);
  1797. }
  1798. /**
  1799. * Add a new term to the database.
  1800. *
  1801. * A non-existent term is inserted in the following sequence:
  1802. * 1. The term is added to the term table, then related to the taxonomy.
  1803. * 2. If everything is correct, several actions are fired.
  1804. * 3. The 'term_id_filter' is evaluated.
  1805. * 4. The term cache is cleaned.
  1806. * 5. Several more actions are fired.
  1807. * 6. An array is returned containing the term_id and term_taxonomy_id.
  1808. *
  1809. * If the 'slug' argument is not empty, then it is checked to see if the term
  1810. * is invalid. If it is not a valid, existing term, it is added and the term_id
  1811. * is given.
  1812. *
  1813. * If the taxonomy is hierarchical, and the 'parent' argument is not empty,
  1814. * the term is inserted and the term_id will be given.
  1815. * Error handling:
  1816. * If $taxonomy does not exist or $term is empty,
  1817. * a WP_Error object will be returned.
  1818. *
  1819. * If the term already exists on the same hierarchical level,
  1820. * or the term slug and name are not unique, a WP_Error object will be returned.
  1821. *
  1822. * @global wpdb $wpdb The WordPress database object.
  1823. * @since 2.3.0
  1824. *
  1825. * @param string $term The term to add or update.
  1826. * @param string $taxonomy The taxonomy to which to add the term
  1827. * @param array|string $args {
  1828. * Arguments to change values of the inserted term.
  1829. *
  1830. * @type string 'alias_of' Slug of the term to make this term an alias of.
  1831. * Default empty string. Accepts a term slug.
  1832. * @type string 'description' The term description.
  1833. * Default empty string.
  1834. * @type int 'parent' The id of the parent term.
  1835. * Default 0.
  1836. * @type string 'slug' The term slug to use.
  1837. * Default empty string.
  1838. * }
  1839. * @return array|WP_Error An array containing the term_id and term_taxonomy_id, WP_Error otherwise.
  1840. */
  1841. function wp_insert_term( $term, $taxonomy, $args = array() ) {
  1842. global $wpdb;
  1843. if ( ! taxonomy_exists($taxonomy) )
  1844. return new WP_Error('invalid_taxonomy', __('Invalid taxonomy'));
  1845. $term = apply_filters( 'pre_insert_term', $term, $taxonomy );
  1846. if ( is_wp_error( $term ) )
  1847. return $term;
  1848. if ( is_int($term) && 0 == $term )
  1849. return new WP_Error('invalid_term_id', __('Invalid term ID'));
  1850. if ( '' == trim($term) )
  1851. return new WP_Error('empty_term_name', __('A name is required for this term'));
  1852. $defaults = array( 'alias_of' => '', 'description' => '', 'parent' => 0, 'slug' => '');
  1853. $args = wp_parse_args($args, $defaults);
  1854. $args['name'] = $term;
  1855. $args['taxonomy'] = $taxonomy;
  1856. $args = sanitize_term($args, $taxonomy, 'db');
  1857. extract($args, EXTR_SKIP);
  1858. // expected_slashed ($name)
  1859. $name = wp_unslash($name);
  1860. $description = wp_unslash($description);
  1861. if ( empty($slug) )
  1862. $slug = sanitize_title($name);
  1863. $term_group = 0;
  1864. if ( $alias_of ) {
  1865. $alias = $wpdb->get_row( $wpdb->prepare( "SELECT term_id, term_group FROM $wpdb->terms WHERE slug = %s", $alias_of) );
  1866. if ( $alias->term_group ) {
  1867. // The alias we want is already in a group, so let's use that one.
  1868. $term_group = $alias->term_group;
  1869. } else {
  1870. // The alias isn't in a group, so let's create a new one and firstly add the alias term to it.
  1871. $term_group = $wpdb->get_var("SELECT MAX(term_group) FROM $wpdb->terms") + 1;
  1872. do_action( 'edit_terms', $alias->term_id, $taxonomy );
  1873. $wpdb->update($wpdb->terms, compact('term_group'), array('term_id' => $alias->term_id) );
  1874. do_action( 'edited_terms', $alias->term_id, $taxonomy );
  1875. }
  1876. }
  1877. if ( $term_id = term_exists($slug) ) {
  1878. $existing_term = $wpdb->get_row( $wpdb->prepare( "SELECT name FROM $wpdb->terms WHERE term_id = %d", $term_id), ARRAY_A );
  1879. // We've got an existing term in the same taxonomy, which matches the name of the new term:
  1880. if ( is_taxonomy_hierarchical($taxonomy) && $existing_term['name'] == $name && $exists = term_exists( (int) $term_id, $taxonomy ) ) {
  1881. // Hierarchical, and it matches an existing term, Do not allow same "name" in the same level.
  1882. $siblings = get_terms($taxonomy, array('fields' => 'names', 'get' => 'all', 'parent' => (int)$parent) );
  1883. if ( in_array($name, $siblings) ) {
  1884. return new WP_Error('term_exists', __('A term with the name provided already exists with this parent.'), $exists['term_id']);
  1885. } else {
  1886. $slug = wp_unique_term_slug($slug, (object) $args);
  1887. if ( false === $wpdb->insert( $wpdb->terms, compact( 'name', 'slug', 'term_group' ) ) )
  1888. return new WP_Error('db_insert_error', __('Could not insert term into the database'), $wpdb->last_error);
  1889. $term_id = (int) $wpdb->insert_id;
  1890. }
  1891. } elseif ( $existing_term['name'] != $name ) {
  1892. // We've got an existing term, with a different name, Create the new term.
  1893. $slug = wp_unique_term_slug($slug, (object) $args);
  1894. if ( false === $wpdb->insert( $wpdb->terms, compact( 'name', 'slug', 'term_group' ) ) )
  1895. return new WP_Error('db_insert_error', __('Could not insert term into the database'), $wpdb->last_error);
  1896. $term_id = (int) $wpdb->insert_id;
  1897. } elseif ( $exists = term_exists( (int) $term_id, $taxonomy ) ) {
  1898. // Same name, same slug.
  1899. return new WP_Error('term_exists', __('A term with the name provided already exists.'), $exists['term_id']);
  1900. }
  1901. } else {
  1902. // This term does not exist at all in the database, Create it.
  1903. $slug = wp_unique_term_slug($slug, (object) $args);
  1904. if ( false === $wpdb->insert( $wpdb->terms, compact( 'name', 'slug', 'term_group' ) ) )
  1905. return new WP_Error('db_insert_error', __('Could not insert term into the database'), $wpdb->last_error);
  1906. $term_id = (int) $wpdb->insert_id;
  1907. }
  1908. // Seems unreachable, However, Is used in the case that a term name is provided, which sanitizes to an empty string.
  1909. if ( empty($slug) ) {
  1910. $slug = sanitize_title($slug, $term_id);
  1911. do_action( 'edit_terms', $term_id, $taxonomy );
  1912. $wpdb->update( $wpdb->terms, compact( 'slug' ), compact( 'term_id' ) );
  1913. do_action( 'edited_terms', $term_id, $taxonomy );
  1914. }
  1915. $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 ) );
  1916. if ( !empty($tt_id) )
  1917. return array('term_id' => $term_id, 'term_taxonomy_id' => $tt_id);
  1918. $wpdb->insert( $wpdb->term_taxonomy, compact( 'term_id', 'taxonomy', 'description', 'parent') + array( 'count' => 0 ) );
  1919. $tt_id = (int) $wpdb->insert_id;
  1920. do_action("create_term", $term_id, $tt_id, $taxonomy);
  1921. do_action("create_$taxonomy", $term_id, $tt_id);
  1922. $term_id = apply_filters('term_id_filter', $term_id, $tt_id);
  1923. clean_term_cache($term_id, $taxonomy);
  1924. do_action("created_term", $term_id, $tt_id, $taxonomy);
  1925. do_action("created_$taxonomy", $term_id, $tt_id);
  1926. return array('term_id' => $term_id, 'term_taxonomy_id' => $tt_id);
  1927. }
  1928. /**
  1929. * Create Term and Taxonomy Relationships.
  1930. *
  1931. * Relates an object (post, link etc) to a term and taxonomy type. Creates the
  1932. * term and taxonomy relationship if it doesn't already exist. Creates a term if
  1933. * it doesn't exist (using the slug).
  1934. *
  1935. * A relationship means that the term is grouped in or belongs to the taxonomy.
  1936. * A term has no meaning until it is given context by defining which taxonomy it
  1937. * exists under.
  1938. *
  1939. * @package WordPress
  1940. * @subpackage Taxonomy
  1941. * @since 2.3.0
  1942. * @uses wp_remove_object_terms()
  1943. *
  1944. * @param int $object_id The object to relate to.
  1945. * @param array|int|string $terms The slug or id of the term, will replace all existing
  1946. * related terms in this taxonomy.
  1947. * @param array|string $taxonomy The context in which to relate the term to the object.
  1948. * @param bool $append If false will delete difference of terms.
  1949. * @return array|WP_Error Affected Term IDs
  1950. */
  1951. function wp_set_object_terms($object_id, $terms, $taxonomy, $append = false) {
  1952. global $wpdb;
  1953. $object_id = (int) $object_id;
  1954. if ( ! taxonomy_exists($taxonomy) )
  1955. return new WP_Error('invalid_taxonomy', __('Invalid taxonomy'));
  1956. if ( !is_array($terms) )
  1957. $terms = array($terms);
  1958. if ( ! $append )
  1959. $old_tt_ids = wp_get_object_terms($object_id, $taxonomy, array('fields' => 'tt_ids', 'orderby' => 'none'));
  1960. else
  1961. $old_tt_ids = array();
  1962. $tt_ids = array();
  1963. $term_ids = array();
  1964. $new_tt_ids = array();
  1965. foreach ( (array) $terms as $term) {
  1966. if ( !strlen(trim($term)) )
  1967. continue;
  1968. if ( !$term_info = term_exists($term, $taxonomy) ) {
  1969. // Skip if a non-existent term ID is passed.
  1970. if ( is_int($term) )
  1971. continue;
  1972. $term_info = wp_insert_term($term, $taxonomy);
  1973. }
  1974. if ( is_wp_error($term_info) )
  1975. return $term_info;
  1976. $term_ids[] = $term_info['term_id'];
  1977. $tt_id = $term_info['term_taxonomy_id'];
  1978. $tt_ids[] = $tt_id;
  1979. 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 ) ) )
  1980. continue;
  1981. do_action( 'add_term_relationship', $object_id, $tt_id );
  1982. $wpdb->insert( $wpdb->term_relationships, array( 'object_id' => $object_id, 'term_taxonomy_id' => $tt_id ) );
  1983. do_action( 'added_term_relationship', $object_id, $tt_id );
  1984. $new_tt_ids[] = $tt_id;
  1985. }
  1986. if ( $new_tt_ids )
  1987. wp_update_term_count( $new_tt_ids, $taxonomy );
  1988. if ( ! $append ) {
  1989. $delete_tt_ids = array_diff( $old_tt_ids, $tt_ids );
  1990. if ( $delete_tt_ids ) {
  1991. $in_delete_tt_ids = "'" . implode( "', '", $delete_tt_ids ) . "'";
  1992. $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 ) );
  1993. $delete_term_ids = array_map( 'intval', $delete_term_ids );
  1994. $remove = wp_remove_object_terms( $object_id, $delete_term_ids, $taxonomy );
  1995. if ( is_wp_error( $remove ) ) {
  1996. return $remove;
  1997. }
  1998. }
  1999. }
  2000. $t = get_taxonomy($taxonomy);
  2001. if ( ! $append && isset($t->sort) && $t->sort ) {
  2002. $values = array();
  2003. $term_order = 0;
  2004. $final_tt_ids = wp_get_object_terms($object_id, $taxonomy, array('fields' => 'tt_ids'));
  2005. foreach ( $tt_ids as $tt_id )
  2006. if ( in_array($tt_id, $final_tt_ids) )
  2007. $values[] = $wpdb->prepare( "(%d, %d, %d)", $object_id, $tt_id, ++$term_order);
  2008. if ( $values )
  2009. 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)" ) )
  2010. return new WP_Error( 'db_insert_error', __( 'Could not insert term relationship into the database' ), $wpdb->last_error );
  2011. }
  2012. wp_cache_delete( $object_id, $taxonomy . '_relationships' );
  2013. do_action('set_object_terms', $object_id, $terms, $tt_ids, $taxonomy, $append, $old_tt_ids);
  2014. return $tt_ids;
  2015. }
  2016. /**
  2017. * Add term(s) associated with a given object.
  2018. *
  2019. * @package WordPress
  2020. * @subpackage Taxonomy
  2021. * @since 3.6
  2022. * @uses wp_set_object_terms()
  2023. *
  2024. * @param int $object_id The ID of the object to which the terms will be added.
  2025. * @param array|int|string $terms The slug(s) or ID(s) of the term(s) to add.
  2026. * @param array|string $taxonomy Taxonomy name.
  2027. * @return array|WP_Error Affected Term IDs
  2028. */
  2029. function wp_add_object_terms( $object_id, $terms, $taxonomy ) {
  2030. return wp_set_object_terms( $object_id, $terms, $taxonomy, true );
  2031. }
  2032. /**
  2033. * Remove term(s) associated with a given object.
  2034. *
  2035. * @package WordPress
  2036. * @subpackage Taxonomy
  2037. * @since 3.6
  2038. * @uses $wpdb
  2039. *
  2040. * @uses apply_filters() Calls 'delete_term_relationships' hook with object_id and tt_ids as parameters.
  2041. * @uses apply_filters() Calls 'deleted_term_relationships' hook with object_id and tt_ids as parameters.
  2042. *
  2043. * @param int $object_id The ID of the object from which the terms will be removed.
  2044. * @param array|int|string $terms The slug(s) or ID(s) of the term(s) to remove.
  2045. * @param array|string $taxonomy Taxonomy name.
  2046. * @return bool|WP_Error True on success, false or WP_Error on failure.
  2047. */
  2048. function wp_remove_object_terms( $object_id, $terms, $taxonomy ) {
  2049. global $wpdb;
  2050. $object_id = (int) $object_id;
  2051. if ( ! taxonomy_exists( $taxonomy ) ) {
  2052. return new WP_Error( 'invalid_taxonomy', __( 'Invalid Taxonomy' ) );
  2053. }
  2054. if ( ! is_array( $terms ) ) {
  2055. $terms = array( $terms );
  2056. }
  2057. $tt_ids = array();
  2058. foreach ( (array) $terms as $term ) {
  2059. if ( ! strlen( trim( $term ) ) ) {
  2060. continue;
  2061. }
  2062. if ( ! $term_info = term_exists( $term, $taxonomy ) ) {
  2063. // Skip if a non-existent term ID is passed.
  2064. if ( is_int( $term ) ) {
  2065. continue;
  2066. }
  2067. }
  2068. if ( is_wp_error( $term_info ) ) {
  2069. return $term_info;
  2070. }
  2071. $tt_ids[] = $term_info['term_taxonomy_id'];
  2072. }
  2073. if ( $tt_ids ) {
  2074. $in_tt_ids = "'" . implode( "', '", $tt_ids ) . "'";
  2075. do_action( 'delete_term_relationships', $object_id, $tt_ids );
  2076. $deleted = $wpdb->query( $wpdb->prepare( "DELETE FROM $wpdb->term_relationships WHERE object_id = %d AND term_taxonomy_id IN ($in_tt_ids)", $object_id ) );
  2077. do_action( 'deleted_term_relationships', $object_id, $tt_ids );
  2078. wp_update_term_count( $tt_ids, $taxonomy );
  2079. return (bool) $deleted;
  2080. }
  2081. return false;
  2082. }
  2083. /**
  2084. * Will make slug unique, if it isn't already.
  2085. *
  2086. * The $slug has to be unique global to every taxonomy, meaning that one
  2087. * taxonomy term can't have a matching slug with another taxonomy term. Each
  2088. * slug has to be globally unique for every taxonomy.
  2089. *
  2090. * The way this works is that if the taxonomy that the term belongs to is
  2091. * hierarchical and has a parent, it will append that parent to the $slug.
  2092. *
  2093. * If that still doesn't return an unique slug, then it try to append a number
  2094. * until it finds a number that is truly unique.
  2095. *
  2096. * The only purpose for $term is for appending a parent, if one exists.
  2097. *
  2098. * @package WordPress
  2099. * @subpackage Taxonomy
  2100. * @since 2.3.0
  2101. * @uses $wpdb
  2102. *
  2103. * @param string $slug The string that will be tried for a unique slug
  2104. * @param object $term The term object that the $slug will belong too
  2105. * @return string Will return a true unique slug.
  2106. */
  2107. function wp_unique_term_slug($slug, $term) {
  2108. global $wpdb;
  2109. if ( ! term_exists( $slug ) )
  2110. return $slug;
  2111. // If the taxonomy supports hierarchy and the term has a parent, make the slug unique
  2112. // by incorporating parent slugs.
  2113. if ( is_taxonomy_hierarchical($term->taxonomy) && !empty($term->parent) ) {
  2114. $the_parent = $term->parent;
  2115. while ( ! empty($the_parent) ) {
  2116. $parent_term = get_term($the_parent, $term->taxonomy);
  2117. if ( is_wp_error($parent_term) || empty($parent_term) )
  2118. break;
  2119. $slug .= '-' . $parent_term->slug;
  2120. if ( ! term_exists( $slug ) )
  2121. return $slug;
  2122. if ( empty($parent_term->parent) )
  2123. break;
  2124. $the_parent = $parent_term->parent;
  2125. }
  2126. }
  2127. // If we didn't get a unique slug, try appending a number to make it unique.
  2128. if ( ! empty( $term->term_id ) )
  2129. $query = $wpdb->prepare( "SELECT slug FROM $wpdb->terms WHERE slug = %s AND term_id != %d", $slug, $term->term_id );
  2130. else
  2131. $query = $wpdb->prepare( "SELECT slug FROM $wpdb->terms WHERE slug = %s", $slug );
  2132. if ( $wpdb->get_var( $query ) ) {
  2133. $num = 2;
  2134. do {
  2135. $alt_slug = $slug . "-$num";
  2136. $num++;
  2137. $slug_check = $wpdb->get_var( $wpdb->prepare( "SELECT slug FROM $wpdb->terms WHERE slug = %s", $alt_slug ) );
  2138. } while ( $slug_check );
  2139. $slug = $alt_slug;
  2140. }
  2141. return $slug;
  2142. }
  2143. /**
  2144. * Update term based on arguments provided.
  2145. *
  2146. * The $args will indiscriminately override all values with the same field name.
  2147. * Care must be taken to not override important information need to update or
  2148. * update will fail (or perhaps create a new term, neither would be acceptable).
  2149. *
  2150. * Defaults will set 'alias_of', 'description', 'parent', and 'slug' if not
  2151. * defined in $args already.
  2152. *
  2153. * 'alias_of' will create a term group, if it doesn't already exist, and update
  2154. * it for the $term.
  2155. *
  2156. * If the 'slug' argument in $args is missing, then the 'name' in $args will be
  2157. * used. It should also be noted that if you set 'slug' and it isn't unique then
  2158. * a WP_Error will be passed back. If you don't pass any slug, then a unique one
  2159. * will be created for you.
  2160. *
  2161. * For what can be overrode in $args, check the term scheme can contain and stay
  2162. * away from the term keys.
  2163. *
  2164. * @package WordPress
  2165. * @subpackage Taxonomy
  2166. * @since 2.3.0
  2167. *
  2168. * @uses $wpdb
  2169. * @uses do_action() Will call both 'edit_term' and 'edit_$taxonomy' twice.
  2170. * @uses apply_filters() Will call the 'term_id_filter' filter and pass the term
  2171. * id and taxonomy id.
  2172. *
  2173. * @param int $term_id The ID of the term
  2174. * @param string $taxonomy The context in which to relate the term to the object.
  2175. * @param array|string $args Overwrite term field values
  2176. * @return array|WP_Error Returns Term ID and Taxonomy Term ID
  2177. */
  2178. function wp_update_term( $term_id, $taxonomy, $args = array() ) {
  2179. global $wpdb;
  2180. if ( ! taxonomy_exists($taxonomy) )
  2181. return new WP_Error('invalid_taxonomy', __('Invalid taxonomy'));
  2182. $term_id = (int) $term_id;
  2183. // First, get all of the original args
  2184. $term = get_term ($term_id, $taxonomy, ARRAY_A);
  2185. if ( is_wp_error( $term ) )
  2186. return $term;
  2187. // Escape data pulled from DB.
  2188. $term = wp_slash($term);
  2189. // Merge old and new args with new args overwriting old ones.
  2190. $args = array_merge($term, $args);
  2191. $defaults = array( 'alias_of' => '', 'description' => '', 'parent' => 0, 'slug' => '');
  2192. $args = wp_parse_args($args, $defaults);
  2193. $args = sanitize_term($args, $taxonomy, 'db');
  2194. extract($args, EXTR_SKIP);
  2195. // expected_slashed ($name)
  2196. $name = wp_unslash($name);
  2197. $description = wp_unslash($description);
  2198. if ( '' == trim($name) )
  2199. return new WP_Error('empty_term_name', __('A name is required for this term'));
  2200. $empty_slug = false;
  2201. if ( empty($slug) ) {
  2202. $empty_slug = true;
  2203. $slug = sanitize_title($name);
  2204. }
  2205. if ( $alias_of ) {
  2206. $alias = $wpdb->get_row( $wpdb->prepare( "SELECT term_id, term_group FROM $wpdb->terms WHERE slug = %s", $alias_of) );
  2207. if ( $alias->term_group ) {
  2208. // The alias we want is already in a group, so let's use that one.
  2209. $term_group = $alias->term_group;
  2210. } else {
  2211. // The alias isn't in a group, so let's create a new one and firstly add the alias term to it.
  2212. $term_group = $wpdb->get_var("SELECT MAX(term_group) FROM $wpdb->terms") + 1;
  2213. do_action( 'edit_terms', $alias->term_id, $taxonomy );
  2214. $wpdb->update( $wpdb->terms, compact('term_group'), array( 'term_id' => $alias->term_id ) );
  2215. do_action( 'edited_terms', $alias->term_id, $taxonomy );
  2216. }
  2217. }
  2218. // Check $parent to see if it will cause a hierarchy loop
  2219. $parent = apply_filters( 'wp_update_term_parent', $parent, $term_id, $taxonomy, compact( array_keys( $args ) ), $args );
  2220. // Check for duplicate slug
  2221. $id = $wpdb->get_var( $wpdb->prepare( "SELECT term_id FROM $wpdb->terms WHERE slug = %s", $slug ) );
  2222. if ( $id && ($id != $term_id) ) {
  2223. // If an empty slug was passed or the parent changed, reset the slug to something unique.
  2224. // Otherwise, bail.
  2225. if ( $empty_slug || ( $parent != $term['parent']) )
  2226. $slug = wp_unique_term_slug($slug, (object) $args);
  2227. else
  2228. return new WP_Error('duplicate_term_slug', sprintf(__('The slug &#8220;%s&#8221; is already in use by another term'), $slug));
  2229. }
  2230. do_action( 'edit_terms', $term_id, $taxonomy );
  2231. $wpdb->update($wpdb->terms, compact( 'name', 'slug', 'term_group' ), compact( 'term_id' ) );
  2232. if ( empty($slug) ) {
  2233. $slug = sanitize_title($name, $term_id);
  2234. $wpdb->update( $wpdb->terms, compact( 'slug' ), compact( 'term_id' ) );
  2235. }
  2236. do_action( 'edited_terms', $term_id, $taxonomy );
  2237. $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) );
  2238. do_action( 'edit_term_taxonomy', $tt_id, $taxonomy );
  2239. $wpdb->update( $wpdb->term_taxonomy, compact( 'term_id', 'taxonomy', 'description', 'parent' ), array( 'term_taxonomy_id' => $tt_id ) );
  2240. do_action( 'edited_term_taxonomy', $tt_id, $taxonomy );
  2241. do_action("edit_term", $term_id, $tt_id, $taxonomy);
  2242. do_action("edit_$taxonomy", $term_id, $tt_id);
  2243. $term_id = apply_filters('term_id_filter', $term_id, $tt_id);
  2244. clean_term_cache($term_id, $taxonomy);
  2245. do_action("edited_term", $term_id, $tt_id, $taxonomy);
  2246. do_action("edited_$taxonomy", $term_id, $tt_id);
  2247. return array('term_id' => $term_id, 'term_taxonomy_id' => $tt_id);
  2248. }
  2249. /**
  2250. * Enable or disable term counting.
  2251. *
  2252. * @since 2.5.0
  2253. *
  2254. * @param bool $defer Optional. Enable if true, disable if false.
  2255. * @return bool Whether term counting is enabled or disabled.
  2256. */
  2257. function wp_defer_term_counting($defer=null) {
  2258. static $_defer = false;
  2259. if ( is_bool($defer) ) {
  2260. $_defer = $defer;
  2261. // flush any deferred counts
  2262. if ( !$defer )
  2263. wp_update_term_count( null, null, true );
  2264. }
  2265. return $_defer;
  2266. }
  2267. /**
  2268. * Updates the amount of terms in taxonomy.
  2269. *
  2270. * If there is a taxonomy callback applied, then it will be called for updating
  2271. * the count.
  2272. *
  2273. * The default action is to count what the amount of terms have the relationship
  2274. * of term ID. Once that is done, then update the database.
  2275. *
  2276. * @package WordPress
  2277. * @subpackage Taxonomy
  2278. * @since 2.3.0
  2279. * @uses $wpdb
  2280. *
  2281. * @param int|array $terms The term_taxonomy_id of the terms
  2282. * @param string $taxonomy The context of the term.
  2283. * @return bool If no terms will return false, and if successful will return true.
  2284. */
  2285. function wp_update_term_count( $terms, $taxonomy, $do_deferred=false ) {
  2286. static $_deferred = array();
  2287. if ( $do_deferred ) {
  2288. foreach ( (array) array_keys($_deferred) as $tax ) {
  2289. wp_update_term_count_now( $_deferred[$tax], $tax );
  2290. unset( $_deferred[$tax] );
  2291. }
  2292. }
  2293. if ( empty($terms) )
  2294. return false;
  2295. if ( !is_array($terms) )
  2296. $terms = array($terms);
  2297. if ( wp_defer_term_counting() ) {
  2298. if ( !isset($_deferred[$taxonomy]) )
  2299. $_deferred[$taxonomy] = array();
  2300. $_deferred[$taxonomy] = array_unique( array_merge($_deferred[$taxonomy], $terms) );
  2301. return true;
  2302. }
  2303. return wp_update_term_count_now( $terms, $taxonomy );
  2304. }
  2305. /**
  2306. * Perform term count update immediately.
  2307. *
  2308. * @since 2.5.0
  2309. *
  2310. * @param array $terms The term_taxonomy_id of terms to update.
  2311. * @param string $taxonomy The context of the term.
  2312. * @return bool Always true when complete.
  2313. */
  2314. function wp_update_term_count_now( $terms, $taxonomy ) {
  2315. global $wpdb;
  2316. $terms = array_map('intval', $terms);
  2317. $taxonomy = get_taxonomy($taxonomy);
  2318. if ( !empty($taxonomy->update_count_callback) ) {
  2319. call_user_func($taxonomy->update_count_callback, $terms, $taxonomy);
  2320. } else {
  2321. $object_types = (array) $taxonomy->object_type;
  2322. foreach ( $object_types as &$object_type ) {
  2323. if ( 0 === strpos( $object_type, 'attachment:' ) )
  2324. list( $object_type ) = explode( ':', $object_type );
  2325. }
  2326. if ( $object_types == array_filter( $object_types, 'post_type_exists' ) ) {
  2327. // Only post types are attached to this taxonomy
  2328. _update_post_term_count( $terms, $taxonomy );
  2329. } else {
  2330. // Default count updater
  2331. _update_generic_term_count( $terms, $taxonomy );
  2332. }
  2333. }
  2334. clean_term_cache($terms, '', false);
  2335. return true;
  2336. }
  2337. //
  2338. // Cache
  2339. //
  2340. /**
  2341. * Removes the taxonomy relationship to terms from the cache.
  2342. *
  2343. * Will remove the entire taxonomy relationship containing term $object_id. The
  2344. * term IDs have to exist within the taxonomy $object_type for the deletion to
  2345. * take place.
  2346. *
  2347. * @package WordPress
  2348. * @subpackage Taxonomy
  2349. * @since 2.3.0
  2350. *
  2351. * @see get_object_taxonomies() for more on $object_type
  2352. * @uses do_action() Will call action hook named, 'clean_object_term_cache' after completion.
  2353. * Passes, function params in same order.
  2354. *
  2355. * @param int|array $object_ids Single or list of term object ID(s)
  2356. * @param array|string $object_type The taxonomy object type
  2357. */
  2358. function clean_object_term_cache($object_ids, $object_type) {
  2359. if ( !is_array($object_ids) )
  2360. $object_ids = array($object_ids);
  2361. $taxonomies = get_object_taxonomies( $object_type );
  2362. foreach ( $object_ids as $id )
  2363. foreach ( $taxonomies as $taxonomy )
  2364. wp_cache_delete($id, "{$taxonomy}_relationships");
  2365. do_action('clean_object_term_cache', $object_ids, $object_type);
  2366. }
  2367. /**
  2368. * Will remove all of the term ids from the cache.
  2369. *
  2370. * @package WordPress
  2371. * @subpackage Taxonomy
  2372. * @since 2.3.0
  2373. * @uses $wpdb
  2374. *
  2375. * @param int|array $ids Single or list of Term IDs
  2376. * @param string $taxonomy Can be empty and will assume tt_ids, else will use for context.
  2377. * @param bool $clean_taxonomy Whether to clean taxonomy wide caches (true), or just individual term object caches (false). Default is true.
  2378. */
  2379. function clean_term_cache($ids, $taxonomy = '', $clean_taxonomy = true) {
  2380. global $wpdb;
  2381. static $cleaned = array();
  2382. if ( !is_array($ids) )
  2383. $ids = array($ids);
  2384. $taxonomies = array();
  2385. // If no taxonomy, assume tt_ids.
  2386. if ( empty($taxonomy) ) {
  2387. $tt_ids = array_map('intval', $ids);
  2388. $tt_ids = implode(', ', $tt_ids);
  2389. $terms = $wpdb->get_results("SELECT term_id, taxonomy FROM $wpdb->term_taxonomy WHERE term_taxonomy_id IN ($tt_ids)");
  2390. $ids = array();
  2391. foreach ( (array) $terms as $term ) {
  2392. $taxonomies[] = $term->taxonomy;
  2393. $ids[] = $term->term_id;
  2394. wp_cache_delete($term->term_id, $term->taxonomy);
  2395. }
  2396. $taxonomies = array_unique($taxonomies);
  2397. } else {
  2398. $taxonomies = array($taxonomy);
  2399. foreach ( $taxonomies as $taxonomy ) {
  2400. foreach ( $ids as $id ) {
  2401. wp_cache_delete($id, $taxonomy);
  2402. }
  2403. }
  2404. }
  2405. foreach ( $taxonomies as $taxonomy ) {
  2406. if ( isset($cleaned[$taxonomy]) )
  2407. continue;
  2408. $cleaned[$taxonomy] = true;
  2409. if ( $clean_taxonomy ) {
  2410. wp_cache_delete('all_ids', $taxonomy);
  2411. wp_cache_delete('get', $taxonomy);
  2412. delete_option("{$taxonomy}_children");
  2413. // Regenerate {$taxonomy}_children
  2414. _get_term_hierarchy($taxonomy);
  2415. }
  2416. do_action('clean_term_cache', $ids, $taxonomy);
  2417. }
  2418. wp_cache_set( 'last_changed', microtime(), 'terms' );
  2419. }
  2420. /**
  2421. * Retrieves the taxonomy relationship to the term object id.
  2422. *
  2423. * @package WordPress
  2424. * @subpackage Taxonomy
  2425. * @since 2.3.0
  2426. *
  2427. * @uses wp_cache_get() Retrieves taxonomy relationship from cache
  2428. *
  2429. * @param int|array $id Term object ID
  2430. * @param string $taxonomy Taxonomy Name
  2431. * @return bool|array Empty array if $terms found, but not $taxonomy. False if nothing is in cache for $taxonomy and $id.
  2432. */
  2433. function get_object_term_cache($id, $taxonomy) {
  2434. $cache = wp_cache_get($id, "{$taxonomy}_relationships");
  2435. return $cache;
  2436. }
  2437. /**
  2438. * Updates the cache for Term ID(s).
  2439. *
  2440. * Will only update the cache for terms not already cached.
  2441. *
  2442. * The $object_ids expects that the ids be separated by commas, if it is a
  2443. * string.
  2444. *
  2445. * It should be noted that update_object_term_cache() is very time extensive. It
  2446. * is advised that the function is not called very often or at least not for a
  2447. * lot of terms that exist in a lot of taxonomies. The amount of time increases
  2448. * for each term and it also increases for each taxonomy the term belongs to.
  2449. *
  2450. * @package WordPress
  2451. * @subpackage Taxonomy
  2452. * @since 2.3.0
  2453. * @uses wp_get_object_terms() Used to get terms from the database to update
  2454. *
  2455. * @param string|array $object_ids Single or list of term object ID(s)
  2456. * @param array|string $object_type The taxonomy object type
  2457. * @return null|bool Null value is given with empty $object_ids. False if
  2458. */
  2459. function update_object_term_cache($object_ids, $object_type) {
  2460. if ( empty($object_ids) )
  2461. return;
  2462. if ( !is_array($object_ids) )
  2463. $object_ids = explode(',', $object_ids);
  2464. $object_ids = array_map('intval', $object_ids);
  2465. $taxonomies = get_object_taxonomies($object_type);
  2466. $ids = array();
  2467. foreach ( (array) $object_ids as $id ) {
  2468. foreach ( $taxonomies as $taxonomy ) {
  2469. if ( false === wp_cache_get($id, "{$taxonomy}_relationships") ) {
  2470. $ids[] = $id;
  2471. break;
  2472. }
  2473. }
  2474. }
  2475. if ( empty( $ids ) )
  2476. return false;
  2477. $terms = wp_get_object_terms($ids, $taxonomies, array('fields' => 'all_with_object_id'));
  2478. $object_terms = array();
  2479. foreach ( (array) $terms as $term )
  2480. $object_terms[$term->object_id][$term->taxonomy][$term->term_id] = $term;
  2481. foreach ( $ids as $id ) {
  2482. foreach ( $taxonomies as $taxonomy ) {
  2483. if ( ! isset($object_terms[$id][$taxonomy]) ) {
  2484. if ( !isset($object_terms[$id]) )
  2485. $object_terms[$id] = array();
  2486. $object_terms[$id][$taxonomy] = array();
  2487. }
  2488. }
  2489. }
  2490. foreach ( $object_terms as $id => $value ) {
  2491. foreach ( $value as $taxonomy => $terms ) {
  2492. wp_cache_add( $id, $terms, "{$taxonomy}_relationships" );
  2493. }
  2494. }
  2495. }
  2496. /**
  2497. * Updates Terms to Taxonomy in cache.
  2498. *
  2499. * @package WordPress
  2500. * @subpackage Taxonomy
  2501. * @since 2.3.0
  2502. *
  2503. * @param array $terms List of Term objects to change
  2504. * @param string $taxonomy Optional. Update Term to this taxonomy in cache
  2505. */
  2506. function update_term_cache($terms, $taxonomy = '') {
  2507. foreach ( (array) $terms as $term ) {
  2508. $term_taxonomy = $taxonomy;
  2509. if ( empty($term_taxonomy) )
  2510. $term_taxonomy = $term->taxonomy;
  2511. wp_cache_add($term->term_id, $term, $term_taxonomy);
  2512. }
  2513. }
  2514. //
  2515. // Private
  2516. //
  2517. /**
  2518. * Retrieves children of taxonomy as Term IDs.
  2519. *
  2520. * @package WordPress
  2521. * @subpackage Taxonomy
  2522. * @access private
  2523. * @since 2.3.0
  2524. *
  2525. * @uses update_option() Stores all of the children in "$taxonomy_children"
  2526. * option. That is the name of the taxonomy, immediately followed by '_children'.
  2527. *
  2528. * @param string $taxonomy Taxonomy Name
  2529. * @return array Empty if $taxonomy isn't hierarchical or returns children as Term IDs.
  2530. */
  2531. function _get_term_hierarchy($taxonomy) {
  2532. if ( !is_taxonomy_hierarchical($taxonomy) )
  2533. return array();
  2534. $children = get_option("{$taxonomy}_children");
  2535. if ( is_array($children) )
  2536. return $children;
  2537. $children = array();
  2538. $terms = get_terms($taxonomy, array('get' => 'all', 'orderby' => 'id', 'fields' => 'id=>parent'));
  2539. foreach ( $terms as $term_id => $parent ) {
  2540. if ( $parent > 0 )
  2541. $children[$parent][] = $term_id;
  2542. }
  2543. update_option("{$taxonomy}_children", $children);
  2544. return $children;
  2545. }
  2546. /**
  2547. * Get the subset of $terms that are descendants of $term_id.
  2548. *
  2549. * If $terms is an array of objects, then _get_term_children returns an array of objects.
  2550. * If $terms is an array of IDs, then _get_term_children returns an array of IDs.
  2551. *
  2552. * @package WordPress
  2553. * @subpackage Taxonomy
  2554. * @access private
  2555. * @since 2.3.0
  2556. *
  2557. * @param int $term_id The ancestor term: all returned terms should be descendants of $term_id.
  2558. * @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.
  2559. * @param string $taxonomy The taxonomy which determines the hierarchy of the terms.
  2560. * @return array The subset of $terms that are descendants of $term_id.
  2561. */
  2562. function _get_term_children($term_id, $terms, $taxonomy) {
  2563. $empty_array = array();
  2564. if ( empty($terms) )
  2565. return $empty_array;
  2566. $term_list = array();
  2567. $has_children = _get_term_hierarchy($taxonomy);
  2568. if ( ( 0 != $term_id ) && ! isset($has_children[$term_id]) )
  2569. return $empty_array;
  2570. foreach ( (array) $terms as $term ) {
  2571. $use_id = false;
  2572. if ( !is_object($term) ) {
  2573. $term = get_term($term, $taxonomy);
  2574. if ( is_wp_error( $term ) )
  2575. return $term;
  2576. $use_id = true;
  2577. }
  2578. if ( $term->term_id == $term_id )
  2579. continue;
  2580. if ( $term->parent == $term_id ) {
  2581. if ( $use_id )
  2582. $term_list[] = $term->term_id;
  2583. else
  2584. $term_list[] = $term;
  2585. if ( !isset($has_children[$term->term_id]) )
  2586. continue;
  2587. if ( $children = _get_term_children($term->term_id, $terms, $taxonomy) )
  2588. $term_list = array_merge($term_list, $children);
  2589. }
  2590. }
  2591. return $term_list;
  2592. }
  2593. /**
  2594. * Add count of children to parent count.
  2595. *
  2596. * Recalculates term counts by including items from child terms. Assumes all
  2597. * relevant children are already in the $terms argument.
  2598. *
  2599. * @package WordPress
  2600. * @subpackage Taxonomy
  2601. * @access private
  2602. * @since 2.3.0
  2603. * @uses $wpdb
  2604. *
  2605. * @param array $terms List of Term IDs
  2606. * @param string $taxonomy Term Context
  2607. * @return null Will break from function if conditions are not met.
  2608. */
  2609. function _pad_term_counts(&$terms, $taxonomy) {
  2610. global $wpdb;
  2611. // This function only works for hierarchical taxonomies like post categories.
  2612. if ( !is_taxonomy_hierarchical( $taxonomy ) )
  2613. return;
  2614. $term_hier = _get_term_hierarchy($taxonomy);
  2615. if ( empty($term_hier) )
  2616. return;
  2617. $term_items = array();
  2618. foreach ( (array) $terms as $key => $term ) {
  2619. $terms_by_id[$term->term_id] = & $terms[$key];
  2620. $term_ids[$term->term_taxonomy_id] = $term->term_id;
  2621. }
  2622. // Get the object and term ids and stick them in a lookup table
  2623. $tax_obj = get_taxonomy($taxonomy);
  2624. $object_types = esc_sql($tax_obj->object_type);
  2625. $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'");
  2626. foreach ( $results as $row ) {
  2627. $id = $term_ids[$row->term_taxonomy_id];
  2628. $term_items[$id][$row->object_id] = isset($term_items[$id][$row->object_id]) ? ++$term_items[$id][$row->object_id] : 1;
  2629. }
  2630. // Touch every ancestor's lookup row for each post in each term
  2631. foreach ( $term_ids as $term_id ) {
  2632. $child = $term_id;
  2633. while ( !empty( $terms_by_id[$child] ) && $parent = $terms_by_id[$child]->parent ) {
  2634. if ( !empty( $term_items[$term_id] ) )
  2635. foreach ( $term_items[$term_id] as $item_id => $touches ) {
  2636. $term_items[$parent][$item_id] = isset($term_items[$parent][$item_id]) ? ++$term_items[$parent][$item_id]: 1;
  2637. }
  2638. $child = $parent;
  2639. }
  2640. }
  2641. // Transfer the touched cells
  2642. foreach ( (array) $term_items as $id => $items )
  2643. if ( isset($terms_by_id[$id]) )
  2644. $terms_by_id[$id]->count = count($items);
  2645. }
  2646. //
  2647. // Default callbacks
  2648. //
  2649. /**
  2650. * Will update term count based on object types of the current taxonomy.
  2651. *
  2652. * Private function for the default callback for post_tag and category
  2653. * taxonomies.
  2654. *
  2655. * @package WordPress
  2656. * @subpackage Taxonomy
  2657. * @access private
  2658. * @since 2.3.0
  2659. * @uses $wpdb
  2660. *
  2661. * @param array $terms List of Term taxonomy IDs
  2662. * @param object $taxonomy Current taxonomy object of terms
  2663. */
  2664. function _update_post_term_count( $terms, $taxonomy ) {
  2665. global $wpdb;
  2666. $object_types = (array) $taxonomy->object_type;
  2667. foreach ( $object_types as &$object_type )
  2668. list( $object_type ) = explode( ':', $object_type );
  2669. $object_types = array_unique( $object_types );
  2670. if ( false !== ( $check_attachments = array_search( 'attachment', $object_types ) ) ) {
  2671. unset( $object_types[ $check_attachments ] );
  2672. $check_attachments = true;
  2673. }
  2674. if ( $object_types )
  2675. $object_types = esc_sql( array_filter( $object_types, 'post_type_exists' ) );
  2676. foreach ( (array) $terms as $term ) {
  2677. $count = 0;
  2678. // Attachments can be 'inherit' status, we need to base count off the parent's status if so
  2679. if ( $check_attachments )
  2680. $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 ) );
  2681. if ( $object_types )
  2682. $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 ) );
  2683. do_action( 'edit_term_taxonomy', $term, $taxonomy );
  2684. $wpdb->update( $wpdb->term_taxonomy, compact( 'count' ), array( 'term_taxonomy_id' => $term ) );
  2685. do_action( 'edited_term_taxonomy', $term, $taxonomy );
  2686. }
  2687. }
  2688. /**
  2689. * Will update term count based on number of objects.
  2690. *
  2691. * Default callback for the link_category taxonomy.
  2692. *
  2693. * @package WordPress
  2694. * @subpackage Taxonomy
  2695. * @since 3.3.0
  2696. * @uses $wpdb
  2697. *
  2698. * @param array $terms List of Term taxonomy IDs
  2699. * @param object $taxonomy Current taxonomy object of terms
  2700. */
  2701. function _update_generic_term_count( $terms, $taxonomy ) {
  2702. global $wpdb;
  2703. foreach ( (array) $terms as $term ) {
  2704. $count = $wpdb->get_var( $wpdb->prepare( "SELECT COUNT(*) FROM $wpdb->term_relationships WHERE term_taxonomy_id = %d", $term ) );
  2705. do_action( 'edit_term_taxonomy', $term, $taxonomy );
  2706. $wpdb->update( $wpdb->term_taxonomy, compact( 'count' ), array( 'term_taxonomy_id' => $term ) );
  2707. do_action( 'edited_term_taxonomy', $term, $taxonomy );
  2708. }
  2709. }
  2710. /**
  2711. * Generates a permalink for a taxonomy term archive.
  2712. *
  2713. * @since 2.5.0
  2714. *
  2715. * @uses apply_filters() Calls 'term_link' with term link and term object, and taxonomy parameters.
  2716. * @uses apply_filters() For the post_tag Taxonomy, Calls 'tag_link' with tag link and tag ID as parameters.
  2717. * @uses apply_filters() For the category Taxonomy, Calls 'category_link' filter on category link and category ID.
  2718. *
  2719. * @param object|int|string $term
  2720. * @param string $taxonomy (optional if $term is object)
  2721. * @return string|WP_Error HTML link to taxonomy term archive on success, WP_Error if term does not exist.
  2722. */
  2723. function get_term_link( $term, $taxonomy = '') {
  2724. global $wp_rewrite;
  2725. if ( !is_object($term) ) {
  2726. if ( is_int($term) ) {
  2727. $term = get_term($term, $taxonomy);
  2728. } else {
  2729. $term = get_term_by('slug', $term, $taxonomy);
  2730. }
  2731. }
  2732. if ( !is_object($term) )
  2733. $term = new WP_Error('invalid_term', __('Empty Term'));
  2734. if ( is_wp_error( $term ) )
  2735. return $term;
  2736. $taxonomy = $term->taxonomy;
  2737. $termlink = $wp_rewrite->get_extra_permastruct($taxonomy);
  2738. $slug = $term->slug;
  2739. $t = get_taxonomy($taxonomy);
  2740. if ( empty($termlink) ) {
  2741. if ( 'category' == $taxonomy )
  2742. $termlink = '?cat=' . $term->term_id;
  2743. elseif ( $t->query_var )
  2744. $termlink = "?$t->query_var=$slug";
  2745. else
  2746. $termlink = "?taxonomy=$taxonomy&term=$slug";
  2747. $termlink = home_url($termlink);
  2748. } else {
  2749. if ( $t->rewrite['hierarchical'] ) {
  2750. $hierarchical_slugs = array();
  2751. $ancestors = get_ancestors($term->term_id, $taxonomy);
  2752. foreach ( (array)$ancestors as $ancestor ) {
  2753. $ancestor_term = get_term($ancestor, $taxonomy);
  2754. $hierarchical_slugs[] = $ancestor_term->slug;
  2755. }
  2756. $hierarchical_slugs = array_reverse($hierarchical_slugs);
  2757. $hierarchical_slugs[] = $slug;
  2758. $termlink = str_replace("%$taxonomy%", implode('/', $hierarchical_slugs), $termlink);
  2759. } else {
  2760. $termlink = str_replace("%$taxonomy%", $slug, $termlink);
  2761. }
  2762. $termlink = home_url( user_trailingslashit($termlink, 'category') );
  2763. }
  2764. // Back Compat filters.
  2765. if ( 'post_tag' == $taxonomy )
  2766. $termlink = apply_filters( 'tag_link', $termlink, $term->term_id );
  2767. elseif ( 'category' == $taxonomy )
  2768. $termlink = apply_filters( 'category_link', $termlink, $term->term_id );
  2769. return apply_filters('term_link', $termlink, $term, $taxonomy);
  2770. }
  2771. /**
  2772. * Display the taxonomies of a post with available options.
  2773. *
  2774. * This function can be used within the loop to display the taxonomies for a
  2775. * post without specifying the Post ID. You can also use it outside the Loop to
  2776. * display the taxonomies for a specific post.
  2777. *
  2778. * The available defaults are:
  2779. * 'post' : default is 0. The post ID to get taxonomies of.
  2780. * 'before' : default is empty string. Display before taxonomies list.
  2781. * 'sep' : default is empty string. Separate every taxonomy with value in this.
  2782. * 'after' : default is empty string. Display this after the taxonomies list.
  2783. * 'template' : The template to use for displaying the taxonomy terms.
  2784. *
  2785. * @since 2.5.0
  2786. * @uses get_the_taxonomies()
  2787. *
  2788. * @param array $args Override the defaults.
  2789. */
  2790. function the_taxonomies($args = array()) {
  2791. $defaults = array(
  2792. 'post' => 0,
  2793. 'before' => '',
  2794. 'sep' => ' ',
  2795. 'after' => '',
  2796. 'template' => '%s: %l.'
  2797. );
  2798. $r = wp_parse_args( $args, $defaults );
  2799. extract( $r, EXTR_SKIP );
  2800. echo $before . join($sep, get_the_taxonomies($post, $r)) . $after;
  2801. }
  2802. /**
  2803. * Retrieve all taxonomies associated with a post.
  2804. *
  2805. * This function can be used within the loop. It will also return an array of
  2806. * the taxonomies with links to the taxonomy and name.
  2807. *
  2808. * @since 2.5.0
  2809. *
  2810. * @param int $post Optional. Post ID or will use Global Post ID (in loop).
  2811. * @param array $args Override the defaults.
  2812. * @return array
  2813. */
  2814. function get_the_taxonomies($post = 0, $args = array() ) {
  2815. $post = get_post( $post );
  2816. $args = wp_parse_args( $args, array(
  2817. 'template' => '%s: %l.',
  2818. ) );
  2819. extract( $args, EXTR_SKIP );
  2820. $taxonomies = array();
  2821. if ( !$post )
  2822. return $taxonomies;
  2823. foreach ( get_object_taxonomies($post) as $taxonomy ) {
  2824. $t = (array) get_taxonomy($taxonomy);
  2825. if ( empty($t['label']) )
  2826. $t['label'] = $taxonomy;
  2827. if ( empty($t['args']) )
  2828. $t['args'] = array();
  2829. if ( empty($t['template']) )
  2830. $t['template'] = $template;
  2831. $terms = get_object_term_cache($post->ID, $taxonomy);
  2832. if ( false === $terms )
  2833. $terms = wp_get_object_terms($post->ID, $taxonomy, $t['args']);
  2834. $links = array();
  2835. foreach ( $terms as $term )
  2836. $links[] = "<a href='" . esc_attr( get_term_link($term) ) . "'>$term->name</a>";
  2837. if ( $links )
  2838. $taxonomies[$taxonomy] = wp_sprintf($t['template'], $t['label'], $links, $terms);
  2839. }
  2840. return $taxonomies;
  2841. }
  2842. /**
  2843. * Retrieve all taxonomies of a post with just the names.
  2844. *
  2845. * @since 2.5.0
  2846. * @uses get_object_taxonomies()
  2847. *
  2848. * @param int $post Optional. Post ID
  2849. * @return array
  2850. */
  2851. function get_post_taxonomies($post = 0) {
  2852. $post = get_post( $post );
  2853. return get_object_taxonomies($post);
  2854. }
  2855. /**
  2856. * Determine if the given object is associated with any of the given terms.
  2857. *
  2858. * The given terms are checked against the object's terms' term_ids, names and slugs.
  2859. * Terms given as integers will only be checked against the object's terms' term_ids.
  2860. * If no terms are given, determines if object is associated with any terms in the given taxonomy.
  2861. *
  2862. * @since 2.7.0
  2863. * @uses get_object_term_cache()
  2864. * @uses wp_get_object_terms()
  2865. *
  2866. * @param int $object_id ID of the object (post ID, link ID, ...)
  2867. * @param string $taxonomy Single taxonomy name
  2868. * @param int|string|array $terms Optional. Term term_id, name, slug or array of said
  2869. * @return bool|WP_Error. WP_Error on input error.
  2870. */
  2871. function is_object_in_term( $object_id, $taxonomy, $terms = null ) {
  2872. if ( !$object_id = (int) $object_id )
  2873. return new WP_Error( 'invalid_object', __( 'Invalid object ID' ) );
  2874. $object_terms = get_object_term_cache( $object_id, $taxonomy );
  2875. if ( false === $object_terms )
  2876. $object_terms = wp_get_object_terms( $object_id, $taxonomy );
  2877. if ( is_wp_error( $object_terms ) )
  2878. return $object_terms;
  2879. if ( empty( $object_terms ) )
  2880. return false;
  2881. if ( empty( $terms ) )
  2882. return ( !empty( $object_terms ) );
  2883. $terms = (array) $terms;
  2884. if ( $ints = array_filter( $terms, 'is_int' ) )
  2885. $strs = array_diff( $terms, $ints );
  2886. else
  2887. $strs =& $terms;
  2888. foreach ( $object_terms as $object_term ) {
  2889. if ( $ints && in_array( $object_term->term_id, $ints ) ) return true; // If int, check against term_id
  2890. if ( $strs ) {
  2891. if ( in_array( $object_term->term_id, $strs ) ) return true;
  2892. if ( in_array( $object_term->name, $strs ) ) return true;
  2893. if ( in_array( $object_term->slug, $strs ) ) return true;
  2894. }
  2895. }
  2896. return false;
  2897. }
  2898. /**
  2899. * Determine if the given object type is associated with the given taxonomy.
  2900. *
  2901. * @since 3.0.0
  2902. * @uses get_object_taxonomies()
  2903. *
  2904. * @param string $object_type Object type string
  2905. * @param string $taxonomy Single taxonomy name
  2906. * @return bool True if object is associated with the taxonomy, otherwise false.
  2907. */
  2908. function is_object_in_taxonomy($object_type, $taxonomy) {
  2909. $taxonomies = get_object_taxonomies($object_type);
  2910. if ( empty($taxonomies) )
  2911. return false;
  2912. if ( in_array($taxonomy, $taxonomies) )
  2913. return true;
  2914. return false;
  2915. }
  2916. /**
  2917. * Get an array of ancestor IDs for a given object.
  2918. *
  2919. * @param int $object_id The ID of the object
  2920. * @param string $object_type The type of object for which we'll be retrieving ancestors.
  2921. * @return array of ancestors from lowest to highest in the hierarchy.
  2922. */
  2923. function get_ancestors($object_id = 0, $object_type = '') {
  2924. $object_id = (int) $object_id;
  2925. $ancestors = array();
  2926. if ( empty( $object_id ) ) {
  2927. return apply_filters('get_ancestors', $ancestors, $object_id, $object_type);
  2928. }
  2929. if ( is_taxonomy_hierarchical( $object_type ) ) {
  2930. $term = get_term($object_id, $object_type);
  2931. while ( ! is_wp_error($term) && ! empty( $term->parent ) && ! in_array( $term->parent, $ancestors ) ) {
  2932. $ancestors[] = (int) $term->parent;
  2933. $term = get_term($term->parent, $object_type);
  2934. }
  2935. } elseif ( post_type_exists( $object_type ) ) {
  2936. $ancestors = get_post_ancestors($object_id);
  2937. }
  2938. return apply_filters('get_ancestors', $ancestors, $object_id, $object_type);
  2939. }
  2940. /**
  2941. * Returns the term's parent's term_ID
  2942. *
  2943. * @since 3.1.0
  2944. *
  2945. * @param int $term_id
  2946. * @param string $taxonomy
  2947. *
  2948. * @return int|bool false on error
  2949. */
  2950. function wp_get_term_taxonomy_parent_id( $term_id, $taxonomy ) {
  2951. $term = get_term( $term_id, $taxonomy );
  2952. if ( !$term || is_wp_error( $term ) )
  2953. return false;
  2954. return (int) $term->parent;
  2955. }
  2956. /**
  2957. * Checks the given subset of the term hierarchy for hierarchy loops.
  2958. * Prevents loops from forming and breaks those that it finds.
  2959. *
  2960. * Attached to the wp_update_term_parent filter.
  2961. *
  2962. * @since 3.1.0
  2963. * @uses wp_find_hierarchy_loop()
  2964. *
  2965. * @param int $parent term_id of the parent for the term we're checking.
  2966. * @param int $term_id The term we're checking.
  2967. * @param string $taxonomy The taxonomy of the term we're checking.
  2968. *
  2969. * @return int The new parent for the term.
  2970. */
  2971. function wp_check_term_hierarchy_for_loops( $parent, $term_id, $taxonomy ) {
  2972. // Nothing fancy here - bail
  2973. if ( !$parent )
  2974. return 0;
  2975. // Can't be its own parent
  2976. if ( $parent == $term_id )
  2977. return 0;
  2978. // Now look for larger loops
  2979. if ( !$loop = wp_find_hierarchy_loop( 'wp_get_term_taxonomy_parent_id', $term_id, $parent, array( $taxonomy ) ) )
  2980. return $parent; // No loop
  2981. // Setting $parent to the given value causes a loop
  2982. if ( isset( $loop[$term_id] ) )
  2983. return 0;
  2984. // There's a loop, but it doesn't contain $term_id. Break the loop.
  2985. foreach ( array_keys( $loop ) as $loop_member )
  2986. wp_update_term( $loop_member, $taxonomy, array( 'parent' => 0 ) );
  2987. return $parent;
  2988. }