You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 
 

4224 lines
146 KiB

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