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