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