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