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