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