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