PageRenderTime 72ms CodeModel.GetById 17ms RepoModel.GetById 0ms app.codeStats 1ms

/wp-includes/taxonomy.php

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