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