]> scripts.mit.edu Git - autoinstalls/wordpress.git/blob - wp-includes/taxonomy.php
WordPress 4.7.2-scripts
[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 = wp_parse_args( $args );
1875
1876         $args['taxonomy'] = $taxonomies;
1877         $args['object_ids'] = $object_ids;
1878
1879         $terms = get_terms( $args );
1880
1881         /**
1882          * Filters the terms for a given object or objects.
1883          *
1884          * @since 4.2.0
1885          *
1886          * @param array $terms      An array of terms for the given object or objects.
1887          * @param array $object_ids Array of object IDs for which `$terms` were retrieved.
1888          * @param array $taxonomies Array of taxonomies from which `$terms` were retrieved.
1889          * @param array $args       An array of arguments for retrieving terms for the given
1890          *                          object(s). See wp_get_object_terms() for details.
1891          */
1892         $terms = apply_filters( 'get_object_terms', $terms, $object_ids, $taxonomies, $args );
1893
1894         $object_ids = implode( ',', $object_ids );
1895         $taxonomies = implode( ',', $taxonomies );
1896
1897         /**
1898          * Filters the terms for a given object or objects.
1899          *
1900          * The `$taxonomies` parameter passed to this filter is formatted as a SQL fragment. The
1901          * {@see 'get_object_terms'} filter is recommended as an alternative.
1902          *
1903          * @since 2.8.0
1904          *
1905          * @param array     $terms      An array of terms for the given object or objects.
1906          * @param int|array $object_ids Object ID or array of IDs.
1907          * @param string    $taxonomies SQL-formatted (comma-separated and quoted) list of taxonomy names.
1908          * @param array     $args       An array of arguments for retrieving terms for the given object(s).
1909          *                              See wp_get_object_terms() for details.
1910          */
1911         return apply_filters( 'wp_get_object_terms', $terms, $object_ids, $taxonomies, $args );
1912 }
1913
1914 /**
1915  * Add a new term to the database.
1916  *
1917  * A non-existent term is inserted in the following sequence:
1918  * 1. The term is added to the term table, then related to the taxonomy.
1919  * 2. If everything is correct, several actions are fired.
1920  * 3. The 'term_id_filter' is evaluated.
1921  * 4. The term cache is cleaned.
1922  * 5. Several more actions are fired.
1923  * 6. An array is returned containing the term_id and term_taxonomy_id.
1924  *
1925  * If the 'slug' argument is not empty, then it is checked to see if the term
1926  * is invalid. If it is not a valid, existing term, it is added and the term_id
1927  * is given.
1928  *
1929  * If the taxonomy is hierarchical, and the 'parent' argument is not empty,
1930  * the term is inserted and the term_id will be given.
1931  *
1932  * Error handling:
1933  * If $taxonomy does not exist or $term is empty,
1934  * a WP_Error object will be returned.
1935  *
1936  * If the term already exists on the same hierarchical level,
1937  * or the term slug and name are not unique, a WP_Error object will be returned.
1938  *
1939  * @global wpdb $wpdb WordPress database abstraction object.
1940  *
1941  * @since 2.3.0
1942  *
1943  * @param string       $term     The term to add or update.
1944  * @param string       $taxonomy The taxonomy to which to add the term.
1945  * @param array|string $args {
1946  *     Optional. Array or string of arguments for inserting a term.
1947  *
1948  *     @type string $alias_of    Slug of the term to make this term an alias of.
1949  *                               Default empty string. Accepts a term slug.
1950  *     @type string $description The term description. Default empty string.
1951  *     @type int    $parent      The id of the parent term. Default 0.
1952  *     @type string $slug        The term slug to use. Default empty string.
1953  * }
1954  * @return array|WP_Error An array containing the `term_id` and `term_taxonomy_id`,
1955  *                        WP_Error otherwise.
1956  */
1957 function wp_insert_term( $term, $taxonomy, $args = array() ) {
1958         global $wpdb;
1959
1960         if ( ! taxonomy_exists($taxonomy) ) {
1961                 return new WP_Error( 'invalid_taxonomy', __( 'Invalid taxonomy.' ) );
1962         }
1963         /**
1964          * Filters a term before it is sanitized and inserted into the database.
1965          *
1966          * @since 3.0.0
1967          *
1968          * @param string $term     The term to add or update.
1969          * @param string $taxonomy Taxonomy slug.
1970          */
1971         $term = apply_filters( 'pre_insert_term', $term, $taxonomy );
1972         if ( is_wp_error( $term ) ) {
1973                 return $term;
1974         }
1975         if ( is_int( $term ) && 0 == $term ) {
1976                 return new WP_Error( 'invalid_term_id', __( 'Invalid term ID.' ) );
1977         }
1978         if ( '' == trim( $term ) ) {
1979                 return new WP_Error( 'empty_term_name', __( 'A name is required for this term.' ) );
1980         }
1981         $defaults = array( 'alias_of' => '', 'description' => '', 'parent' => 0, 'slug' => '');
1982         $args = wp_parse_args( $args, $defaults );
1983
1984         if ( $args['parent'] > 0 && ! term_exists( (int) $args['parent'] ) ) {
1985                 return new WP_Error( 'missing_parent', __( 'Parent term does not exist.' ) );
1986         }
1987
1988         $args['name'] = $term;
1989         $args['taxonomy'] = $taxonomy;
1990
1991         // Coerce null description to strings, to avoid database errors.
1992         $args['description'] = (string) $args['description'];
1993
1994         $args = sanitize_term($args, $taxonomy, 'db');
1995
1996         // expected_slashed ($name)
1997         $name = wp_unslash( $args['name'] );
1998         $description = wp_unslash( $args['description'] );
1999         $parent = (int) $args['parent'];
2000
2001         $slug_provided = ! empty( $args['slug'] );
2002         if ( ! $slug_provided ) {
2003                 $slug = sanitize_title( $name );
2004         } else {
2005                 $slug = $args['slug'];
2006         }
2007
2008         $term_group = 0;
2009         if ( $args['alias_of'] ) {
2010                 $alias = get_term_by( 'slug', $args['alias_of'], $taxonomy );
2011                 if ( ! empty( $alias->term_group ) ) {
2012                         // The alias we want is already in a group, so let's use that one.
2013                         $term_group = $alias->term_group;
2014                 } elseif ( ! empty( $alias->term_id ) ) {
2015                         /*
2016                          * The alias is not in a group, so we create a new one
2017                          * and add the alias to it.
2018                          */
2019                         $term_group = $wpdb->get_var("SELECT MAX(term_group) FROM $wpdb->terms") + 1;
2020
2021                         wp_update_term( $alias->term_id, $taxonomy, array(
2022                                 'term_group' => $term_group,
2023                         ) );
2024                 }
2025         }
2026
2027         /*
2028          * Prevent the creation of terms with duplicate names at the same level of a taxonomy hierarchy,
2029          * unless a unique slug has been explicitly provided.
2030          */
2031         $name_matches = get_terms( $taxonomy, array(
2032                 'name' => $name,
2033                 'hide_empty' => false,
2034         ) );
2035
2036         /*
2037          * The `name` match in `get_terms()` doesn't differentiate accented characters,
2038          * so we do a stricter comparison here.
2039          */
2040         $name_match = null;
2041         if ( $name_matches ) {
2042                 foreach ( $name_matches as $_match ) {
2043                         if ( strtolower( $name ) === strtolower( $_match->name ) ) {
2044                                 $name_match = $_match;
2045                                 break;
2046                         }
2047                 }
2048         }
2049
2050         if ( $name_match ) {
2051                 $slug_match = get_term_by( 'slug', $slug, $taxonomy );
2052                 if ( ! $slug_provided || $name_match->slug === $slug || $slug_match ) {
2053                         if ( is_taxonomy_hierarchical( $taxonomy ) ) {
2054                                 $siblings = get_terms( $taxonomy, array( 'get' => 'all', 'parent' => $parent ) );
2055
2056                                 $existing_term = null;
2057                                 if ( $name_match->slug === $slug && in_array( $name, wp_list_pluck( $siblings, 'name' ) ) ) {
2058                                         $existing_term = $name_match;
2059                                 } elseif ( $slug_match && in_array( $slug, wp_list_pluck( $siblings, 'slug' ) ) ) {
2060                                         $existing_term = $slug_match;
2061                                 }
2062
2063                                 if ( $existing_term ) {
2064                                         return new WP_Error( 'term_exists', __( 'A term with the name provided already exists with this parent.' ), $existing_term->term_id );
2065                                 }
2066                         } else {
2067                                 return new WP_Error( 'term_exists', __( 'A term with the name provided already exists in this taxonomy.' ), $name_match->term_id );
2068                         }
2069                 }
2070         }
2071
2072         $slug = wp_unique_term_slug( $slug, (object) $args );
2073
2074         $data = compact( 'name', 'slug', 'term_group' );
2075
2076         /**
2077          * Filters term data before it is inserted into the database.
2078          *
2079          * @since 4.7.0
2080          *
2081          * @param array  $data     Term data to be inserted.
2082          * @param string $taxonomy Taxonomy slug.
2083          * @param array  $args     Arguments passed to wp_insert_term().
2084          */
2085         $data = apply_filters( 'wp_insert_term_data', $data, $taxonomy, $args );
2086
2087         if ( false === $wpdb->insert( $wpdb->terms, $data ) ) {
2088                 return new WP_Error( 'db_insert_error', __( 'Could not insert term into the database' ), $wpdb->last_error );
2089         }
2090
2091         $term_id = (int) $wpdb->insert_id;
2092
2093         // Seems unreachable, However, Is used in the case that a term name is provided, which sanitizes to an empty string.
2094         if ( empty($slug) ) {
2095                 $slug = sanitize_title($slug, $term_id);
2096
2097                 /** This action is documented in wp-includes/taxonomy.php */
2098                 do_action( 'edit_terms', $term_id, $taxonomy );
2099                 $wpdb->update( $wpdb->terms, compact( 'slug' ), compact( 'term_id' ) );
2100
2101                 /** This action is documented in wp-includes/taxonomy.php */
2102                 do_action( 'edited_terms', $term_id, $taxonomy );
2103         }
2104
2105         $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 ) );
2106
2107         if ( !empty($tt_id) ) {
2108                 return array('term_id' => $term_id, 'term_taxonomy_id' => $tt_id);
2109         }
2110         $wpdb->insert( $wpdb->term_taxonomy, compact( 'term_id', 'taxonomy', 'description', 'parent') + array( 'count' => 0 ) );
2111         $tt_id = (int) $wpdb->insert_id;
2112
2113         /*
2114          * Sanity check: if we just created a term with the same parent + taxonomy + slug but a higher term_id than
2115          * an existing term, then we have unwittingly created a duplicate term. Delete the dupe, and use the term_id
2116          * and term_taxonomy_id of the older term instead. Then return out of the function so that the "create" hooks
2117          * are not fired.
2118          */
2119         $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 ) );
2120         if ( $duplicate_term ) {
2121                 $wpdb->delete( $wpdb->terms, array( 'term_id' => $term_id ) );
2122                 $wpdb->delete( $wpdb->term_taxonomy, array( 'term_taxonomy_id' => $tt_id ) );
2123
2124                 $term_id = (int) $duplicate_term->term_id;
2125                 $tt_id   = (int) $duplicate_term->term_taxonomy_id;
2126
2127                 clean_term_cache( $term_id, $taxonomy );
2128                 return array( 'term_id' => $term_id, 'term_taxonomy_id' => $tt_id );
2129         }
2130
2131         /**
2132          * Fires immediately after a new term is created, before the term cache is cleaned.
2133          *
2134          * @since 2.3.0
2135          *
2136          * @param int    $term_id  Term ID.
2137          * @param int    $tt_id    Term taxonomy ID.
2138          * @param string $taxonomy Taxonomy slug.
2139          */
2140         do_action( "create_term", $term_id, $tt_id, $taxonomy );
2141
2142         /**
2143          * Fires after a new term is created for a specific taxonomy.
2144          *
2145          * The dynamic portion of the hook name, `$taxonomy`, refers
2146          * to the slug of the taxonomy the term was created for.
2147          *
2148          * @since 2.3.0
2149          *
2150          * @param int $term_id Term ID.
2151          * @param int $tt_id   Term taxonomy ID.
2152          */
2153         do_action( "create_{$taxonomy}", $term_id, $tt_id );
2154
2155         /**
2156          * Filters the term ID after a new term is created.
2157          *
2158          * @since 2.3.0
2159          *
2160          * @param int $term_id Term ID.
2161          * @param int $tt_id   Taxonomy term ID.
2162          */
2163         $term_id = apply_filters( 'term_id_filter', $term_id, $tt_id );
2164
2165         clean_term_cache($term_id, $taxonomy);
2166
2167         /**
2168          * Fires after a new term is created, and after the term cache has been cleaned.
2169          *
2170          * @since 2.3.0
2171          *
2172          * @param int    $term_id  Term ID.
2173          * @param int    $tt_id    Term taxonomy ID.
2174          * @param string $taxonomy Taxonomy slug.
2175          */
2176         do_action( 'created_term', $term_id, $tt_id, $taxonomy );
2177
2178         /**
2179          * Fires after a new term in a specific taxonomy is created, and after the term
2180          * cache has been cleaned.
2181          *
2182          * The dynamic portion of the hook name, `$taxonomy`, refers to the taxonomy slug.
2183          *
2184          * @since 2.3.0
2185          *
2186          * @param int $term_id Term ID.
2187          * @param int $tt_id   Term taxonomy ID.
2188          */
2189         do_action( "created_{$taxonomy}", $term_id, $tt_id );
2190
2191         return array('term_id' => $term_id, 'term_taxonomy_id' => $tt_id);
2192 }
2193
2194 /**
2195  * Create Term and Taxonomy Relationships.
2196  *
2197  * Relates an object (post, link etc) to a term and taxonomy type. Creates the
2198  * term and taxonomy relationship if it doesn't already exist. Creates a term if
2199  * it doesn't exist (using the slug).
2200  *
2201  * A relationship means that the term is grouped in or belongs to the taxonomy.
2202  * A term has no meaning until it is given context by defining which taxonomy it
2203  * exists under.
2204  *
2205  * @since 2.3.0
2206  *
2207  * @global wpdb $wpdb The WordPress database abstraction object.
2208  *
2209  * @param int              $object_id The object to relate to.
2210  * @param array|int|string $terms     A single term slug, single term id, or array of either term slugs or ids.
2211  *                                    Will replace all existing related terms in this taxonomy.
2212  * @param string           $taxonomy  The context in which to relate the term to the object.
2213  * @param bool             $append    Optional. If false will delete difference of terms. Default false.
2214  * @return array|WP_Error Term taxonomy IDs of the affected terms.
2215  */
2216 function wp_set_object_terms( $object_id, $terms, $taxonomy, $append = false ) {
2217         global $wpdb;
2218
2219         $object_id = (int) $object_id;
2220
2221         if ( ! taxonomy_exists( $taxonomy ) ) {
2222                 return new WP_Error( 'invalid_taxonomy', __( 'Invalid taxonomy.' ) );
2223         }
2224
2225         if ( !is_array($terms) )
2226                 $terms = array($terms);
2227
2228         if ( ! $append )
2229                 $old_tt_ids =  wp_get_object_terms($object_id, $taxonomy, array('fields' => 'tt_ids', 'orderby' => 'none'));
2230         else
2231                 $old_tt_ids = array();
2232
2233         $tt_ids = array();
2234         $term_ids = array();
2235         $new_tt_ids = array();
2236
2237         foreach ( (array) $terms as $term) {
2238                 if ( !strlen(trim($term)) )
2239                         continue;
2240
2241                 if ( !$term_info = term_exists($term, $taxonomy) ) {
2242                         // Skip if a non-existent term ID is passed.
2243                         if ( is_int($term) )
2244                                 continue;
2245                         $term_info = wp_insert_term($term, $taxonomy);
2246                 }
2247                 if ( is_wp_error($term_info) )
2248                         return $term_info;
2249                 $term_ids[] = $term_info['term_id'];
2250                 $tt_id = $term_info['term_taxonomy_id'];
2251                 $tt_ids[] = $tt_id;
2252
2253                 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 ) ) )
2254                         continue;
2255
2256                 /**
2257                  * Fires immediately before an object-term relationship is added.
2258                  *
2259                  * @since 2.9.0
2260                  * @since 4.7.0 Added the `$taxonomy` parameter.
2261                  *
2262                  * @param int    $object_id Object ID.
2263                  * @param int    $tt_id     Term taxonomy ID.
2264                  * @param string $taxonomy  Taxonomy slug.
2265                  */
2266                 do_action( 'add_term_relationship', $object_id, $tt_id, $taxonomy );
2267                 $wpdb->insert( $wpdb->term_relationships, array( 'object_id' => $object_id, 'term_taxonomy_id' => $tt_id ) );
2268
2269                 /**
2270                  * Fires immediately after an object-term relationship is added.
2271                  *
2272                  * @since 2.9.0
2273                  * @since 4.7.0 Added the `$taxonomy` parameter.
2274                  *
2275                  * @param int    $object_id Object ID.
2276                  * @param int    $tt_id     Term taxonomy ID.
2277                  * @param string $taxonomy  Taxonomy slug.
2278                  */
2279                 do_action( 'added_term_relationship', $object_id, $tt_id, $taxonomy );
2280                 $new_tt_ids[] = $tt_id;
2281         }
2282
2283         if ( $new_tt_ids )
2284                 wp_update_term_count( $new_tt_ids, $taxonomy );
2285
2286         if ( ! $append ) {
2287                 $delete_tt_ids = array_diff( $old_tt_ids, $tt_ids );
2288
2289                 if ( $delete_tt_ids ) {
2290                         $in_delete_tt_ids = "'" . implode( "', '", $delete_tt_ids ) . "'";
2291                         $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 ) );
2292                         $delete_term_ids = array_map( 'intval', $delete_term_ids );
2293
2294                         $remove = wp_remove_object_terms( $object_id, $delete_term_ids, $taxonomy );
2295                         if ( is_wp_error( $remove ) ) {
2296                                 return $remove;
2297                         }
2298                 }
2299         }
2300
2301         $t = get_taxonomy($taxonomy);
2302         if ( ! $append && isset($t->sort) && $t->sort ) {
2303                 $values = array();
2304                 $term_order = 0;
2305                 $final_tt_ids = wp_get_object_terms($object_id, $taxonomy, array('fields' => 'tt_ids'));
2306                 foreach ( $tt_ids as $tt_id )
2307                         if ( in_array($tt_id, $final_tt_ids) )
2308                                 $values[] = $wpdb->prepare( "(%d, %d, %d)", $object_id, $tt_id, ++$term_order);
2309                 if ( $values )
2310                         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)" ) )
2311                                 return new WP_Error( 'db_insert_error', __( 'Could not insert term relationship into the database' ), $wpdb->last_error );
2312         }
2313
2314         wp_cache_delete( $object_id, $taxonomy . '_relationships' );
2315
2316         /**
2317          * Fires after an object's terms have been set.
2318          *
2319          * @since 2.8.0
2320          *
2321          * @param int    $object_id  Object ID.
2322          * @param array  $terms      An array of object terms.
2323          * @param array  $tt_ids     An array of term taxonomy IDs.
2324          * @param string $taxonomy   Taxonomy slug.
2325          * @param bool   $append     Whether to append new terms to the old terms.
2326          * @param array  $old_tt_ids Old array of term taxonomy IDs.
2327          */
2328         do_action( 'set_object_terms', $object_id, $terms, $tt_ids, $taxonomy, $append, $old_tt_ids );
2329         return $tt_ids;
2330 }
2331
2332 /**
2333  * Add term(s) associated with a given object.
2334  *
2335  * @since 3.6.0
2336  *
2337  * @param int              $object_id The ID of the object to which the terms will be added.
2338  * @param array|int|string $terms     The slug(s) or ID(s) of the term(s) to add.
2339  * @param array|string     $taxonomy  Taxonomy name.
2340  * @return array|WP_Error Term taxonomy IDs of the affected terms.
2341  */
2342 function wp_add_object_terms( $object_id, $terms, $taxonomy ) {
2343         return wp_set_object_terms( $object_id, $terms, $taxonomy, true );
2344 }
2345
2346 /**
2347  * Remove term(s) associated with a given object.
2348  *
2349  * @since 3.6.0
2350  *
2351  * @global wpdb $wpdb WordPress database abstraction object.
2352  *
2353  * @param int              $object_id The ID of the object from which the terms will be removed.
2354  * @param array|int|string $terms     The slug(s) or ID(s) of the term(s) to remove.
2355  * @param array|string     $taxonomy  Taxonomy name.
2356  * @return bool|WP_Error True on success, false or WP_Error on failure.
2357  */
2358 function wp_remove_object_terms( $object_id, $terms, $taxonomy ) {
2359         global $wpdb;
2360
2361         $object_id = (int) $object_id;
2362
2363         if ( ! taxonomy_exists( $taxonomy ) ) {
2364                 return new WP_Error( 'invalid_taxonomy', __( 'Invalid taxonomy.' ) );
2365         }
2366
2367         if ( ! is_array( $terms ) ) {
2368                 $terms = array( $terms );
2369         }
2370
2371         $tt_ids = array();
2372
2373         foreach ( (array) $terms as $term ) {
2374                 if ( ! strlen( trim( $term ) ) ) {
2375                         continue;
2376                 }
2377
2378                 if ( ! $term_info = term_exists( $term, $taxonomy ) ) {
2379                         // Skip if a non-existent term ID is passed.
2380                         if ( is_int( $term ) ) {
2381                                 continue;
2382                         }
2383                 }
2384
2385                 if ( is_wp_error( $term_info ) ) {
2386                         return $term_info;
2387                 }
2388
2389                 $tt_ids[] = $term_info['term_taxonomy_id'];
2390         }
2391
2392         if ( $tt_ids ) {
2393                 $in_tt_ids = "'" . implode( "', '", $tt_ids ) . "'";
2394
2395                 /**
2396                  * Fires immediately before an object-term relationship is deleted.
2397                  *
2398                  * @since 2.9.0
2399                  * @since 4.7.0 Added the `$taxonomy` parameter.
2400                  *
2401                  * @param int   $object_id Object ID.
2402                  * @param array $tt_ids    An array of term taxonomy IDs.
2403                  * @param string $taxonomy  Taxonomy slug.
2404                  */
2405                 do_action( 'delete_term_relationships', $object_id, $tt_ids, $taxonomy );
2406                 $deleted = $wpdb->query( $wpdb->prepare( "DELETE FROM $wpdb->term_relationships WHERE object_id = %d AND term_taxonomy_id IN ($in_tt_ids)", $object_id ) );
2407
2408                 wp_cache_delete( $object_id, $taxonomy . '_relationships' );
2409
2410                 /**
2411                  * Fires immediately after an object-term relationship is deleted.
2412                  *
2413                  * @since 2.9.0
2414                  * @since 4.7.0 Added the `$taxonomy` parameter.
2415                  *
2416                  * @param int    $object_id Object ID.
2417                  * @param array  $tt_ids    An array of term taxonomy IDs.
2418                  * @param string $taxonomy  Taxonomy slug.
2419                  */
2420                 do_action( 'deleted_term_relationships', $object_id, $tt_ids, $taxonomy );
2421
2422                 wp_update_term_count( $tt_ids, $taxonomy );
2423
2424                 return (bool) $deleted;
2425         }
2426
2427         return false;
2428 }
2429
2430 /**
2431  * Will make slug unique, if it isn't already.
2432  *
2433  * The `$slug` has to be unique global to every taxonomy, meaning that one
2434  * taxonomy term can't have a matching slug with another taxonomy term. Each
2435  * slug has to be globally unique for every taxonomy.
2436  *
2437  * The way this works is that if the taxonomy that the term belongs to is
2438  * hierarchical and has a parent, it will append that parent to the $slug.
2439  *
2440  * If that still doesn't return an unique slug, then it try to append a number
2441  * until it finds a number that is truly unique.
2442  *
2443  * The only purpose for `$term` is for appending a parent, if one exists.
2444  *
2445  * @since 2.3.0
2446  *
2447  * @global wpdb $wpdb WordPress database abstraction object.
2448  *
2449  * @param string $slug The string that will be tried for a unique slug.
2450  * @param object $term The term object that the `$slug` will belong to.
2451  * @return string Will return a true unique slug.
2452  */
2453 function wp_unique_term_slug( $slug, $term ) {
2454         global $wpdb;
2455
2456         $needs_suffix = true;
2457         $original_slug = $slug;
2458
2459         // As of 4.1, duplicate slugs are allowed as long as they're in different taxonomies.
2460         if ( ! term_exists( $slug ) || get_option( 'db_version' ) >= 30133 && ! get_term_by( 'slug', $slug, $term->taxonomy ) ) {
2461                 $needs_suffix = false;
2462         }
2463
2464         /*
2465          * If the taxonomy supports hierarchy and the term has a parent, make the slug unique
2466          * by incorporating parent slugs.
2467          */
2468         $parent_suffix = '';
2469         if ( $needs_suffix && is_taxonomy_hierarchical( $term->taxonomy ) && ! empty( $term->parent ) ) {
2470                 $the_parent = $term->parent;
2471                 while ( ! empty($the_parent) ) {
2472                         $parent_term = get_term($the_parent, $term->taxonomy);
2473                         if ( is_wp_error($parent_term) || empty($parent_term) )
2474                                 break;
2475                         $parent_suffix .= '-' . $parent_term->slug;
2476                         if ( ! term_exists( $slug . $parent_suffix ) ) {
2477                                 break;
2478                         }
2479
2480                         if ( empty($parent_term->parent) )
2481                                 break;
2482                         $the_parent = $parent_term->parent;
2483                 }
2484         }
2485
2486         // If we didn't get a unique slug, try appending a number to make it unique.
2487
2488         /**
2489          * Filters whether the proposed unique term slug is bad.
2490          *
2491          * @since 4.3.0
2492          *
2493          * @param bool   $needs_suffix Whether the slug needs to be made unique with a suffix.
2494          * @param string $slug         The slug.
2495          * @param object $term         Term object.
2496          */
2497         if ( apply_filters( 'wp_unique_term_slug_is_bad_slug', $needs_suffix, $slug, $term ) ) {
2498                 if ( $parent_suffix ) {
2499                         $slug .= $parent_suffix;
2500                 } else {
2501                         if ( ! empty( $term->term_id ) )
2502                                 $query = $wpdb->prepare( "SELECT slug FROM $wpdb->terms WHERE slug = %s AND term_id != %d", $slug, $term->term_id );
2503                         else
2504                                 $query = $wpdb->prepare( "SELECT slug FROM $wpdb->terms WHERE slug = %s", $slug );
2505
2506                         if ( $wpdb->get_var( $query ) ) {
2507                                 $num = 2;
2508                                 do {
2509                                         $alt_slug = $slug . "-$num";
2510                                         $num++;
2511                                         $slug_check = $wpdb->get_var( $wpdb->prepare( "SELECT slug FROM $wpdb->terms WHERE slug = %s", $alt_slug ) );
2512                                 } while ( $slug_check );
2513                                 $slug = $alt_slug;
2514                         }
2515                 }
2516         }
2517
2518         /**
2519          * Filters the unique term slug.
2520          *
2521          * @since 4.3.0
2522          *
2523          * @param string $slug          Unique term slug.
2524          * @param object $term          Term object.
2525          * @param string $original_slug Slug originally passed to the function for testing.
2526          */
2527         return apply_filters( 'wp_unique_term_slug', $slug, $term, $original_slug );
2528 }
2529
2530 /**
2531  * Update term based on arguments provided.
2532  *
2533  * The $args will indiscriminately override all values with the same field name.
2534  * Care must be taken to not override important information need to update or
2535  * update will fail (or perhaps create a new term, neither would be acceptable).
2536  *
2537  * Defaults will set 'alias_of', 'description', 'parent', and 'slug' if not
2538  * defined in $args already.
2539  *
2540  * 'alias_of' will create a term group, if it doesn't already exist, and update
2541  * it for the $term.
2542  *
2543  * If the 'slug' argument in $args is missing, then the 'name' in $args will be
2544  * used. It should also be noted that if you set 'slug' and it isn't unique then
2545  * a WP_Error will be passed back. If you don't pass any slug, then a unique one
2546  * will be created for you.
2547  *
2548  * For what can be overrode in `$args`, check the term scheme can contain and stay
2549  * away from the term keys.
2550  *
2551  * @since 2.3.0
2552  *
2553  * @global wpdb $wpdb WordPress database abstraction object.
2554  *
2555  * @param int          $term_id  The ID of the term
2556  * @param string       $taxonomy The context in which to relate the term to the object.
2557  * @param array|string $args     Optional. Array of get_terms() arguments. Default empty array.
2558  * @return array|WP_Error Returns Term ID and Taxonomy Term ID
2559  */
2560 function wp_update_term( $term_id, $taxonomy, $args = array() ) {
2561         global $wpdb;
2562
2563         if ( ! taxonomy_exists( $taxonomy ) ) {
2564                 return new WP_Error( 'invalid_taxonomy', __( 'Invalid taxonomy.' ) );
2565         }
2566
2567         $term_id = (int) $term_id;
2568
2569         // First, get all of the original args
2570         $term = get_term( $term_id, $taxonomy );
2571
2572         if ( is_wp_error( $term ) ) {
2573                 return $term;
2574         }
2575
2576         if ( ! $term ) {
2577                 return new WP_Error( 'invalid_term', __( 'Empty Term' ) );
2578         }
2579
2580         $term = (array) $term->data;
2581
2582         // Escape data pulled from DB.
2583         $term = wp_slash( $term );
2584
2585         // Merge old and new args with new args overwriting old ones.
2586         $args = array_merge($term, $args);
2587
2588         $defaults = array( 'alias_of' => '', 'description' => '', 'parent' => 0, 'slug' => '');
2589         $args = wp_parse_args($args, $defaults);
2590         $args = sanitize_term($args, $taxonomy, 'db');
2591         $parsed_args = $args;
2592
2593         // expected_slashed ($name)
2594         $name = wp_unslash( $args['name'] );
2595         $description = wp_unslash( $args['description'] );
2596
2597         $parsed_args['name'] = $name;
2598         $parsed_args['description'] = $description;
2599
2600         if ( '' == trim( $name ) ) {
2601                 return new WP_Error( 'empty_term_name', __( 'A name is required for this term.' ) );
2602         }
2603
2604         if ( $parsed_args['parent'] > 0 && ! term_exists( (int) $parsed_args['parent'] ) ) {
2605                 return new WP_Error( 'missing_parent', __( 'Parent term does not exist.' ) );
2606         }
2607
2608         $empty_slug = false;
2609         if ( empty( $args['slug'] ) ) {
2610                 $empty_slug = true;
2611                 $slug = sanitize_title($name);
2612         } else {
2613                 $slug = $args['slug'];
2614         }
2615
2616         $parsed_args['slug'] = $slug;
2617
2618         $term_group = isset( $parsed_args['term_group'] ) ? $parsed_args['term_group'] : 0;
2619         if ( $args['alias_of'] ) {
2620                 $alias = get_term_by( 'slug', $args['alias_of'], $taxonomy );
2621                 if ( ! empty( $alias->term_group ) ) {
2622                         // The alias we want is already in a group, so let's use that one.
2623                         $term_group = $alias->term_group;
2624                 } elseif ( ! empty( $alias->term_id ) ) {
2625                         /*
2626                          * The alias is not in a group, so we create a new one
2627                          * and add the alias to it.
2628                          */
2629                         $term_group = $wpdb->get_var("SELECT MAX(term_group) FROM $wpdb->terms") + 1;
2630
2631                         wp_update_term( $alias->term_id, $taxonomy, array(
2632                                 'term_group' => $term_group,
2633                         ) );
2634                 }
2635
2636                 $parsed_args['term_group'] = $term_group;
2637         }
2638
2639         /**
2640          * Filters the term parent.
2641          *
2642          * Hook to this filter to see if it will cause a hierarchy loop.
2643          *
2644          * @since 3.1.0
2645          *
2646          * @param int    $parent      ID of the parent term.
2647          * @param int    $term_id     Term ID.
2648          * @param string $taxonomy    Taxonomy slug.
2649          * @param array  $parsed_args An array of potentially altered update arguments for the given term.
2650          * @param array  $args        An array of update arguments for the given term.
2651          */
2652         $parent = apply_filters( 'wp_update_term_parent', $args['parent'], $term_id, $taxonomy, $parsed_args, $args );
2653
2654         // Check for duplicate slug
2655         $duplicate = get_term_by( 'slug', $slug, $taxonomy );
2656         if ( $duplicate && $duplicate->term_id != $term_id ) {
2657                 // If an empty slug was passed or the parent changed, reset the slug to something unique.
2658                 // Otherwise, bail.
2659                 if ( $empty_slug || ( $parent != $term['parent']) ) {
2660                         $slug = wp_unique_term_slug($slug, (object) $args);
2661                 } else {
2662                         /* translators: 1: Taxonomy term slug */
2663                         return new WP_Error('duplicate_term_slug', sprintf(__('The slug &#8220;%s&#8221; is already in use by another term'), $slug));
2664                 }
2665         }
2666
2667         $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) );
2668
2669         // Check whether this is a shared term that needs splitting.
2670         $_term_id = _split_shared_term( $term_id, $tt_id );
2671         if ( ! is_wp_error( $_term_id ) ) {
2672                 $term_id = $_term_id;
2673         }
2674
2675         /**
2676          * Fires immediately before the given terms are edited.
2677          *
2678          * @since 2.9.0
2679          *
2680          * @param int    $term_id  Term ID.
2681          * @param string $taxonomy Taxonomy slug.
2682          */
2683         do_action( 'edit_terms', $term_id, $taxonomy );
2684
2685         $data = compact( 'name', 'slug', 'term_group' );
2686
2687         /**
2688          * Filters term data before it is updated in the database.
2689          *
2690          * @since 4.7.0
2691          *
2692          * @param array  $data     Term data to be updated.
2693          * @param int    $term_id  Term ID.
2694          * @param string $taxonomy Taxonomy slug.
2695          * @param array  $args     Arguments passed to wp_update_term().
2696          */
2697         $data = apply_filters( 'wp_update_term_data', $data, $term_id, $taxonomy, $args );
2698
2699         $wpdb->update( $wpdb->terms, $data, compact( 'term_id' ) );
2700         if ( empty($slug) ) {
2701                 $slug = sanitize_title($name, $term_id);
2702                 $wpdb->update( $wpdb->terms, compact( 'slug' ), compact( 'term_id' ) );
2703         }
2704
2705         /**
2706          * Fires immediately after the given terms are edited.
2707          *
2708          * @since 2.9.0
2709          *
2710          * @param int    $term_id  Term ID
2711          * @param string $taxonomy Taxonomy slug.
2712          */
2713         do_action( 'edited_terms', $term_id, $taxonomy );
2714
2715         /**
2716          * Fires immediate before a term-taxonomy relationship is updated.
2717          *
2718          * @since 2.9.0
2719          *
2720          * @param int    $tt_id    Term taxonomy ID.
2721          * @param string $taxonomy Taxonomy slug.
2722          */
2723         do_action( 'edit_term_taxonomy', $tt_id, $taxonomy );
2724
2725         $wpdb->update( $wpdb->term_taxonomy, compact( 'term_id', 'taxonomy', 'description', 'parent' ), array( 'term_taxonomy_id' => $tt_id ) );
2726
2727         /**
2728          * Fires immediately after a term-taxonomy relationship is updated.
2729          *
2730          * @since 2.9.0
2731          *
2732          * @param int    $tt_id    Term taxonomy ID.
2733          * @param string $taxonomy Taxonomy slug.
2734          */
2735         do_action( 'edited_term_taxonomy', $tt_id, $taxonomy );
2736
2737         /**
2738          * Fires after a term has been updated, but before the term cache has been cleaned.
2739          *
2740          * @since 2.3.0
2741          *
2742          * @param int    $term_id  Term ID.
2743          * @param int    $tt_id    Term taxonomy ID.
2744          * @param string $taxonomy Taxonomy slug.
2745          */
2746         do_action( "edit_term", $term_id, $tt_id, $taxonomy );
2747
2748         /**
2749          * Fires after a term in a specific taxonomy has been updated, but before the term
2750          * cache has been cleaned.
2751          *
2752          * The dynamic portion of the hook name, `$taxonomy`, refers to the taxonomy slug.
2753          *
2754          * @since 2.3.0
2755          *
2756          * @param int $term_id Term ID.
2757          * @param int $tt_id   Term taxonomy ID.
2758          */
2759         do_action( "edit_{$taxonomy}", $term_id, $tt_id );
2760
2761         /** This filter is documented in wp-includes/taxonomy.php */
2762         $term_id = apply_filters( 'term_id_filter', $term_id, $tt_id );
2763
2764         clean_term_cache($term_id, $taxonomy);
2765
2766         /**
2767          * Fires after a term has been updated, and the term cache has been cleaned.
2768          *
2769          * @since 2.3.0
2770          *
2771          * @param int    $term_id  Term ID.
2772          * @param int    $tt_id    Term taxonomy ID.
2773          * @param string $taxonomy Taxonomy slug.
2774          */
2775         do_action( "edited_term", $term_id, $tt_id, $taxonomy );
2776
2777         /**
2778          * Fires after a term for a specific taxonomy has been updated, and the term
2779          * cache has been cleaned.
2780          *
2781          * The dynamic portion of the hook name, `$taxonomy`, refers to the taxonomy slug.
2782          *
2783          * @since 2.3.0
2784          *
2785          * @param int $term_id Term ID.
2786          * @param int $tt_id   Term taxonomy ID.
2787          */
2788         do_action( "edited_{$taxonomy}", $term_id, $tt_id );
2789
2790         return array('term_id' => $term_id, 'term_taxonomy_id' => $tt_id);
2791 }
2792
2793 /**
2794  * Enable or disable term counting.
2795  *
2796  * @since 2.5.0
2797  *
2798  * @staticvar bool $_defer
2799  *
2800  * @param bool $defer Optional. Enable if true, disable if false.
2801  * @return bool Whether term counting is enabled or disabled.
2802  */
2803 function wp_defer_term_counting($defer=null) {
2804         static $_defer = false;
2805
2806         if ( is_bool($defer) ) {
2807                 $_defer = $defer;
2808                 // flush any deferred counts
2809                 if ( !$defer )
2810                         wp_update_term_count( null, null, true );
2811         }
2812
2813         return $_defer;
2814 }
2815
2816 /**
2817  * Updates the amount of terms in taxonomy.
2818  *
2819  * If there is a taxonomy callback applied, then it will be called for updating
2820  * the count.
2821  *
2822  * The default action is to count what the amount of terms have the relationship
2823  * of term ID. Once that is done, then update the database.
2824  *
2825  * @since 2.3.0
2826  *
2827  * @staticvar array $_deferred
2828  *
2829  * @param int|array $terms       The term_taxonomy_id of the terms.
2830  * @param string    $taxonomy    The context of the term.
2831  * @param bool      $do_deferred Whether to flush the deferred term counts too. Default false.
2832  * @return bool If no terms will return false, and if successful will return true.
2833  */
2834 function wp_update_term_count( $terms, $taxonomy, $do_deferred = false ) {
2835         static $_deferred = array();
2836
2837         if ( $do_deferred ) {
2838                 foreach ( (array) array_keys($_deferred) as $tax ) {
2839                         wp_update_term_count_now( $_deferred[$tax], $tax );
2840                         unset( $_deferred[$tax] );
2841                 }
2842         }
2843
2844         if ( empty($terms) )
2845                 return false;
2846
2847         if ( !is_array($terms) )
2848                 $terms = array($terms);
2849
2850         if ( wp_defer_term_counting() ) {
2851                 if ( !isset($_deferred[$taxonomy]) )
2852                         $_deferred[$taxonomy] = array();
2853                 $_deferred[$taxonomy] = array_unique( array_merge($_deferred[$taxonomy], $terms) );
2854                 return true;
2855         }
2856
2857         return wp_update_term_count_now( $terms, $taxonomy );
2858 }
2859
2860 /**
2861  * Perform term count update immediately.
2862  *
2863  * @since 2.5.0
2864  *
2865  * @param array  $terms    The term_taxonomy_id of terms to update.
2866  * @param string $taxonomy The context of the term.
2867  * @return true Always true when complete.
2868  */
2869 function wp_update_term_count_now( $terms, $taxonomy ) {
2870         $terms = array_map('intval', $terms);
2871
2872         $taxonomy = get_taxonomy($taxonomy);
2873         if ( !empty($taxonomy->update_count_callback) ) {
2874                 call_user_func($taxonomy->update_count_callback, $terms, $taxonomy);
2875         } else {
2876                 $object_types = (array) $taxonomy->object_type;
2877                 foreach ( $object_types as &$object_type ) {
2878                         if ( 0 === strpos( $object_type, 'attachment:' ) )
2879                                 list( $object_type ) = explode( ':', $object_type );
2880                 }
2881
2882                 if ( $object_types == array_filter( $object_types, 'post_type_exists' ) ) {
2883                         // Only post types are attached to this taxonomy
2884                         _update_post_term_count( $terms, $taxonomy );
2885                 } else {
2886                         // Default count updater
2887                         _update_generic_term_count( $terms, $taxonomy );
2888                 }
2889         }
2890
2891         clean_term_cache($terms, '', false);
2892
2893         return true;
2894 }
2895
2896 //
2897 // Cache
2898 //
2899
2900 /**
2901  * Removes the taxonomy relationship to terms from the cache.
2902  *
2903  * Will remove the entire taxonomy relationship containing term `$object_id`. The
2904  * term IDs have to exist within the taxonomy `$object_type` for the deletion to
2905  * take place.
2906  *
2907  * @since 2.3.0
2908  *
2909  * @global bool $_wp_suspend_cache_invalidation
2910  *
2911  * @see get_object_taxonomies() for more on $object_type.
2912  *
2913  * @param int|array    $object_ids  Single or list of term object ID(s).
2914  * @param array|string $object_type The taxonomy object type.
2915  */
2916 function clean_object_term_cache($object_ids, $object_type) {
2917         global $_wp_suspend_cache_invalidation;
2918
2919         if ( ! empty( $_wp_suspend_cache_invalidation ) ) {
2920                 return;
2921         }
2922
2923         if ( !is_array($object_ids) )
2924                 $object_ids = array($object_ids);
2925
2926         $taxonomies = get_object_taxonomies( $object_type );
2927
2928         foreach ( $object_ids as $id ) {
2929                 foreach ( $taxonomies as $taxonomy ) {
2930                         wp_cache_delete($id, "{$taxonomy}_relationships");
2931                 }
2932         }
2933
2934         /**
2935          * Fires after the object term cache has been cleaned.
2936          *
2937          * @since 2.5.0
2938          *
2939          * @param array  $object_ids An array of object IDs.
2940          * @param string $objet_type Object type.
2941          */
2942         do_action( 'clean_object_term_cache', $object_ids, $object_type );
2943 }
2944
2945 /**
2946  * Will remove all of the term ids from the cache.
2947  *
2948  * @since 2.3.0
2949  *
2950  * @global wpdb $wpdb WordPress database abstraction object.
2951  * @global bool $_wp_suspend_cache_invalidation
2952  *
2953  * @param int|array $ids            Single or list of Term IDs.
2954  * @param string    $taxonomy       Optional. Can be empty and will assume `tt_ids`, else will use for context.
2955  *                                  Default empty.
2956  * @param bool      $clean_taxonomy Optional. Whether to clean taxonomy wide caches (true), or just individual
2957  *                                  term object caches (false). Default true.
2958  */
2959 function clean_term_cache($ids, $taxonomy = '', $clean_taxonomy = true) {
2960         global $wpdb, $_wp_suspend_cache_invalidation;
2961
2962         if ( ! empty( $_wp_suspend_cache_invalidation ) ) {
2963                 return;
2964         }
2965
2966         if ( !is_array($ids) )
2967                 $ids = array($ids);
2968
2969         $taxonomies = array();
2970         // If no taxonomy, assume tt_ids.
2971         if ( empty($taxonomy) ) {
2972                 $tt_ids = array_map('intval', $ids);
2973                 $tt_ids = implode(', ', $tt_ids);
2974                 $terms = $wpdb->get_results("SELECT term_id, taxonomy FROM $wpdb->term_taxonomy WHERE term_taxonomy_id IN ($tt_ids)");
2975                 $ids = array();
2976                 foreach ( (array) $terms as $term ) {
2977                         $taxonomies[] = $term->taxonomy;
2978                         $ids[] = $term->term_id;
2979                         wp_cache_delete( $term->term_id, 'terms' );
2980                 }
2981                 $taxonomies = array_unique($taxonomies);
2982         } else {
2983                 $taxonomies = array($taxonomy);
2984                 foreach ( $taxonomies as $taxonomy ) {
2985                         foreach ( $ids as $id ) {
2986                                 wp_cache_delete( $id, 'terms' );
2987                         }
2988                 }
2989         }
2990
2991         foreach ( $taxonomies as $taxonomy ) {
2992                 if ( $clean_taxonomy ) {
2993                         wp_cache_delete('all_ids', $taxonomy);
2994                         wp_cache_delete('get', $taxonomy);
2995                         delete_option("{$taxonomy}_children");
2996                         // Regenerate {$taxonomy}_children
2997                         _get_term_hierarchy($taxonomy);
2998                 }
2999
3000                 /**
3001                  * Fires once after each taxonomy's term cache has been cleaned.
3002                  *
3003                  * @since 2.5.0
3004                  * @since 4.5.0 Added the `$clean_taxonomy` parameter.
3005                  *
3006                  * @param array  $ids            An array of term IDs.
3007                  * @param string $taxonomy       Taxonomy slug.
3008                  * @param bool   $clean_taxonomy Whether or not to clean taxonomy-wide caches
3009                  */
3010                 do_action( 'clean_term_cache', $ids, $taxonomy, $clean_taxonomy );
3011         }
3012
3013         wp_cache_set( 'last_changed', microtime(), 'terms' );
3014 }
3015
3016 /**
3017  * Retrieves the taxonomy relationship to the term object id.
3018  *
3019  * Upstream functions (like get_the_terms() and is_object_in_term()) are
3020  * responsible for populating the object-term relationship cache. The current
3021  * function only fetches relationship data that is already in the cache.
3022  *
3023  * @since 2.3.0
3024  * @since 4.7.0 Returns a WP_Error object if get_term() returns an error for
3025  *              any of the matched terms.
3026  *
3027  * @param int    $id       Term object ID.
3028  * @param string $taxonomy Taxonomy name.
3029  * @return bool|array|WP_Error Array of `WP_Term` objects, if cached.
3030  *                             False if cache is empty for `$taxonomy` and `$id`.
3031  *                             WP_Error if get_term() returns an error object for any term.
3032  */
3033 function get_object_term_cache( $id, $taxonomy ) {
3034         $_term_ids = wp_cache_get( $id, "{$taxonomy}_relationships" );
3035
3036         // We leave the priming of relationship caches to upstream functions.
3037         if ( false === $_term_ids ) {
3038                 return false;
3039         }
3040
3041         // Backward compatibility for if a plugin is putting objects into the cache, rather than IDs.
3042         $term_ids = array();
3043         foreach ( $_term_ids as $term_id ) {
3044                 if ( is_numeric( $term_id ) ) {
3045                         $term_ids[] = intval( $term_id );
3046                 } elseif ( isset( $term_id->term_id ) ) {
3047                         $term_ids[] = intval( $term_id->term_id );
3048                 }
3049         }
3050
3051         // Fill the term objects.
3052         _prime_term_caches( $term_ids );
3053
3054         $terms = array();
3055         foreach ( $term_ids as $term_id ) {
3056                 $term = get_term( $term_id, $taxonomy );
3057                 if ( is_wp_error( $term ) ) {
3058                         return $term;
3059                 }
3060
3061                 $terms[] = $term;
3062         }
3063
3064         return $terms;
3065 }
3066
3067 /**
3068  * Updates the cache for the given term object ID(s).
3069  *
3070  * Note: Due to performance concerns, great care should be taken to only update
3071  * term caches when necessary. Processing time can increase exponentially depending
3072  * on both the number of passed term IDs and the number of taxonomies those terms
3073  * belong to.
3074  *
3075  * Caches will only be updated for terms not already cached.
3076  *
3077  * @since 2.3.0
3078  *
3079  * @param string|array $object_ids  Comma-separated list or array of term object IDs.
3080  * @param array|string $object_type The taxonomy object type.
3081  * @return void|false False if all of the terms in `$object_ids` are already cached.
3082  */
3083 function update_object_term_cache($object_ids, $object_type) {
3084         if ( empty($object_ids) )
3085                 return;
3086
3087         if ( !is_array($object_ids) )
3088                 $object_ids = explode(',', $object_ids);
3089
3090         $object_ids = array_map('intval', $object_ids);
3091
3092         $taxonomies = get_object_taxonomies($object_type);
3093
3094         $ids = array();
3095         foreach ( (array) $object_ids as $id ) {
3096                 foreach ( $taxonomies as $taxonomy ) {
3097                         if ( false === wp_cache_get($id, "{$taxonomy}_relationships") ) {
3098                                 $ids[] = $id;
3099                                 break;
3100                         }
3101                 }
3102         }
3103
3104         if ( empty( $ids ) )
3105                 return false;
3106
3107         $terms = wp_get_object_terms( $ids, $taxonomies, array(
3108                 'fields' => 'all_with_object_id',
3109                 'orderby' => 'name',
3110                 'update_term_meta_cache' => false,
3111         ) );
3112
3113         $object_terms = array();
3114         foreach ( (array) $terms as $term ) {
3115                 $object_terms[ $term->object_id ][ $term->taxonomy ][] = $term->term_id;
3116         }
3117
3118         foreach ( $ids as $id ) {
3119                 foreach ( $taxonomies as $taxonomy ) {
3120                         if ( ! isset($object_terms[$id][$taxonomy]) ) {
3121                                 if ( !isset($object_terms[$id]) )
3122                                         $object_terms[$id] = array();
3123                                 $object_terms[$id][$taxonomy] = array();
3124                         }
3125                 }
3126         }
3127
3128         foreach ( $object_terms as $id => $value ) {
3129                 foreach ( $value as $taxonomy => $terms ) {
3130                         wp_cache_add( $id, $terms, "{$taxonomy}_relationships" );
3131                 }
3132         }
3133 }
3134
3135 /**
3136  * Updates Terms to Taxonomy in cache.
3137  *
3138  * @since 2.3.0
3139  *
3140  * @param array  $terms    List of term objects to change.
3141  * @param string $taxonomy Optional. Update Term to this taxonomy in cache. Default empty.
3142  */
3143 function update_term_cache( $terms, $taxonomy = '' ) {
3144         foreach ( (array) $terms as $term ) {
3145                 // Create a copy in case the array was passed by reference.
3146                 $_term = clone $term;
3147
3148                 // Object ID should not be cached.
3149                 unset( $_term->object_id );
3150
3151                 wp_cache_add( $term->term_id, $_term, 'terms' );
3152         }
3153 }
3154
3155 //
3156 // Private
3157 //
3158
3159 /**
3160  * Retrieves children of taxonomy as Term IDs.
3161  *
3162  * @ignore
3163  * @since 2.3.0
3164  *
3165  * @param string $taxonomy Taxonomy name.
3166  * @return array Empty if $taxonomy isn't hierarchical or returns children as Term IDs.
3167  */
3168 function _get_term_hierarchy( $taxonomy ) {
3169         if ( !is_taxonomy_hierarchical($taxonomy) )
3170                 return array();
3171         $children = get_option("{$taxonomy}_children");
3172
3173         if ( is_array($children) )
3174                 return $children;
3175         $children = array();
3176         $terms = get_terms($taxonomy, array('get' => 'all', 'orderby' => 'id', 'fields' => 'id=>parent'));
3177         foreach ( $terms as $term_id => $parent ) {
3178                 if ( $parent > 0 )
3179                         $children[$parent][] = $term_id;
3180         }
3181         update_option("{$taxonomy}_children", $children);
3182
3183         return $children;
3184 }
3185
3186 /**
3187  * Get the subset of $terms that are descendants of $term_id.
3188  *
3189  * If `$terms` is an array of objects, then _get_term_children() returns an array of objects.
3190  * If `$terms` is an array of IDs, then _get_term_children() returns an array of IDs.
3191  *
3192  * @access private
3193  * @since 2.3.0
3194  *
3195  * @param int    $term_id   The ancestor term: all returned terms should be descendants of `$term_id`.
3196  * @param array  $terms     The set of terms - either an array of term objects or term IDs - from which those that
3197  *                          are descendants of $term_id will be chosen.
3198  * @param string $taxonomy  The taxonomy which determines the hierarchy of the terms.
3199  * @param array  $ancestors Optional. Term ancestors that have already been identified. Passed by reference, to keep
3200  *                          track of found terms when recursing the hierarchy. The array of located ancestors is used
3201  *                          to prevent infinite recursion loops. For performance, `term_ids` are used as array keys,
3202  *                          with 1 as value. Default empty array.
3203  * @return array|WP_Error The subset of $terms that are descendants of $term_id.
3204  */
3205 function _get_term_children( $term_id, $terms, $taxonomy, &$ancestors = array() ) {
3206         $empty_array = array();
3207         if ( empty($terms) )
3208                 return $empty_array;
3209
3210         $term_list = array();
3211         $has_children = _get_term_hierarchy($taxonomy);
3212
3213         if  ( ( 0 != $term_id ) && ! isset($has_children[$term_id]) )
3214                 return $empty_array;
3215
3216         // Include the term itself in the ancestors array, so we can properly detect when a loop has occurred.
3217         if ( empty( $ancestors ) ) {
3218                 $ancestors[ $term_id ] = 1;
3219         }
3220
3221         foreach ( (array) $terms as $term ) {
3222                 $use_id = false;
3223                 if ( !is_object($term) ) {
3224                         $term = get_term($term, $taxonomy);
3225                         if ( is_wp_error( $term ) )
3226                                 return $term;
3227                         $use_id = true;
3228                 }
3229
3230                 // Don't recurse if we've already identified the term as a child - this indicates a loop.
3231                 if ( isset( $ancestors[ $term->term_id ] ) ) {
3232                         continue;
3233                 }
3234
3235                 if ( $term->parent == $term_id ) {
3236                         if ( $use_id )
3237                                 $term_list[] = $term->term_id;
3238                         else
3239                                 $term_list[] = $term;
3240
3241                         if ( !isset($has_children[$term->term_id]) )
3242                                 continue;
3243
3244                         $ancestors[ $term->term_id ] = 1;
3245
3246                         if ( $children = _get_term_children( $term->term_id, $terms, $taxonomy, $ancestors) )
3247                                 $term_list = array_merge($term_list, $children);
3248                 }
3249         }
3250
3251         return $term_list;
3252 }
3253
3254 /**
3255  * Add count of children to parent count.
3256  *
3257  * Recalculates term counts by including items from child terms. Assumes all
3258  * relevant children are already in the $terms argument.
3259  *
3260  * @access private
3261  * @since 2.3.0
3262  *
3263  * @global wpdb $wpdb WordPress database abstraction object.
3264  *
3265  * @param array  $terms    List of term objects, passed by reference.
3266  * @param string $taxonomy Term context.
3267  */
3268 function _pad_term_counts( &$terms, $taxonomy ) {
3269         global $wpdb;
3270
3271         // This function only works for hierarchical taxonomies like post categories.
3272         if ( !is_taxonomy_hierarchical( $taxonomy ) )
3273                 return;
3274
3275         $term_hier = _get_term_hierarchy($taxonomy);
3276
3277         if ( empty($term_hier) )
3278                 return;
3279
3280         $term_items = array();
3281         $terms_by_id = array();
3282         $term_ids = array();
3283
3284         foreach ( (array) $terms as $key => $term ) {
3285                 $terms_by_id[$term->term_id] = & $terms[$key];
3286                 $term_ids[$term->term_taxonomy_id] = $term->term_id;
3287         }
3288
3289         // Get the object and term ids and stick them in a lookup table.
3290         $tax_obj = get_taxonomy($taxonomy);
3291         $object_types = esc_sql($tax_obj->object_type);
3292         $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'");
3293         foreach ( $results as $row ) {
3294                 $id = $term_ids[$row->term_taxonomy_id];
3295                 $term_items[$id][$row->object_id] = isset($term_items[$id][$row->object_id]) ? ++$term_items[$id][$row->object_id] : 1;
3296         }
3297
3298         // Touch every ancestor's lookup row for each post in each term.
3299         foreach ( $term_ids as $term_id ) {
3300                 $child = $term_id;
3301                 $ancestors = array();
3302                 while ( !empty( $terms_by_id[$child] ) && $parent = $terms_by_id[$child]->parent ) {
3303                         $ancestors[] = $child;
3304                         if ( !empty( $term_items[$term_id] ) )
3305                                 foreach ( $term_items[$term_id] as $item_id => $touches ) {
3306                                         $term_items[$parent][$item_id] = isset($term_items[$parent][$item_id]) ? ++$term_items[$parent][$item_id]: 1;
3307                                 }
3308                         $child = $parent;
3309
3310                         if ( in_array( $parent, $ancestors ) ) {
3311                                 break;
3312                         }
3313                 }
3314         }
3315
3316         // Transfer the touched cells.
3317         foreach ( (array) $term_items as $id => $items )
3318                 if ( isset($terms_by_id[$id]) )
3319                         $terms_by_id[$id]->count = count($items);
3320 }
3321
3322 /**
3323  * Adds any terms from the given IDs to the cache that do not already exist in cache.
3324  *
3325  * @since 4.6.0
3326  * @access private
3327  *
3328  * @global wpdb $wpdb WordPress database abstraction object.
3329  *
3330  * @param array $term_ids          Array of term IDs.
3331  * @param bool  $update_meta_cache Optional. Whether to update the meta cache. Default true.
3332  */
3333 function _prime_term_caches( $term_ids, $update_meta_cache = true ) {
3334         global $wpdb;
3335
3336         $non_cached_ids = _get_non_cached_ids( $term_ids, 'terms' );
3337         if ( ! empty( $non_cached_ids ) ) {
3338                 $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 ) ) ) );
3339
3340                 update_term_cache( $fresh_terms, $update_meta_cache );
3341
3342                 if ( $update_meta_cache ) {
3343                         update_termmeta_cache( $non_cached_ids );
3344                 }
3345         }
3346 }
3347
3348 //
3349 // Default callbacks
3350 //
3351
3352 /**
3353  * Will update term count based on object types of the current taxonomy.
3354  *
3355  * Private function for the default callback for post_tag and category
3356  * taxonomies.
3357  *
3358  * @access private
3359  * @since 2.3.0
3360  *
3361  * @global wpdb $wpdb WordPress database abstraction object.
3362  *
3363  * @param array  $terms    List of Term taxonomy IDs.
3364  * @param object $taxonomy Current taxonomy object of terms.
3365  */
3366 function _update_post_term_count( $terms, $taxonomy ) {
3367         global $wpdb;
3368
3369         $object_types = (array) $taxonomy->object_type;
3370
3371         foreach ( $object_types as &$object_type )
3372                 list( $object_type ) = explode( ':', $object_type );
3373
3374         $object_types = array_unique( $object_types );
3375
3376         if ( false !== ( $check_attachments = array_search( 'attachment', $object_types ) ) ) {
3377                 unset( $object_types[ $check_attachments ] );
3378                 $check_attachments = true;
3379         }
3380
3381         if ( $object_types )
3382                 $object_types = esc_sql( array_filter( $object_types, 'post_type_exists' ) );
3383
3384         foreach ( (array) $terms as $term ) {
3385                 $count = 0;
3386
3387                 // Attachments can be 'inherit' status, we need to base count off the parent's status if so.
3388                 if ( $check_attachments )
3389                         $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 ) );
3390
3391                 if ( $object_types )
3392                         $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 ) );
3393
3394                 /** This action is documented in wp-includes/taxonomy.php */
3395                 do_action( 'edit_term_taxonomy', $term, $taxonomy->name );
3396                 $wpdb->update( $wpdb->term_taxonomy, compact( 'count' ), array( 'term_taxonomy_id' => $term ) );
3397
3398                 /** This action is documented in wp-includes/taxonomy.php */
3399                 do_action( 'edited_term_taxonomy', $term, $taxonomy->name );
3400         }
3401 }
3402
3403 /**
3404  * Will update term count based on number of objects.
3405  *
3406  * Default callback for the 'link_category' taxonomy.
3407  *
3408  * @since 3.3.0
3409  *
3410  * @global wpdb $wpdb WordPress database abstraction object.
3411  *
3412  * @param array  $terms    List of term taxonomy IDs.
3413  * @param object $taxonomy Current taxonomy object of terms.
3414  */
3415 function _update_generic_term_count( $terms, $taxonomy ) {
3416         global $wpdb;
3417
3418         foreach ( (array) $terms as $term ) {
3419                 $count = $wpdb->get_var( $wpdb->prepare( "SELECT COUNT(*) FROM $wpdb->term_relationships WHERE term_taxonomy_id = %d", $term ) );
3420
3421                 /** This action is documented in wp-includes/taxonomy.php */
3422                 do_action( 'edit_term_taxonomy', $term, $taxonomy->name );
3423                 $wpdb->update( $wpdb->term_taxonomy, compact( 'count' ), array( 'term_taxonomy_id' => $term ) );
3424
3425                 /** This action is documented in wp-includes/taxonomy.php */
3426                 do_action( 'edited_term_taxonomy', $term, $taxonomy->name );
3427         }
3428 }
3429
3430 /**
3431  * Create a new term for a term_taxonomy item that currently shares its term
3432  * with another term_taxonomy.
3433  *
3434  * @ignore
3435  * @since 4.2.0
3436  * @since 4.3.0 Introduced `$record` parameter. Also, `$term_id` and
3437  *              `$term_taxonomy_id` can now accept objects.
3438  *
3439  * @global wpdb $wpdb WordPress database abstraction object.
3440  *
3441  * @param int|object $term_id          ID of the shared term, or the shared term object.
3442  * @param int|object $term_taxonomy_id ID of the term_taxonomy item to receive a new term, or the term_taxonomy object
3443  *                                     (corresponding to a row from the term_taxonomy table).
3444  * @param bool       $record           Whether to record data about the split term in the options table. The recording
3445  *                                     process has the potential to be resource-intensive, so during batch operations
3446  *                                     it can be beneficial to skip inline recording and do it just once, after the
3447  *                                     batch is processed. Only set this to `false` if you know what you are doing.
3448  *                                     Default: true.
3449  * @return int|WP_Error When the current term does not need to be split (or cannot be split on the current
3450  *                      database schema), `$term_id` is returned. When the term is successfully split, the
3451  *                      new term_id is returned. A WP_Error is returned for miscellaneous errors.
3452  */
3453 function _split_shared_term( $term_id, $term_taxonomy_id, $record = true ) {
3454         global $wpdb;
3455
3456         if ( is_object( $term_id ) ) {
3457                 $shared_term = $term_id;
3458                 $term_id = intval( $shared_term->term_id );
3459         }
3460
3461         if ( is_object( $term_taxonomy_id ) ) {
3462                 $term_taxonomy = $term_taxonomy_id;
3463                 $term_taxonomy_id = intval( $term_taxonomy->term_taxonomy_id );
3464         }
3465
3466         // If there are no shared term_taxonomy rows, there's nothing to do here.
3467         $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 ) );
3468
3469         if ( ! $shared_tt_count ) {
3470                 return $term_id;
3471         }
3472
3473         /*
3474          * Verify that the term_taxonomy_id passed to the function is actually associated with the term_id.
3475          * If there's a mismatch, it may mean that the term is already split. Return the actual term_id from the db.
3476          */
3477         $check_term_id = $wpdb->get_var( $wpdb->prepare( "SELECT term_id FROM $wpdb->term_taxonomy WHERE term_taxonomy_id = %d", $term_taxonomy_id ) );
3478         if ( $check_term_id != $term_id ) {
3479                 return $check_term_id;
3480         }
3481
3482         // Pull up data about the currently shared slug, which we'll use to populate the new one.
3483         if ( empty( $shared_term ) ) {
3484                 $shared_term = $wpdb->get_row( $wpdb->prepare( "SELECT t.* FROM $wpdb->terms t WHERE t.term_id = %d", $term_id ) );
3485         }
3486
3487         $new_term_data = array(
3488                 'name' => $shared_term->name,
3489                 'slug' => $shared_term->slug,
3490                 'term_group' => $shared_term->term_group,
3491         );
3492
3493         if ( false === $wpdb->insert( $wpdb->terms, $new_term_data ) ) {
3494                 return new WP_Error( 'db_insert_error', __( 'Could not split shared term.' ), $wpdb->last_error );
3495         }
3496
3497         $new_term_id = (int) $wpdb->insert_id;
3498
3499         // Update the existing term_taxonomy to point to the newly created term.
3500         $wpdb->update( $wpdb->term_taxonomy,
3501                 array( 'term_id' => $new_term_id ),
3502                 array( 'term_taxonomy_id' => $term_taxonomy_id )
3503         );
3504
3505         // Reassign child terms to the new parent.
3506         if ( empty( $term_taxonomy ) ) {
3507                 $term_taxonomy = $wpdb->get_row( $wpdb->prepare( "SELECT * FROM $wpdb->term_taxonomy WHERE term_taxonomy_id = %d", $term_taxonomy_id ) );
3508         }
3509
3510         $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 ) );
3511         if ( ! empty( $children_tt_ids ) ) {
3512                 foreach ( $children_tt_ids as $child_tt_id ) {
3513                         $wpdb->update( $wpdb->term_taxonomy,
3514                                 array( 'parent' => $new_term_id ),
3515                                 array( 'term_taxonomy_id' => $child_tt_id )
3516                         );
3517                         clean_term_cache( $term_id, $term_taxonomy->taxonomy );
3518                 }
3519         } else {
3520                 // If the term has no children, we must force its taxonomy cache to be rebuilt separately.
3521                 clean_term_cache( $new_term_id, $term_taxonomy->taxonomy );
3522         }
3523
3524         // Clean the cache for term taxonomies formerly shared with the current term.
3525         $shared_term_taxonomies = $wpdb->get_row( $wpdb->prepare( "SELECT taxonomy FROM $wpdb->term_taxonomy WHERE term_id = %d", $term_id ) );
3526         if ( $shared_term_taxonomies ) {
3527                 foreach ( $shared_term_taxonomies as $shared_term_taxonomy ) {
3528                         clean_term_cache( $term_id, $shared_term_taxonomy );
3529                 }
3530         }
3531
3532         // Keep a record of term_ids that have been split, keyed by old term_id. See wp_get_split_term().
3533         if ( $record ) {
3534                 $split_term_data = get_option( '_split_terms', array() );
3535                 if ( ! isset( $split_term_data[ $term_id ] ) ) {
3536                         $split_term_data[ $term_id ] = array();
3537                 }
3538
3539                 $split_term_data[ $term_id ][ $term_taxonomy->taxonomy ] = $new_term_id;
3540                 update_option( '_split_terms', $split_term_data );
3541         }
3542
3543         // If we've just split the final shared term, set the "finished" flag.
3544         $shared_terms_exist = $wpdb->get_results(
3545                 "SELECT tt.term_id, t.*, count(*) as term_tt_count FROM {$wpdb->term_taxonomy} tt
3546                  LEFT JOIN {$wpdb->terms} t ON t.term_id = tt.term_id
3547                  GROUP BY t.term_id
3548                  HAVING term_tt_count > 1
3549                  LIMIT 1"
3550         );
3551         if ( ! $shared_terms_exist ) {
3552                 update_option( 'finished_splitting_shared_terms', true );
3553         }
3554
3555         /**
3556          * Fires after a previously shared taxonomy term is split into two separate terms.
3557          *
3558          * @since 4.2.0
3559          *
3560          * @param int    $term_id          ID of the formerly shared term.
3561          * @param int    $new_term_id      ID of the new term created for the $term_taxonomy_id.
3562          * @param int    $term_taxonomy_id ID for the term_taxonomy row affected by the split.
3563          * @param string $taxonomy         Taxonomy for the split term.
3564          */
3565         do_action( 'split_shared_term', $term_id, $new_term_id, $term_taxonomy_id, $term_taxonomy->taxonomy );
3566
3567         return $new_term_id;
3568 }
3569
3570 /**
3571  * Splits a batch of shared taxonomy terms.
3572  *
3573  * @since 4.3.0
3574  *
3575  * @global wpdb $wpdb WordPress database abstraction object.
3576  */
3577 function _wp_batch_split_terms() {
3578         global $wpdb;
3579
3580         $lock_name = 'term_split.lock';
3581
3582         // Try to lock.
3583         $lock_result = $wpdb->query( $wpdb->prepare( "INSERT IGNORE INTO `$wpdb->options` ( `option_name`, `option_value`, `autoload` ) VALUES (%s, %s, 'no') /* LOCK */", $lock_name, time() ) );
3584
3585         if ( ! $lock_result ) {
3586                 $lock_result = get_option( $lock_name );
3587
3588                 // Bail if we were unable to create a lock, or if the existing lock is still valid.
3589                 if ( ! $lock_result || ( $lock_result > ( time() - HOUR_IN_SECONDS ) ) ) {
3590                         wp_schedule_single_event( time() + ( 5 * MINUTE_IN_SECONDS ), 'wp_split_shared_term_batch' );
3591                         return;
3592                 }
3593         }
3594
3595         // Update the lock, as by this point we've definitely got a lock, just need to fire the actions.
3596         update_option( $lock_name, time() );
3597
3598         // Get a list of shared terms (those with more than one associated row in term_taxonomy).
3599         $shared_terms = $wpdb->get_results(
3600                 "SELECT tt.term_id, t.*, count(*) as term_tt_count FROM {$wpdb->term_taxonomy} tt
3601                  LEFT JOIN {$wpdb->terms} t ON t.term_id = tt.term_id
3602                  GROUP BY t.term_id
3603                  HAVING term_tt_count > 1
3604                  LIMIT 10"
3605         );
3606
3607         // No more terms, we're done here.
3608         if ( ! $shared_terms ) {
3609                 update_option( 'finished_splitting_shared_terms', true );
3610                 delete_option( $lock_name );
3611                 return;
3612         }
3613
3614         // Shared terms found? We'll need to run this script again.
3615         wp_schedule_single_event( time() + ( 2 * MINUTE_IN_SECONDS ), 'wp_split_shared_term_batch' );
3616
3617         // Rekey shared term array for faster lookups.
3618         $_shared_terms = array();
3619         foreach ( $shared_terms as $shared_term ) {
3620                 $term_id = intval( $shared_term->term_id );
3621                 $_shared_terms[ $term_id ] = $shared_term;
3622         }
3623         $shared_terms = $_shared_terms;
3624
3625         // Get term taxonomy data for all shared terms.
3626         $shared_term_ids = implode( ',', array_keys( $shared_terms ) );
3627         $shared_tts = $wpdb->get_results( "SELECT * FROM {$wpdb->term_taxonomy} WHERE `term_id` IN ({$shared_term_ids})" );
3628
3629         // Split term data recording is slow, so we do it just once, outside the loop.
3630         $split_term_data = get_option( '_split_terms', array() );
3631         $skipped_first_term = $taxonomies = array();
3632         foreach ( $shared_tts as $shared_tt ) {
3633                 $term_id = intval( $shared_tt->term_id );
3634
3635                 // Don't split the first tt belonging to a given term_id.
3636                 if ( ! isset( $skipped_first_term[ $term_id ] ) ) {
3637                         $skipped_first_term[ $term_id ] = 1;
3638                         continue;
3639                 }
3640
3641                 if ( ! isset( $split_term_data[ $term_id ] ) ) {
3642                         $split_term_data[ $term_id ] = array();
3643                 }
3644
3645                 // Keep track of taxonomies whose hierarchies need flushing.
3646                 if ( ! isset( $taxonomies[ $shared_tt->taxonomy ] ) ) {
3647                         $taxonomies[ $shared_tt->taxonomy ] = 1;
3648                 }
3649
3650                 // Split the term.
3651                 $split_term_data[ $term_id ][ $shared_tt->taxonomy ] = _split_shared_term( $shared_terms[ $term_id ], $shared_tt, false );
3652         }
3653
3654         // Rebuild the cached hierarchy for each affected taxonomy.
3655         foreach ( array_keys( $taxonomies ) as $tax ) {
3656                 delete_option( "{$tax}_children" );
3657                 _get_term_hierarchy( $tax );
3658         }
3659
3660         update_option( '_split_terms', $split_term_data );
3661
3662         delete_option( $lock_name );
3663 }
3664
3665 /**
3666  * In order to avoid the _wp_batch_split_terms() job being accidentally removed,
3667  * check that it's still scheduled while we haven't finished splitting terms.
3668  *
3669  * @ignore
3670  * @since 4.3.0
3671  */
3672 function _wp_check_for_scheduled_split_terms() {
3673         if ( ! get_option( 'finished_splitting_shared_terms' ) && ! wp_next_scheduled( 'wp_split_shared_term_batch' ) ) {
3674                 wp_schedule_single_event( time() + MINUTE_IN_SECONDS, 'wp_split_shared_term_batch' );
3675         }
3676 }
3677
3678 /**
3679  * Check default categories when a term gets split to see if any of them need to be updated.
3680  *
3681  * @ignore
3682  * @since 4.2.0
3683  *
3684  * @param int    $term_id          ID of the formerly shared term.
3685  * @param int    $new_term_id      ID of the new term created for the $term_taxonomy_id.
3686  * @param int    $term_taxonomy_id ID for the term_taxonomy row affected by the split.
3687  * @param string $taxonomy         Taxonomy for the split term.
3688  */
3689 function _wp_check_split_default_terms( $term_id, $new_term_id, $term_taxonomy_id, $taxonomy ) {
3690         if ( 'category' != $taxonomy ) {
3691                 return;
3692         }
3693
3694         foreach ( array( 'default_category', 'default_link_category', 'default_email_category' ) as $option ) {
3695                 if ( $term_id == get_option( $option, -1 ) ) {
3696                         update_option( $option, $new_term_id );
3697                 }
3698         }
3699 }
3700
3701 /**
3702  * Check menu items when a term gets split to see if any of them need to be updated.
3703  *
3704  * @ignore
3705  * @since 4.2.0
3706  *
3707  * @global wpdb $wpdb WordPress database abstraction object.
3708  *
3709  * @param int    $term_id          ID of the formerly shared term.
3710  * @param int    $new_term_id      ID of the new term created for the $term_taxonomy_id.
3711  * @param int    $term_taxonomy_id ID for the term_taxonomy row affected by the split.
3712  * @param string $taxonomy         Taxonomy for the split term.
3713  */
3714 function _wp_check_split_terms_in_menus( $term_id, $new_term_id, $term_taxonomy_id, $taxonomy ) {
3715         global $wpdb;
3716         $post_ids = $wpdb->get_col( $wpdb->prepare(
3717                 "SELECT m1.post_id
3718                 FROM {$wpdb->postmeta} AS m1
3719                         INNER JOIN {$wpdb->postmeta} AS m2 ON ( m2.post_id = m1.post_id )
3720                         INNER JOIN {$wpdb->postmeta} AS m3 ON ( m3.post_id = m1.post_id )
3721                 WHERE ( m1.meta_key = '_menu_item_type' AND m1.meta_value = 'taxonomy' )
3722                         AND ( m2.meta_key = '_menu_item_object' AND m2.meta_value = '%s' )
3723                         AND ( m3.meta_key = '_menu_item_object_id' AND m3.meta_value = %d )",
3724                 $taxonomy,
3725                 $term_id
3726         ) );
3727
3728         if ( $post_ids ) {
3729                 foreach ( $post_ids as $post_id ) {
3730                         update_post_meta( $post_id, '_menu_item_object_id', $new_term_id, $term_id );
3731                 }
3732         }
3733 }
3734
3735 /**
3736  * If the term being split is a nav_menu, change associations.
3737  *
3738  * @ignore
3739  * @since 4.3.0
3740  *
3741  * @param int    $term_id          ID of the formerly shared term.
3742  * @param int    $new_term_id      ID of the new term created for the $term_taxonomy_id.
3743  * @param int    $term_taxonomy_id ID for the term_taxonomy row affected by the split.
3744  * @param string $taxonomy         Taxonomy for the split term.
3745  */
3746 function _wp_check_split_nav_menu_terms( $term_id, $new_term_id, $term_taxonomy_id, $taxonomy ) {
3747         if ( 'nav_menu' !== $taxonomy ) {
3748                 return;
3749         }
3750
3751         // Update menu locations.
3752         $locations = get_nav_menu_locations();
3753         foreach ( $locations as $location => $menu_id ) {
3754                 if ( $term_id == $menu_id ) {
3755                         $locations[ $location ] = $new_term_id;
3756                 }
3757         }
3758         set_theme_mod( 'nav_menu_locations', $locations );
3759 }
3760
3761 /**
3762  * Get data about terms that previously shared a single term_id, but have since been split.
3763  *
3764  * @since 4.2.0
3765  *
3766  * @param int $old_term_id Term ID. This is the old, pre-split term ID.
3767  * @return array Array of new term IDs, keyed by taxonomy.
3768  */
3769 function wp_get_split_terms( $old_term_id ) {
3770         $split_terms = get_option( '_split_terms', array() );
3771
3772         $terms = array();
3773         if ( isset( $split_terms[ $old_term_id ] ) ) {
3774                 $terms = $split_terms[ $old_term_id ];
3775         }
3776
3777         return $terms;
3778 }
3779
3780 /**
3781  * Get the new term ID corresponding to a previously split term.
3782  *
3783  * @since 4.2.0
3784  *
3785  * @param int    $old_term_id Term ID. This is the old, pre-split term ID.
3786  * @param string $taxonomy    Taxonomy that the term belongs to.
3787  * @return int|false If a previously split term is found corresponding to the old term_id and taxonomy,
3788  *                   the new term_id will be returned. If no previously split term is found matching
3789  *                   the parameters, returns false.
3790  */
3791 function wp_get_split_term( $old_term_id, $taxonomy ) {
3792         $split_terms = wp_get_split_terms( $old_term_id );
3793
3794         $term_id = false;
3795         if ( isset( $split_terms[ $taxonomy ] ) ) {
3796                 $term_id = (int) $split_terms[ $taxonomy ];
3797         }
3798
3799         return $term_id;
3800 }
3801
3802 /**
3803  * Determine whether a term is shared between multiple taxonomies.
3804  *
3805  * Shared taxonomy terms began to be split in 4.3, but failed cron tasks or other delays in upgrade routines may cause
3806  * shared terms to remain.
3807  *
3808  * @since 4.4.0
3809  *
3810  * @param int $term_id
3811  * @return bool
3812  */
3813 function wp_term_is_shared( $term_id ) {
3814         global $wpdb;
3815
3816         if ( get_option( 'finished_splitting_shared_terms' ) ) {
3817                 return false;
3818         }
3819
3820         $tt_count = $wpdb->get_var( $wpdb->prepare( "SELECT COUNT(*) FROM $wpdb->term_taxonomy WHERE term_id = %d", $term_id ) );
3821
3822         return $tt_count > 1;
3823 }
3824
3825 /**
3826  * Generate a permalink for a taxonomy term archive.
3827  *
3828  * @since 2.5.0
3829  *
3830  * @global WP_Rewrite $wp_rewrite
3831  *
3832  * @param object|int|string $term     The term object, ID, or slug whose link will be retrieved.
3833  * @param string            $taxonomy Optional. Taxonomy. Default empty.
3834  * @return string|WP_Error HTML link to taxonomy term archive on success, WP_Error if term does not exist.
3835  */
3836 function get_term_link( $term, $taxonomy = '' ) {
3837         global $wp_rewrite;
3838
3839         if ( !is_object($term) ) {
3840                 if ( is_int( $term ) ) {
3841                         $term = get_term( $term, $taxonomy );
3842                 } else {
3843                         $term = get_term_by( 'slug', $term, $taxonomy );
3844                 }
3845         }
3846
3847         if ( !is_object($term) )
3848                 $term = new WP_Error('invalid_term', __('Empty Term'));
3849
3850         if ( is_wp_error( $term ) )
3851                 return $term;
3852
3853         $taxonomy = $term->taxonomy;
3854
3855         $termlink = $wp_rewrite->get_extra_permastruct($taxonomy);
3856
3857         $slug = $term->slug;
3858         $t = get_taxonomy($taxonomy);
3859
3860         if ( empty($termlink) ) {
3861                 if ( 'category' == $taxonomy )
3862                         $termlink = '?cat=' . $term->term_id;
3863                 elseif ( $t->query_var )
3864                         $termlink = "?$t->query_var=$slug";
3865                 else
3866                         $termlink = "?taxonomy=$taxonomy&term=$slug";
3867                 $termlink = home_url($termlink);
3868         } else {
3869                 if ( $t->rewrite['hierarchical'] ) {
3870                         $hierarchical_slugs = array();
3871                         $ancestors = get_ancestors( $term->term_id, $taxonomy, 'taxonomy' );
3872                         foreach ( (array)$ancestors as $ancestor ) {
3873                                 $ancestor_term = get_term($ancestor, $taxonomy);
3874                                 $hierarchical_slugs[] = $ancestor_term->slug;
3875                         }
3876                         $hierarchical_slugs = array_reverse($hierarchical_slugs);
3877                         $hierarchical_slugs[] = $slug;
3878                         $termlink = str_replace("%$taxonomy%", implode('/', $hierarchical_slugs), $termlink);
3879                 } else {
3880                         $termlink = str_replace("%$taxonomy%", $slug, $termlink);
3881                 }
3882                 $termlink = home_url( user_trailingslashit($termlink, 'category') );
3883         }
3884         // Back Compat filters.
3885         if ( 'post_tag' == $taxonomy ) {
3886
3887                 /**
3888                  * Filters the tag link.
3889                  *
3890                  * @since 2.3.0
3891                  * @deprecated 2.5.0 Use 'term_link' instead.
3892                  *
3893                  * @param string $termlink Tag link URL.
3894                  * @param int    $term_id  Term ID.
3895                  */
3896                 $termlink = apply_filters( 'tag_link', $termlink, $term->term_id );
3897         } elseif ( 'category' == $taxonomy ) {
3898
3899                 /**
3900                  * Filters the category link.
3901                  *
3902                  * @since 1.5.0
3903                  * @deprecated 2.5.0 Use 'term_link' instead.
3904                  *
3905                  * @param string $termlink Category link URL.
3906                  * @param int    $term_id  Term ID.
3907                  */
3908                 $termlink = apply_filters( 'category_link', $termlink, $term->term_id );
3909         }
3910
3911         /**
3912          * Filters the term link.
3913          *
3914          * @since 2.5.0
3915          *
3916          * @param string $termlink Term link URL.
3917          * @param object $term     Term object.
3918          * @param string $taxonomy Taxonomy slug.
3919          */
3920         return apply_filters( 'term_link', $termlink, $term, $taxonomy );
3921 }
3922
3923 /**
3924  * Display the taxonomies of a post with available options.
3925  *
3926  * This function can be used within the loop to display the taxonomies for a
3927  * post without specifying the Post ID. You can also use it outside the Loop to
3928  * display the taxonomies for a specific post.
3929  *
3930  * @since 2.5.0
3931  *
3932  * @param array $args {
3933  *     Arguments about which post to use and how to format the output. Shares all of the arguments
3934  *     supported by get_the_taxonomies(), in addition to the following.
3935  *
3936  *     @type  int|WP_Post $post   Post ID or object to get taxonomies of. Default current post.
3937  *     @type  string      $before Displays before the taxonomies. Default empty string.
3938  *     @type  string      $sep    Separates each taxonomy. Default is a space.
3939  *     @type  string      $after  Displays after the taxonomies. Default empty string.
3940  * }
3941  */
3942 function the_taxonomies( $args = array() ) {
3943         $defaults = array(
3944                 'post' => 0,
3945                 'before' => '',
3946                 'sep' => ' ',
3947                 'after' => '',
3948         );
3949
3950         $r = wp_parse_args( $args, $defaults );
3951
3952         echo $r['before'] . join( $r['sep'], get_the_taxonomies( $r['post'], $r ) ) . $r['after'];
3953 }
3954
3955 /**
3956  * Retrieve all taxonomies associated with a post.
3957  *
3958  * This function can be used within the loop. It will also return an array of
3959  * the taxonomies with links to the taxonomy and name.
3960  *
3961  * @since 2.5.0
3962  *
3963  * @param int|WP_Post $post Optional. Post ID or WP_Post object. Default is global $post.
3964  * @param array $args {
3965  *     Optional. Arguments about how to format the list of taxonomies. Default empty array.
3966  *
3967  *     @type string $template      Template for displaying a taxonomy label and list of terms.
3968  *                                 Default is "Label: Terms."
3969  *     @type string $term_template Template for displaying a single term in the list. Default is the term name
3970  *                                 linked to its archive.
3971  * }
3972  * @return array List of taxonomies.
3973  */
3974 function get_the_taxonomies( $post = 0, $args = array() ) {
3975         $post = get_post( $post );
3976
3977         $args = wp_parse_args( $args, array(
3978                 /* translators: %s: taxonomy label, %l: list of terms formatted as per $term_template */
3979                 'template' => __( '%s: %l.' ),
3980                 'term_template' => '<a href="%1$s">%2$s</a>',
3981         ) );
3982
3983         $taxonomies = array();
3984
3985         if ( ! $post ) {
3986                 return $taxonomies;
3987         }
3988
3989         foreach ( get_object_taxonomies( $post ) as $taxonomy ) {
3990                 $t = (array) get_taxonomy( $taxonomy );
3991                 if ( empty( $t['label'] ) ) {
3992                         $t['label'] = $taxonomy;
3993                 }
3994                 if ( empty( $t['args'] ) ) {
3995                         $t['args'] = array();
3996                 }
3997                 if ( empty( $t['template'] ) ) {
3998                         $t['template'] = $args['template'];
3999                 }
4000                 if ( empty( $t['term_template'] ) ) {
4001                         $t['term_template'] = $args['term_template'];
4002                 }
4003
4004                 $terms = get_object_term_cache( $post->ID, $taxonomy );
4005                 if ( false === $terms ) {
4006                         $terms = wp_get_object_terms( $post->ID, $taxonomy, $t['args'] );
4007                 }
4008                 $links = array();
4009
4010                 foreach ( $terms as $term ) {
4011                         $links[] = wp_sprintf( $t['term_template'], esc_attr( get_term_link( $term ) ), $term->name );
4012                 }
4013                 if ( $links ) {
4014                         $taxonomies[$taxonomy] = wp_sprintf( $t['template'], $t['label'], $links, $terms );
4015                 }
4016         }
4017         return $taxonomies;
4018 }
4019
4020 /**
4021  * Retrieve all taxonomies of a post with just the names.
4022  *
4023  * @since 2.5.0
4024  *
4025  * @param int|WP_Post $post Optional. Post ID or WP_Post object. Default is global $post.
4026  * @return array
4027  */
4028 function get_post_taxonomies( $post = 0 ) {
4029         $post = get_post( $post );
4030
4031         return get_object_taxonomies($post);
4032 }
4033
4034 /**
4035  * Determine if the given object is associated with any of the given terms.
4036  *
4037  * The given terms are checked against the object's terms' term_ids, names and slugs.
4038  * Terms given as integers will only be checked against the object's terms' term_ids.
4039  * If no terms are given, determines if object is associated with any terms in the given taxonomy.
4040  *
4041  * @since 2.7.0
4042  *
4043  * @param int              $object_id ID of the object (post ID, link ID, ...).
4044  * @param string           $taxonomy  Single taxonomy name.
4045  * @param int|string|array $terms     Optional. Term term_id, name, slug or array of said. Default null.
4046  * @return bool|WP_Error WP_Error on input error.
4047  */
4048 function is_object_in_term( $object_id, $taxonomy, $terms = null ) {
4049         if ( !$object_id = (int) $object_id )
4050                 return new WP_Error( 'invalid_object', __( 'Invalid object ID' ) );
4051
4052         $object_terms = get_object_term_cache( $object_id, $taxonomy );
4053         if ( false === $object_terms ) {
4054                 $object_terms = wp_get_object_terms( $object_id, $taxonomy, array( 'update_term_meta_cache' => false ) );
4055                 if ( is_wp_error( $object_terms ) ) {
4056                         return $object_terms;
4057                 }
4058
4059                 wp_cache_set( $object_id, wp_list_pluck( $object_terms, 'term_id' ), "{$taxonomy}_relationships" );
4060         }
4061
4062         if ( is_wp_error( $object_terms ) )
4063                 return $object_terms;
4064         if ( empty( $object_terms ) )
4065                 return false;
4066         if ( empty( $terms ) )
4067                 return ( !empty( $object_terms ) );
4068
4069         $terms = (array) $terms;
4070
4071         if ( $ints = array_filter( $terms, 'is_int' ) )
4072                 $strs = array_diff( $terms, $ints );
4073         else
4074                 $strs =& $terms;
4075
4076         foreach ( $object_terms as $object_term ) {
4077                 // If term is an int, check against term_ids only.
4078                 if ( $ints && in_array( $object_term->term_id, $ints ) ) {
4079                         return true;
4080                 }
4081
4082                 if ( $strs ) {
4083                         // Only check numeric strings against term_id, to avoid false matches due to type juggling.
4084                         $numeric_strs = array_map( 'intval', array_filter( $strs, 'is_numeric' ) );
4085                         if ( in_array( $object_term->term_id, $numeric_strs, true ) ) {
4086                                 return true;
4087                         }
4088
4089                         if ( in_array( $object_term->name, $strs ) ) return true;
4090                         if ( in_array( $object_term->slug, $strs ) ) return true;
4091                 }
4092         }
4093
4094         return false;
4095 }
4096
4097 /**
4098  * Determine if the given object type is associated with the given taxonomy.
4099  *
4100  * @since 3.0.0
4101  *
4102  * @param string $object_type Object type string.
4103  * @param string $taxonomy    Single taxonomy name.
4104  * @return bool True if object is associated with the taxonomy, otherwise false.
4105  */
4106 function is_object_in_taxonomy( $object_type, $taxonomy ) {
4107         $taxonomies = get_object_taxonomies( $object_type );
4108         if ( empty( $taxonomies ) ) {
4109                 return false;
4110         }
4111         return in_array( $taxonomy, $taxonomies );
4112 }
4113
4114 /**
4115  * Get an array of ancestor IDs for a given object.
4116  *
4117  * @since 3.1.0
4118  * @since 4.1.0 Introduced the `$resource_type` argument.
4119  *
4120  * @param int    $object_id     Optional. The ID of the object. Default 0.
4121  * @param string $object_type   Optional. The type of object for which we'll be retrieving
4122  *                              ancestors. Accepts a post type or a taxonomy name. Default empty.
4123  * @param string $resource_type Optional. Type of resource $object_type is. Accepts 'post_type'
4124  *                              or 'taxonomy'. Default empty.
4125  * @return array An array of ancestors from lowest to highest in the hierarchy.
4126  */
4127 function get_ancestors( $object_id = 0, $object_type = '', $resource_type = '' ) {
4128         $object_id = (int) $object_id;
4129
4130         $ancestors = array();
4131
4132         if ( empty( $object_id ) ) {
4133
4134                 /** This filter is documented in wp-includes/taxonomy.php */
4135                 return apply_filters( 'get_ancestors', $ancestors, $object_id, $object_type, $resource_type );
4136         }
4137
4138         if ( ! $resource_type ) {
4139                 if ( is_taxonomy_hierarchical( $object_type ) ) {
4140                         $resource_type = 'taxonomy';
4141                 } elseif ( post_type_exists( $object_type ) ) {
4142                         $resource_type = 'post_type';
4143                 }
4144         }
4145
4146         if ( 'taxonomy' === $resource_type ) {
4147                 $term = get_term($object_id, $object_type);
4148                 while ( ! is_wp_error($term) && ! empty( $term->parent ) && ! in_array( $term->parent, $ancestors ) ) {
4149                         $ancestors[] = (int) $term->parent;
4150                         $term = get_term($term->parent, $object_type);
4151                 }
4152         } elseif ( 'post_type' === $resource_type ) {
4153                 $ancestors = get_post_ancestors($object_id);
4154         }
4155
4156         /**
4157          * Filters a given object's ancestors.
4158          *
4159          * @since 3.1.0
4160          * @since 4.1.1 Introduced the `$resource_type` parameter.
4161          *
4162          * @param array  $ancestors     An array of object ancestors.
4163          * @param int    $object_id     Object ID.
4164          * @param string $object_type   Type of object.
4165          * @param string $resource_type Type of resource $object_type is.
4166          */
4167         return apply_filters( 'get_ancestors', $ancestors, $object_id, $object_type, $resource_type );
4168 }
4169
4170 /**
4171  * Returns the term's parent's term_ID.
4172  *
4173  * @since 3.1.0
4174  *
4175  * @param int    $term_id  Term ID.
4176  * @param string $taxonomy Taxonomy name.
4177  * @return int|false False on error.
4178  */
4179 function wp_get_term_taxonomy_parent_id( $term_id, $taxonomy ) {
4180         $term = get_term( $term_id, $taxonomy );
4181         if ( ! $term || is_wp_error( $term ) ) {
4182                 return false;
4183         }
4184         return (int) $term->parent;
4185 }
4186
4187 /**
4188  * Checks the given subset of the term hierarchy for hierarchy loops.
4189  * Prevents loops from forming and breaks those that it finds.
4190  *
4191  * Attached to the {@see 'wp_update_term_parent'} filter.
4192  *
4193  * @since 3.1.0
4194  *
4195  * @param int    $parent   `term_id` of the parent for the term we're checking.
4196  * @param int    $term_id  The term we're checking.
4197  * @param string $taxonomy The taxonomy of the term we're checking.
4198  *
4199  * @return int The new parent for the term.
4200  */
4201 function wp_check_term_hierarchy_for_loops( $parent, $term_id, $taxonomy ) {
4202         // Nothing fancy here - bail
4203         if ( !$parent )
4204                 return 0;
4205
4206         // Can't be its own parent.
4207         if ( $parent == $term_id )
4208                 return 0;
4209
4210         // Now look for larger loops.
4211         if ( !$loop = wp_find_hierarchy_loop( 'wp_get_term_taxonomy_parent_id', $term_id, $parent, array( $taxonomy ) ) )
4212                 return $parent; // No loop
4213
4214         // Setting $parent to the given value causes a loop.
4215         if ( isset( $loop[$term_id] ) )
4216                 return 0;
4217
4218         // There's a loop, but it doesn't contain $term_id. Break the loop.
4219         foreach ( array_keys( $loop ) as $loop_member )
4220                 wp_update_term( $loop_member, $taxonomy, array( 'parent' => 0 ) );
4221
4222         return $parent;
4223 }