]> scripts.mit.edu Git - autoinstalls/wordpress.git/blob - wp-includes/taxonomy.php
Wordpress 2.7.1-scripts
[autoinstalls/wordpress.git] / wp-includes / taxonomy.php
1 <?php
2 /**
3  * Taxonomy API
4  *
5  * @package WordPress
6  * @subpackage Taxonomy
7  * @since 2.3.0
8  */
9
10 //
11 // Taxonomy Registration
12 //
13
14 /**
15  * Default Taxonomy Objects
16  * @since 2.3.0
17  * @global array $wp_taxonomies
18  */
19 $wp_taxonomies = array();
20 $wp_taxonomies['category'] = (object) array('name' => 'category', 'object_type' => 'post', 'hierarchical' => true, 'update_count_callback' => '_update_post_term_count');
21 $wp_taxonomies['post_tag'] = (object) array('name' => 'post_tag', 'object_type' => 'post', 'hierarchical' => false, 'update_count_callback' => '_update_post_term_count');
22 $wp_taxonomies['link_category'] = (object) array('name' => 'link_category', 'object_type' => 'link', 'hierarchical' => false);
23
24 /**
25  * Return all of the taxonomy names that are of $object_type.
26  *
27  * It appears that this function can be used to find all of the names inside of
28  * $wp_taxonomies global variable.
29  *
30  * <code><?php $taxonomies = get_object_taxonomies('post'); ?></code> Should
31  * result in <code>Array('category', 'post_tag')</code>
32  *
33  * @package WordPress
34  * @subpackage Taxonomy
35  * @since 2.3.0
36  *
37  * @uses $wp_taxonomies
38  *
39  * @param array|string|object $object Name of the type of taxonomy object, or an object (row from posts)
40  * @return array The names of all taxonomy of $object_type.
41  */
42 function get_object_taxonomies($object) {
43         global $wp_taxonomies;
44
45         if ( is_object($object) ) {
46                 if ( $object->post_type == 'attachment' )
47                         return get_attachment_taxonomies($object);
48                 $object = $object->post_type;
49         }
50
51         $object = (array) $object;
52
53         $taxonomies = array();
54         foreach ( (array) $wp_taxonomies as $taxonomy ) {
55                 if ( array_intersect($object, (array) $taxonomy->object_type) )
56                         $taxonomies[] = $taxonomy->name;
57         }
58
59         return $taxonomies;
60 }
61
62 /**
63  * Retrieves the taxonomy object of $taxonomy.
64  *
65  * The get_taxonomy function will first check that the parameter string given
66  * is a taxonomy object and if it is, it will return it.
67  *
68  * @package WordPress
69  * @subpackage Taxonomy
70  * @since 2.3.0
71  *
72  * @uses $wp_taxonomies
73  * @uses is_taxonomy() Checks whether taxonomy exists
74  *
75  * @param string $taxonomy Name of taxonomy object to return
76  * @return object|bool The Taxonomy Object or false if $taxonomy doesn't exist
77  */
78 function get_taxonomy( $taxonomy ) {
79         global $wp_taxonomies;
80
81         if ( ! is_taxonomy($taxonomy) )
82                 return false;
83
84         return $wp_taxonomies[$taxonomy];
85 }
86
87 /**
88  * Checks that the taxonomy name exists.
89  *
90  * @package WordPress
91  * @subpackage Taxonomy
92  * @since 2.3.0
93  *
94  * @uses $wp_taxonomies
95  *
96  * @param string $taxonomy Name of taxonomy object
97  * @return bool Whether the taxonomy exists or not.
98  */
99 function is_taxonomy( $taxonomy ) {
100         global $wp_taxonomies;
101
102         return isset($wp_taxonomies[$taxonomy]);
103 }
104
105 /**
106  * Whether the taxonomy object is hierarchical.
107  *
108  * Checks to make sure that the taxonomy is an object first. Then Gets the
109  * object, and finally returns the hierarchical value in the object.
110  *
111  * A false return value might also mean that the taxonomy does not exist.
112  *
113  * @package WordPress
114  * @subpackage Taxonomy
115  * @since 2.3.0
116  *
117  * @uses is_taxonomy() Checks whether taxonomy exists
118  * @uses get_taxonomy() Used to get the taxonomy object
119  *
120  * @param string $taxonomy Name of taxonomy object
121  * @return bool Whether the taxonomy is hierarchical
122  */
123 function is_taxonomy_hierarchical($taxonomy) {
124         if ( ! is_taxonomy($taxonomy) )
125                 return false;
126
127         $taxonomy = get_taxonomy($taxonomy);
128         return $taxonomy->hierarchical;
129 }
130
131 /**
132  * Create or modify a taxonomy object. Do not use before init.
133  *
134  * A simple function for creating or modifying a taxonomy object based on the
135  * parameters given. The function will accept an array (third optional
136  * parameter), along with strings for the taxonomy name and another string for
137  * the object type.
138  *
139  * Nothing is returned, so expect error maybe or use is_taxonomy() to check
140  * whether taxonomy exists.
141  *
142  * Optional $args contents:
143  *
144  * hierarachical - has some defined purpose at other parts of the API and is a
145  * boolean value.
146  *
147  * update_count_callback - works much like a hook, in that it will be called
148  * when the count is updated.
149  *
150  * rewrite - false to prevent rewrite, or array('slug'=>$slug) to customize
151  * permastruct; default will use $taxonomy as slug.
152  *
153  * query_var - false to prevent queries, or string to customize query var
154  * (?$query_var=$term); default will use $taxonomy as query var.
155  *
156  * @package WordPress
157  * @subpackage Taxonomy
158  * @since 2.3.0
159  * @uses $wp_taxonomies Inserts new taxonomy object into the list
160  * @uses $wp_rewrite Adds rewrite tags and permastructs
161  * @uses $wp Adds query vars
162  *
163  * @param string $taxonomy Name of taxonomy object
164  * @param array|string $object_type Name of the object type for the taxonomy object.
165  * @param array|string $args See above description for the two keys values.
166  */
167 function register_taxonomy( $taxonomy, $object_type, $args = array() ) {
168         global $wp_taxonomies, $wp_rewrite, $wp;
169
170         $defaults = array('hierarchical' => false, 'update_count_callback' => '', 'rewrite' => true, 'query_var' => true);
171         $args = wp_parse_args($args, $defaults);
172
173         if ( false !== $args['query_var'] && !empty($wp) ) {
174                 if ( true === $args['query_var'] )
175                         $args['query_var'] = $taxonomy;
176                 $args['query_var'] = sanitize_title_with_dashes($args['query_var']);
177                 $wp->add_query_var($args['query_var']);
178         }
179
180         if ( false !== $args['rewrite'] && !empty($wp_rewrite) ) {
181                 if ( !is_array($args['rewrite']) )
182                         $args['rewrite'] = array();
183                 if ( !isset($args['rewrite']['slug']) )
184                         $args['rewrite']['slug'] = sanitize_title_with_dashes($taxonomy);
185                 $wp_rewrite->add_rewrite_tag("%$taxonomy%", '([^/]+)', $args['query_var'] ? "{$args['query_var']}=" : "taxonomy=$taxonomy&term=$term");
186                 $wp_rewrite->add_permastruct($taxonomy, "{$args['rewrite']['slug']}/%$taxonomy%");
187         }
188
189         $args['name'] = $taxonomy;
190         $args['object_type'] = $object_type;
191         $wp_taxonomies[$taxonomy] = (object) $args;
192 }
193
194 //
195 // Term API
196 //
197
198 /**
199  * Retrieve object_ids of valid taxonomy and term.
200  *
201  * The strings of $taxonomies must exist before this function will continue. On
202  * failure of finding a valid taxonomy, it will return an WP_Error class, kind
203  * of like Exceptions in PHP 5, except you can't catch them. Even so, you can
204  * still test for the WP_Error class and get the error message.
205  *
206  * The $terms aren't checked the same as $taxonomies, but still need to exist
207  * for $object_ids to be returned.
208  *
209  * It is possible to change the order that object_ids is returned by either
210  * using PHP sort family functions or using the database by using $args with
211  * either ASC or DESC array. The value should be in the key named 'order'.
212  *
213  * @package WordPress
214  * @subpackage Taxonomy
215  * @since 2.3.0
216  *
217  * @uses $wpdb
218  * @uses wp_parse_args() Creates an array from string $args.
219  *
220  * @param string|array $terms String of term or array of string values of terms that will be used
221  * @param string|array $taxonomies String of taxonomy name or Array of string values of taxonomy names
222  * @param array|string $args Change the order of the object_ids, either ASC or DESC
223  * @return WP_Error|array If the taxonomy does not exist, then WP_Error will be returned. On success
224  *      the array can be empty meaning that there are no $object_ids found or it will return the $object_ids found.
225  */
226 function get_objects_in_term( $terms, $taxonomies, $args = array() ) {
227         global $wpdb;
228
229         if ( !is_array( $terms) )
230                 $terms = array($terms);
231
232         if ( !is_array($taxonomies) )
233                 $taxonomies = array($taxonomies);
234
235         foreach ( (array) $taxonomies as $taxonomy ) {
236                 if ( ! is_taxonomy($taxonomy) )
237                         return new WP_Error('invalid_taxonomy', __('Invalid Taxonomy'));
238         }
239
240         $defaults = array('order' => 'ASC');
241         $args = wp_parse_args( $args, $defaults );
242         extract($args, EXTR_SKIP);
243
244         $order = ( 'desc' == strtolower($order) ) ? 'DESC' : 'ASC';
245
246         $terms = array_map('intval', $terms);
247
248         $taxonomies = "'" . implode("', '", $taxonomies) . "'";
249         $terms = "'" . implode("', '", $terms) . "'";
250
251         $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 ($terms) ORDER BY tr.object_id $order");
252
253         if ( ! $object_ids )
254                 return array();
255
256         return $object_ids;
257 }
258
259 /**
260  * Get all Term data from database by Term ID.
261  *
262  * The usage of the get_term function is to apply filters to a term object. It
263  * is possible to get a term object from the database before applying the
264  * filters.
265  *
266  * $term ID must be part of $taxonomy, to get from the database. Failure, might
267  * be able to be captured by the hooks. Failure would be the same value as $wpdb
268  * returns for the get_row method.
269  *
270  * There are two hooks, one is specifically for each term, named 'get_term', and
271  * the second is for the taxonomy name, 'term_$taxonomy'. Both hooks gets the
272  * term object, and the taxonomy name as parameters. Both hooks are expected to
273  * return a Term object.
274  *
275  * 'get_term' hook - Takes two parameters the term Object and the taxonomy name.
276  * Must return term object. Used in get_term() as a catch-all filter for every
277  * $term.
278  *
279  * 'get_$taxonomy' hook - Takes two parameters the term Object and the taxonomy
280  * name. Must return term object. $taxonomy will be the taxonomy name, so for
281  * example, if 'category', it would be 'get_category' as the filter name. Useful
282  * for custom taxonomies or plugging into default taxonomies.
283  *
284  * @package WordPress
285  * @subpackage Taxonomy
286  * @since 2.3.0
287  *
288  * @uses $wpdb
289  * @uses sanitize_term() Cleanses the term based on $filter context before returning.
290  * @see sanitize_term_field() The $context param lists the available values for get_term_by() $filter param.
291  *
292  * @param int|object $term If integer, will get from database. If object will apply filters and return $term.
293  * @param string $taxonomy Taxonomy name that $term is part of.
294  * @param string $output Constant OBJECT, ARRAY_A, or ARRAY_N
295  * @param string $filter Optional, default is raw or no WordPress defined filter will applied.
296  * @return mixed|null|WP_Error Term Row from database. Will return null if $term is empty. If taxonomy does not
297  * exist then WP_Error will be returned.
298  */
299 function &get_term($term, $taxonomy, $output = OBJECT, $filter = 'raw') {
300         global $wpdb;
301
302         if ( empty($term) ) {
303                 $error = new WP_Error('invalid_term', __('Empty Term'));
304                 return $error;
305         }
306
307         if ( ! is_taxonomy($taxonomy) ) {
308                 $error = new WP_Error('invalid_taxonomy', __('Invalid Taxonomy'));
309                 return $error;
310         }
311
312         if ( is_object($term) && empty($term->filter) ) {
313                 wp_cache_add($term->term_id, $term, $taxonomy);
314                 $_term = $term;
315         } else {
316                 if ( is_object($term) )
317                         $term = $term->term_id;
318                 $term = (int) $term;
319                 if ( ! $_term = wp_cache_get($term, $taxonomy) ) {
320                         $_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) );
321                         wp_cache_add($term, $_term, $taxonomy);
322                 }
323         }
324
325         $_term = apply_filters('get_term', $_term, $taxonomy);
326         $_term = apply_filters("get_$taxonomy", $_term, $taxonomy);
327         $_term = sanitize_term($_term, $taxonomy, $filter);
328
329         if ( $output == OBJECT ) {
330                 return $_term;
331         } elseif ( $output == ARRAY_A ) {
332                 $__term = get_object_vars($_term);
333                 return $__term;
334         } elseif ( $output == ARRAY_N ) {
335                 $__term = array_values(get_object_vars($_term));
336                 return $__term;
337         } else {
338                 return $_term;
339         }
340 }
341
342 /**
343  * Get all Term data from database by Term field and data.
344  *
345  * Warning: $value is not escaped for 'name' $field. You must do it yourself, if
346  * required.
347  *
348  * The default $field is 'id', therefore it is possible to also use null for
349  * field, but not recommended that you do so.
350  *
351  * If $value does not exist, the return value will be false. If $taxonomy exists
352  * and $field and $value combinations exist, the Term will be returned.
353  *
354  * @package WordPress
355  * @subpackage Taxonomy
356  * @since 2.3.0
357  *
358  * @uses $wpdb
359  * @uses sanitize_term() Cleanses the term based on $filter context before returning.
360  * @see sanitize_term_field() The $context param lists the available values for get_term_by() $filter param.
361  *
362  * @param string $field Either 'slug', 'name', or 'id'
363  * @param string|int $value Search for this term value
364  * @param string $taxonomy Taxonomy Name
365  * @param string $output Constant OBJECT, ARRAY_A, or ARRAY_N
366  * @param string $filter Optional, default is raw or no WordPress defined filter will applied.
367  * @return mixed Term Row from database. Will return false if $taxonomy does not exist or $term was not found.
368  */
369 function get_term_by($field, $value, $taxonomy, $output = OBJECT, $filter = 'raw') {
370         global $wpdb;
371
372         if ( ! is_taxonomy($taxonomy) )
373                 return false;
374
375         if ( 'slug' == $field ) {
376                 $field = 't.slug';
377                 $value = sanitize_title($value);
378                 if ( empty($value) )
379                         return false;
380         } else if ( 'name' == $field ) {
381                 // Assume already escaped
382                 $value = stripslashes($value);
383                 $field = 't.name';
384         } else {
385                 $field = 't.term_id';
386                 $value = (int) $value;
387         }
388
389         $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) );
390         if ( !$term )
391                 return false;
392
393         wp_cache_add($term->term_id, $term, $taxonomy);
394
395         $term = sanitize_term($term, $taxonomy, $filter);
396
397         if ( $output == OBJECT ) {
398                 return $term;
399         } elseif ( $output == ARRAY_A ) {
400                 return get_object_vars($term);
401         } elseif ( $output == ARRAY_N ) {
402                 return array_values(get_object_vars($term));
403         } else {
404                 return $term;
405         }
406 }
407
408 /**
409  * Merge all term children into a single array.
410  *
411  * This recursive function will merge all of the children of $term into the same
412  * array. Only useful for taxonomies which are hierarchical.
413  *
414  * Will return an empty array if $term does not exist in $taxonomy.
415  *
416  * @package WordPress
417  * @subpackage Taxonomy
418  * @since 2.3.0
419  *
420  * @uses $wpdb
421  * @uses _get_term_hierarchy()
422  * @uses get_term_children() Used to get the children of both $taxonomy and the parent $term
423  *
424  * @param string $term Name of Term to get children
425  * @param string $taxonomy Taxonomy Name
426  * @return array|WP_Error List of Term Objects. WP_Error returned if $taxonomy does not exist
427  */
428 function get_term_children( $term, $taxonomy ) {
429         if ( ! is_taxonomy($taxonomy) )
430                 return new WP_Error('invalid_taxonomy', __('Invalid Taxonomy'));
431
432         $terms = _get_term_hierarchy($taxonomy);
433
434         if ( ! isset($terms[$term]) )
435                 return array();
436
437         $children = $terms[$term];
438
439         foreach ( (array) $terms[$term] as $child ) {
440                 if ( isset($terms[$child]) )
441                         $children = array_merge($children, get_term_children($child, $taxonomy));
442         }
443
444         return $children;
445 }
446
447 /**
448  * Get sanitized Term field.
449  *
450  * Does checks for $term, based on the $taxonomy. The function is for contextual
451  * reasons and for simplicity of usage. See sanitize_term_field() for more
452  * information.
453  *
454  * @package WordPress
455  * @subpackage Taxonomy
456  * @since 2.3.0
457  *
458  * @uses sanitize_term_field() Passes the return value in sanitize_term_field on success.
459  *
460  * @param string $field Term field to fetch
461  * @param int $term Term ID
462  * @param string $taxonomy Taxonomy Name
463  * @param string $context Optional, default is display. Look at sanitize_term_field() for available options.
464  * @return mixed Will return an empty string if $term is not an object or if $field is not set in $term.
465  */
466 function get_term_field( $field, $term, $taxonomy, $context = 'display' ) {
467         $term = (int) $term;
468         $term = get_term( $term, $taxonomy );
469         if ( is_wp_error($term) )
470                 return $term;
471
472         if ( !is_object($term) )
473                 return '';
474
475         if ( !isset($term->$field) )
476                 return '';
477
478         return sanitize_term_field($field, $term->$field, $term->term_id, $taxonomy, $context);
479 }
480
481 /**
482  * Sanitizes Term for editing.
483  *
484  * Return value is sanitize_term() and usage is for sanitizing the term for
485  * editing. Function is for contextual and simplicity.
486  *
487  * @package WordPress
488  * @subpackage Taxonomy
489  * @since 2.3.0
490  *
491  * @uses sanitize_term() Passes the return value on success
492  *
493  * @param int|object $id Term ID or Object
494  * @param string $taxonomy Taxonomy Name
495  * @return mixed|null|WP_Error Will return empty string if $term is not an object.
496  */
497 function get_term_to_edit( $id, $taxonomy ) {
498         $term = get_term( $id, $taxonomy );
499
500         if ( is_wp_error($term) )
501                 return $term;
502
503         if ( !is_object($term) )
504                 return '';
505
506         return sanitize_term($term, $taxonomy, 'edit');
507 }
508
509 /**
510  * Retrieve the terms in a given taxonomy or list of taxonomies.
511  *
512  * You can fully inject any customizations to the query before it is sent, as
513  * well as control the output with a filter.
514  *
515  * The 'get_terms' filter will be called when the cache has the term and will
516  * pass the found term along with the array of $taxonomies and array of $args.
517  * This filter is also called before the array of terms is passed and will pass
518  * the array of terms, along with the $taxonomies and $args.
519  *
520  * The 'list_terms_exclusions' filter passes the compiled exclusions along with
521  * the $args.
522  *
523  * The list of arguments that $args can contain, which will overwrite the defaults:
524  *
525  * orderby - Default is 'name'. Can be name, count, or nothing (will use
526  * term_id).
527  *
528  * order - Default is ASC. Can use DESC.
529  *
530  * hide_empty - Default is true. Will not return empty terms, which means
531  * terms whose count is 0 according to the given taxonomy.
532  *
533  * exclude - Default is an empty string.  A comma- or space-delimited string
534  * of term ids to exclude from the return array.  If 'include' is non-empty,
535  * 'exclude' is ignored.
536  *
537  * exclude_tree - A comma- or space-delimited string of term ids to exclude
538  * from the return array, along with all of their descendant terms according to 
539  * the primary taxonomy.  If 'include' is non-empty, 'exclude_tree' is ignored.
540  *
541  * include - Default is an empty string.  A comma- or space-delimited string
542  * of term ids to include in the return array.
543  *
544  * number - The maximum number of terms to return.  Default is empty.
545  *
546  * offset - The number by which to offset the terms query.
547  *
548  * fields - Default is 'all', which returns an array of term objects.
549  * If 'fields' is 'ids' or 'names', returns an array of
550  * integers or strings, respectively.
551  *
552  * slug - Returns terms whose "slug" matches this value. Default is empty string.
553  *
554  * hierarchical - Whether to include terms that have non-empty descendants
555  * (even if 'hide_empty' is set to true).
556  *
557  * search - Returned terms' names will contain the value of 'search',
558  * case-insensitive.  Default is an empty string.
559  *
560  * name__like - Returned terms' names will begin with the value of 'name__like',
561  * case-insensitive. Default is empty string.
562  *
563  * The argument 'pad_counts', if set to true will include the quantity of a term's
564  * children in the quantity of each term's "count" object variable.
565  *
566  * The 'get' argument, if set to 'all' instead of its default empty string,
567  * returns terms regardless of ancestry or whether the terms are empty.
568  *
569  * The 'child_of' argument, when used, should be set to the integer of a term ID.  Its default
570  * is 0.  If set to a non-zero value, all returned terms will be descendants
571  * of that term according to the given taxonomy.  Hence 'child_of' is set to 0
572  * if more than one taxonomy is passed in $taxonomies, because multiple taxonomies
573  * make term ancestry ambiguous.
574  *
575  * The 'parent' argument, when used, should be set to the integer of a term ID.  Its default is
576  * the empty string '', which has a different meaning from the integer 0.
577  * If set to an integer value, all returned terms will have as an immediate
578  * ancestor the term whose ID is specified by that integer according to the given taxonomy.
579  * The 'parent' argument is different from 'child_of' in that a term X is considered a 'parent'
580  * of term Y only if term X is the father of term Y, not its grandfather or great-grandfather, etc.
581  *
582  * @package WordPress
583  * @subpackage Taxonomy
584  * @since 2.3.0
585  *
586  * @uses $wpdb
587  * @uses wp_parse_args() Merges the defaults with those defined by $args and allows for strings.
588  *
589  * @param string|array Taxonomy name or list of Taxonomy names
590  * @param string|array $args The values of what to search for when returning terms
591  * @return array|WP_Error List of Term Objects and their children. Will return WP_Error, if any of $taxonomies do not exist.
592  */
593 function &get_terms($taxonomies, $args = '') {
594         global $wpdb;
595         $empty_array = array();
596
597         $single_taxonomy = false;
598         if ( !is_array($taxonomies) ) {
599                 $single_taxonomy = true;
600                 $taxonomies = array($taxonomies);
601         }
602
603         foreach ( (array) $taxonomies as $taxonomy ) {
604                 if ( ! is_taxonomy($taxonomy) )
605                         return new WP_Error('invalid_taxonomy', __('Invalid Taxonomy'));
606         }
607
608         $in_taxonomies = "'" . implode("', '", $taxonomies) . "'";
609
610         $defaults = array('orderby' => 'name', 'order' => 'ASC',
611                 'hide_empty' => true, 'exclude' => '', 'exclude_tree' => '', 'include' => '',
612                 'number' => '', 'fields' => 'all', 'slug' => '', 'parent' => '',
613                 'hierarchical' => true, 'child_of' => 0, 'get' => '', 'name__like' => '',
614                 'pad_counts' => false, 'offset' => '', 'search' => '');
615         $args = wp_parse_args( $args, $defaults );
616         $args['number'] = absint( $args['number'] );
617         $args['offset'] = absint( $args['offset'] );
618         if ( !$single_taxonomy || !is_taxonomy_hierarchical($taxonomies[0]) ||
619                 '' != $args['parent'] ) {
620                 $args['child_of'] = 0;
621                 $args['hierarchical'] = false;
622                 $args['pad_counts'] = false;
623         }
624
625         if ( 'all' == $args['get'] ) {
626                 $args['child_of'] = 0;
627                 $args['hide_empty'] = 0;
628                 $args['hierarchical'] = false;
629                 $args['pad_counts'] = false;
630         }
631         extract($args, EXTR_SKIP);
632
633         if ( $child_of ) {
634                 $hierarchy = _get_term_hierarchy($taxonomies[0]);
635                 if ( !isset($hierarchy[$child_of]) )
636                         return $empty_array;
637         }
638
639         if ( $parent ) {
640                 $hierarchy = _get_term_hierarchy($taxonomies[0]);
641                 if ( !isset($hierarchy[$parent]) )
642                         return $empty_array;
643         }
644
645         // $args can be whatever, only use the args defined in defaults to compute the key
646         $filter_key = ( has_filter('list_terms_exclusions') ) ? serialize($GLOBALS['wp_filter']['list_terms_exclusions']) : '';
647         $key = md5( serialize( compact(array_keys($defaults)) ) . serialize( $taxonomies ) . $filter_key );
648         $last_changed = wp_cache_get('last_changed', 'terms');
649         if ( !$last_changed ) {
650                 $last_changed = time();
651                 wp_cache_set('last_changed', $last_changed, 'terms');
652         }
653         $cache_key = "get_terms:$key:$last_changed";
654
655         if ( $cache = wp_cache_get( $cache_key, 'terms' ) ) {
656                 $terms = apply_filters('get_terms', $cache, $taxonomies, $args);
657                 return $terms;
658         }
659
660         if ( 'count' == $orderby )
661                 $orderby = 'tt.count';
662         else if ( 'name' == $orderby )
663                 $orderby = 't.name';
664         else if ( 'slug' == $orderby )
665                 $orderby = 't.slug';
666         else if ( 'term_group' == $orderby )
667                 $orderby = 't.term_group';
668         else
669                 $orderby = 't.term_id';
670
671         $where = '';
672         $inclusions = '';
673         if ( !empty($include) ) {
674                 $exclude = '';
675                 $exclude_tree = '';
676                 $interms = preg_split('/[\s,]+/',$include);
677                 if ( count($interms) ) {
678                         foreach ( (array) $interms as $interm ) {
679                                 if (empty($inclusions))
680                                         $inclusions = ' AND ( t.term_id = ' . intval($interm) . ' ';
681                                 else
682                                         $inclusions .= ' OR t.term_id = ' . intval($interm) . ' ';
683                         }
684                 }
685         }
686
687         if ( !empty($inclusions) )
688                 $inclusions .= ')';
689         $where .= $inclusions;
690
691         $exclusions = '';
692         if ( ! empty( $exclude_tree ) ) {
693                 $excluded_trunks = preg_split('/[\s,]+/',$exclude_tree);
694                 foreach( (array) $excluded_trunks as $extrunk ) {
695                         $excluded_children = (array) get_terms($taxonomies[0], array('child_of' => intval($extrunk), 'fields' => 'ids'));       
696                         $excluded_children[] = $extrunk;
697                         foreach( (array) $excluded_children as $exterm ) {
698                                 if ( empty($exclusions) )
699                                         $exclusions = ' AND ( t.term_id <> ' . intval($exterm) . ' ';
700                                 else
701                                         $exclusions .= ' AND t.term_id <> ' . intval($exterm) . ' ';
702
703                         }
704                 }
705         }
706         if ( !empty($exclude) ) {
707                 $exterms = preg_split('/[\s,]+/',$exclude);
708                 if ( count($exterms) ) {
709                         foreach ( (array) $exterms as $exterm ) {
710                                 if ( empty($exclusions) )
711                                         $exclusions = ' AND ( t.term_id <> ' . intval($exterm) . ' ';
712                                 else
713                                         $exclusions .= ' AND t.term_id <> ' . intval($exterm) . ' ';
714                         }
715                 }
716         }
717
718         if ( !empty($exclusions) )
719                 $exclusions .= ')';
720         $exclusions = apply_filters('list_terms_exclusions', $exclusions, $args );
721         $where .= $exclusions;
722
723         if ( !empty($slug) ) {
724                 $slug = sanitize_title($slug);
725                 $where .= " AND t.slug = '$slug'";
726         }
727
728         if ( !empty($name__like) )
729                 $where .= " AND t.name LIKE '{$name__like}%'";
730
731         if ( '' != $parent ) {
732                 $parent = (int) $parent;
733                 $where .= " AND tt.parent = '$parent'";
734         }
735
736         if ( $hide_empty && !$hierarchical )
737                 $where .= ' AND tt.count > 0';
738
739         // don't limit the query results when we have to descend the family tree 
740         if ( ! empty($number) && ! $hierarchical && empty( $child_of ) && '' == $parent ) {
741                 if( $offset )
742                         $limit = 'LIMIT ' . $offset . ',' . $number;
743                 else
744                         $limit = 'LIMIT ' . $number;
745
746         } else
747                 $limit = '';
748
749         if ( !empty($search) ) {
750                 $search = like_escape($search);
751                 $where .= " AND (t.name LIKE '%$search%')";
752         }
753
754         $select_this = '';
755         if ( 'all' == $fields )
756                 $select_this = 't.*, tt.*';
757         else if ( 'ids' == $fields )
758                 $select_this = 't.term_id, tt.parent, tt.count';
759         else if ( 'names' == $fields )
760                 $select_this = 't.term_id, tt.parent, tt.count, t.name';
761
762         $query = "SELECT $select_this FROM $wpdb->terms AS t INNER JOIN $wpdb->term_taxonomy AS tt ON t.term_id = tt.term_id WHERE tt.taxonomy IN ($in_taxonomies) $where ORDER BY $orderby $order $limit";
763
764         $terms = $wpdb->get_results($query);
765         if ( 'all' == $fields ) {
766                 update_term_cache($terms);
767         }
768
769         if ( empty($terms) ) {
770                 $cache[ $key ] = array();
771                 wp_cache_set( 'get_terms', $cache, 'terms' );
772                 $terms = apply_filters('get_terms', array(), $taxonomies, $args);
773                 return $terms;
774         }
775
776         if ( $child_of ) {
777                 $children = _get_term_hierarchy($taxonomies[0]);
778                 if ( ! empty($children) )
779                         $terms = & _get_term_children($child_of, $terms, $taxonomies[0]);
780         }
781
782         // Update term counts to include children.
783         if ( $pad_counts && 'all' == $fields )
784                 _pad_term_counts($terms, $taxonomies[0]);
785
786         // Make sure we show empty categories that have children.
787         if ( $hierarchical && $hide_empty && is_array($terms) ) {
788                 foreach ( $terms as $k => $term ) {
789                         if ( ! $term->count ) {
790                                 $children = _get_term_children($term->term_id, $terms, $taxonomies[0]);
791                                 if( is_array($children) )
792                                         foreach ( $children as $child )
793                                                 if ( $child->count )
794                                                         continue 2;
795
796                                 // It really is empty
797                                 unset($terms[$k]);
798                         }
799                 }
800         }
801         reset ( $terms );
802
803         $_terms = array();
804         if ( 'ids' == $fields ) {
805                 while ( $term = array_shift($terms) )
806                         $_terms[] = $term->term_id;
807                 $terms = $_terms;
808         } elseif ( 'names' == $fields ) {
809                 while ( $term = array_shift($terms) )
810                         $_terms[] = $term->name;
811                 $terms = $_terms;
812         }
813
814         if ( 0 < $number && intval(@count($terms)) > $number ) {
815                 $terms = array_slice($terms, $offset, $number);
816         }
817
818         wp_cache_add( $cache_key, $terms, 'terms' );
819
820         $terms = apply_filters('get_terms', $terms, $taxonomies, $args);
821         return $terms;
822 }
823
824 /**
825  * Check if Term exists.
826  *
827  * Returns the index of a defined term, or 0 (false) if the term doesn't exist.
828  *
829  * @package WordPress
830  * @subpackage Taxonomy
831  * @since 2.3.0
832  *
833  * @uses $wpdb
834  *
835  * @param int|string $term The term to check
836  * @param string $taxonomy The taxonomy name to use
837  * @return mixed Get the term id or Term Object, if exists.
838  */
839 function is_term($term, $taxonomy = '') {
840         global $wpdb;
841
842         $select = "SELECT term_id FROM $wpdb->terms as t WHERE ";
843         $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 ";
844
845         if ( is_int($term) ) {
846                 if ( 0 == $term )
847                         return 0;
848                 $where = 't.term_id = %d';
849                 if ( !empty($taxonomy) )
850                         return $wpdb->get_row( $wpdb->prepare( $tax_select . $where . " AND tt.taxonomy = %s", $term, $taxonomy ), ARRAY_A );
851                 else
852                         return $wpdb->get_var( $wpdb->prepare( $select . $where, $term ) );
853         }
854
855         if ( '' === $slug = sanitize_title($term) )
856                 return 0;
857
858         $where = 't.slug = %s';
859         $else_where = 't.name = %s';
860
861         if ( !empty($taxonomy) ) {
862                 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", $slug, $taxonomy), ARRAY_A) )
863                         return $result;
864
865                 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", $term, $taxonomy), ARRAY_A);
866         }
867
868         if ( $result = $wpdb->get_var( $wpdb->prepare("SELECT term_id FROM $wpdb->terms as t WHERE $where", $slug) ) )
869                 return $result;
870
871         return $wpdb->get_var( $wpdb->prepare("SELECT term_id FROM $wpdb->terms as t WHERE $else_where", $term) );
872 }
873
874 /**
875  * Sanitize Term all fields.
876  *
877  * Relys on sanitize_term_field() to sanitize the term. The difference is that
878  * this function will sanitize <strong>all</strong> fields. The context is based
879  * on sanitize_term_field().
880  *
881  * The $term is expected to be either an array or an object.
882  *
883  * @package WordPress
884  * @subpackage Taxonomy
885  * @since 2.3.0
886  *
887  * @uses sanitize_term_field Used to sanitize all fields in a term
888  *
889  * @param array|object $term The term to check
890  * @param string $taxonomy The taxonomy name to use
891  * @param string $context Default is 'display'.
892  * @return array|object Term with all fields sanitized
893  */
894 function sanitize_term($term, $taxonomy, $context = 'display') {
895
896         if ( 'raw' == $context )
897                 return $term;
898
899         $fields = array('term_id', 'name', 'description', 'slug', 'count', 'parent', 'term_group');
900
901         $do_object = false;
902         if ( is_object($term) )
903                 $do_object = true;
904
905         $term_id = $do_object ? $term->term_id : (isset($term['term_id']) ? $term['term_id'] : 0);
906
907         foreach ( (array) $fields as $field ) {
908                 if ( $do_object ) {
909                         if ( isset($term->$field) )
910                                 $term->$field = sanitize_term_field($field, $term->$field, $term_id, $taxonomy, $context);
911                 } else {
912                         if ( isset($term[$field]) )
913                                 $term[$field] = sanitize_term_field($field, $term[$field], $term_id, $taxonomy, $context);
914                 }
915         }
916
917         if ( $do_object )
918                 $term->filter = $context;
919         else
920                 $term['filter'] = $context;
921
922         return $term;
923 }
924
925 /**
926  * Cleanse the field value in the term based on the context.
927  *
928  * Passing a term field value through the function should be assumed to have
929  * cleansed the value for whatever context the term field is going to be used.
930  *
931  * If no context or an unsupported context is given, then default filters will
932  * be applied.
933  *
934  * There are enough filters for each context to support a custom filtering
935  * without creating your own filter function. Simply create a function that
936  * hooks into the filter you need.
937  *
938  * @package WordPress
939  * @subpackage Taxonomy
940  * @since 2.3.0
941  *
942  * @uses $wpdb
943  *
944  * @param string $field Term field to sanitize
945  * @param string $value Search for this term value
946  * @param int $term_id Term ID
947  * @param string $taxonomy Taxonomy Name
948  * @param string $context Either edit, db, display, attribute, or js.
949  * @return mixed sanitized field
950  */
951 function sanitize_term_field($field, $value, $term_id, $taxonomy, $context) {
952         if ( 'parent' == $field  || 'term_id' == $field || 'count' == $field || 'term_group' == $field ) {
953                 $value = (int) $value;
954                 if ( $value < 0 )
955                         $value = 0;
956         }
957
958         if ( 'raw' == $context )
959                 return $value;
960
961         if ( 'edit' == $context ) {
962                 $value = apply_filters("edit_term_$field", $value, $term_id, $taxonomy);
963                 $value = apply_filters("edit_${taxonomy}_$field", $value, $term_id);
964                 if ( 'description' == $field )
965                         $value = format_to_edit($value);
966                 else
967                         $value = attribute_escape($value);
968         } else if ( 'db' == $context ) {
969                 $value = apply_filters("pre_term_$field", $value, $taxonomy);
970                 $value = apply_filters("pre_${taxonomy}_$field", $value);
971                 // Back compat filters
972                 if ( 'slug' == $field )
973                         $value = apply_filters('pre_category_nicename', $value);
974
975         } else if ( 'rss' == $context ) {
976                 $value = apply_filters("term_${field}_rss", $value, $taxonomy);
977                 $value = apply_filters("${taxonomy}_${field}_rss", $value);
978         } else {
979                 // Use display filters by default.
980                 $value = apply_filters("term_$field", $value, $term_id, $taxonomy, $context);
981                 $value = apply_filters("${taxonomy}_$field", $value, $term_id, $context);
982         }
983
984         if ( 'attribute' == $context )
985                 $value = attribute_escape($value);
986         else if ( 'js' == $context )
987                 $value = js_escape($value);
988
989         return $value;
990 }
991
992 /**
993  * Count how many terms are in Taxonomy.
994  *
995  * Default $args is 'ignore_empty' which can be <code>'ignore_empty=true'</code>
996  * or <code>array('ignore_empty' => true);</code>.
997  *
998  * @package WordPress
999  * @subpackage Taxonomy
1000  * @since 2.3.0
1001  *
1002  * @uses $wpdb
1003  * @uses wp_parse_args() Turns strings into arrays and merges defaults into an array.
1004  *
1005  * @param string $taxonomy Taxonomy name
1006  * @param array|string $args Overwrite defaults
1007  * @return int How many terms are in $taxonomy
1008  */
1009 function wp_count_terms( $taxonomy, $args = array() ) {
1010         global $wpdb;
1011
1012         $defaults = array('ignore_empty' => false);
1013         $args = wp_parse_args($args, $defaults);
1014         extract($args, EXTR_SKIP);
1015
1016         $where = '';
1017         if ( $ignore_empty )
1018                 $where = 'AND count > 0';
1019
1020         return $wpdb->get_var( $wpdb->prepare("SELECT COUNT(*) FROM $wpdb->term_taxonomy WHERE taxonomy = %s $where", $taxonomy) );
1021 }
1022
1023 /**
1024  * Will unlink the term from the taxonomy.
1025  *
1026  * Will remove the term's relationship to the taxonomy, not the term or taxonomy
1027  * itself. The term and taxonomy will still exist. Will require the term's
1028  * object ID to perform the operation.
1029  *
1030  * @package WordPress
1031  * @subpackage Taxonomy
1032  * @since 2.3.0
1033  * @uses $wpdb
1034  *
1035  * @param int $object_id The term Object Id that refers to the term
1036  * @param string|array $taxonomy List of Taxonomy Names or single Taxonomy name.
1037  */
1038 function wp_delete_object_term_relationships( $object_id, $taxonomies ) {
1039         global $wpdb;
1040
1041         $object_id = (int) $object_id;
1042
1043         if ( !is_array($taxonomies) )
1044                 $taxonomies = array($taxonomies);
1045
1046         foreach ( (array) $taxonomies as $taxonomy ) {
1047                 $tt_ids = wp_get_object_terms($object_id, $taxonomy, 'fields=tt_ids');
1048                 $in_tt_ids = "'" . implode("', '", $tt_ids) . "'";
1049                 $wpdb->query( $wpdb->prepare("DELETE FROM $wpdb->term_relationships WHERE object_id = %d AND term_taxonomy_id IN ($in_tt_ids)", $object_id) );
1050                 wp_update_term_count($tt_ids, $taxonomy);
1051         }
1052 }
1053
1054 /**
1055  * Removes a term from the database.
1056  *
1057  * If the term is a parent of other terms, then the children will be updated to
1058  * that term's parent.
1059  *
1060  * The $args 'default' will only override the terms found, if there is only one
1061  * term found. Any other and the found terms are used.
1062  *
1063  * @package WordPress
1064  * @subpackage Taxonomy
1065  * @since 2.3.0
1066  *
1067  * @uses $wpdb
1068  * @uses do_action() Calls both 'delete_term' and 'delete_$taxonomy' action
1069  *      hooks, passing term object, term id. 'delete_term' gets an additional
1070  *      parameter with the $taxonomy parameter.
1071  *
1072  * @param int $term Term ID
1073  * @param string $taxonomy Taxonomy Name
1074  * @param array|string $args Optional. Change 'default' term id and override found term ids.
1075  * @return bool|WP_Error Returns false if not term; true if completes delete action.
1076  */
1077 function wp_delete_term( $term, $taxonomy, $args = array() ) {
1078         global $wpdb;
1079
1080         $term = (int) $term;
1081
1082         if ( ! $ids = is_term($term, $taxonomy) )
1083                 return false;
1084         if ( is_wp_error( $ids ) )
1085                 return $ids;
1086
1087         $tt_id = $ids['term_taxonomy_id'];
1088
1089         $defaults = array();
1090         $args = wp_parse_args($args, $defaults);
1091         extract($args, EXTR_SKIP);
1092
1093         if ( isset($default) ) {
1094                 $default = (int) $default;
1095                 if ( ! is_term($default, $taxonomy) )
1096                         unset($default);
1097         }
1098
1099         // Update children to point to new parent
1100         if ( is_taxonomy_hierarchical($taxonomy) ) {
1101                 $term_obj = get_term($term, $taxonomy);
1102                 if ( is_wp_error( $term_obj ) )
1103                         return $term_obj;
1104                 $parent = $term_obj->parent;
1105
1106                 $wpdb->update( $wpdb->term_taxonomy, compact( 'parent' ), array( 'parent' => $term_obj->term_id) + compact( 'taxonomy' ) );
1107         }
1108
1109         $objects = $wpdb->get_col( $wpdb->prepare( "SELECT object_id FROM $wpdb->term_relationships WHERE term_taxonomy_id = %d", $tt_id ) );
1110
1111         foreach ( (array) $objects as $object ) {
1112                 $terms = wp_get_object_terms($object, $taxonomy, 'fields=ids');
1113                 if ( 1 == count($terms) && isset($default) )
1114                         $terms = array($default);
1115                 else
1116                         $terms = array_diff($terms, array($term));
1117                 $terms = array_map('intval', $terms);
1118                 wp_set_object_terms($object, $terms, $taxonomy);
1119         }
1120
1121         $wpdb->query( $wpdb->prepare( "DELETE FROM $wpdb->term_taxonomy WHERE term_taxonomy_id = %d", $tt_id ) );
1122
1123         // Delete the term if no taxonomies use it.
1124         if ( !$wpdb->get_var( $wpdb->prepare( "SELECT COUNT(*) FROM $wpdb->term_taxonomy WHERE term_id = %d", $term) ) )
1125                 $wpdb->query( $wpdb->prepare( "DELETE FROM $wpdb->terms WHERE term_id = %d", $term) );
1126
1127         clean_term_cache($term, $taxonomy);
1128
1129         do_action('delete_term', $term, $tt_id, $taxonomy);
1130         do_action("delete_$taxonomy", $term, $tt_id);
1131
1132         return true;
1133 }
1134
1135 /**
1136  * Retrieves the terms associated with the given object(s), in the supplied taxonomies.
1137  *
1138  * The following information has to do the $args parameter and for what can be
1139  * contained in the string or array of that parameter, if it exists.
1140  *
1141  * The first argument is called, 'orderby' and has the default value of 'name'.
1142  * The other value that is supported is 'count'.
1143  *
1144  * The second argument is called, 'order' and has the default value of 'ASC'.
1145  * The only other value that will be acceptable is 'DESC'.
1146  *
1147  * The final argument supported is called, 'fields' and has the default value of
1148  * 'all'. There are multiple other options that can be used instead. Supported
1149  * values are as follows: 'all', 'ids', 'names', and finally
1150  * 'all_with_object_id'.
1151  *
1152  * The fields argument also decides what will be returned. If 'all' or
1153  * 'all_with_object_id' is choosen or the default kept intact, then all matching
1154  * terms objects will be returned. If either 'ids' or 'names' is used, then an
1155  * array of all matching term ids or term names will be returned respectively.
1156  *
1157  * @package WordPress
1158  * @subpackage Taxonomy
1159  * @since 2.3.0
1160  * @uses $wpdb
1161  *
1162  * @param int|array $object_id The id of the object(s) to retrieve.
1163  * @param string|array $taxonomies The taxonomies to retrieve terms from.
1164  * @param array|string $args Change what is returned
1165  * @return array|WP_Error The requested term data or empty array if no terms found. WP_Error if $taxonomy does not exist.
1166  */
1167 function wp_get_object_terms($object_ids, $taxonomies, $args = array()) {
1168         global $wpdb;
1169
1170         if ( !is_array($taxonomies) )
1171                 $taxonomies = array($taxonomies);
1172
1173         foreach ( (array) $taxonomies as $taxonomy ) {
1174                 if ( ! is_taxonomy($taxonomy) )
1175                         return new WP_Error('invalid_taxonomy', __('Invalid Taxonomy'));
1176         }
1177
1178         if ( !is_array($object_ids) )
1179                 $object_ids = array($object_ids);
1180         $object_ids = array_map('intval', $object_ids);
1181
1182         $defaults = array('orderby' => 'name', 'order' => 'ASC', 'fields' => 'all');
1183         $args = wp_parse_args( $args, $defaults );
1184
1185         $terms = array();
1186         if ( count($taxonomies) > 1 ) {
1187                 foreach ( $taxonomies as $index => $taxonomy ) {
1188                         $t = get_taxonomy($taxonomy);
1189                         if ( isset($t->args) && is_array($t->args) && $args != array_merge($args, $t->args) ) {
1190                                 unset($taxonomies[$index]);
1191                                 $terms = array_merge($terms, wp_get_object_terms($object_ids, $taxonomy, array_merge($args, $t->args)));
1192                         }
1193                 }
1194         } else {
1195                 $t = get_taxonomy($taxonomies[0]);
1196                 if ( isset($t->args) && is_array($t->args) )
1197                         $args = array_merge($args, $t->args);
1198         }
1199
1200         extract($args, EXTR_SKIP);
1201
1202         if ( 'count' == $orderby )
1203                 $orderby = 'tt.count';
1204         else if ( 'name' == $orderby )
1205                 $orderby = 't.name';
1206         else if ( 'slug' == $orderby )
1207                 $orderby = 't.slug';
1208         else if ( 'term_group' == $orderby )
1209                 $orderby = 't.term_group';
1210         else if ( 'term_order' == $orderby )
1211                 $orderby = 'tr.term_order';
1212         else
1213                 $orderby = 't.term_id';
1214
1215         $taxonomies = "'" . implode("', '", $taxonomies) . "'";
1216         $object_ids = implode(', ', $object_ids);
1217
1218         $select_this = '';
1219         if ( 'all' == $fields )
1220                 $select_this = 't.*, tt.*';
1221         else if ( 'ids' == $fields )
1222                 $select_this = 't.term_id';
1223         else if ( 'names' == $fields )
1224                 $select_this = 't.name';
1225         else if ( 'all_with_object_id' == $fields )
1226                 $select_this = 't.*, tt.*, tr.object_id';
1227
1228         $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) ORDER BY $orderby $order";
1229
1230         if ( 'all' == $fields || 'all_with_object_id' == $fields ) {
1231                 $terms = array_merge($terms, $wpdb->get_results($query));
1232                 update_term_cache($terms);
1233         } else if ( 'ids' == $fields || 'names' == $fields ) {
1234                 $terms = array_merge($terms, $wpdb->get_col($query));
1235         } else if ( 'tt_ids' == $fields ) {
1236                 $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) ORDER BY tr.term_taxonomy_id $order");
1237         }
1238
1239         if ( ! $terms )
1240                 return array();
1241
1242         return $terms;
1243 }
1244
1245 /**
1246  * Adds a new term to the database. Optionally marks it as an alias of an existing term.
1247  *
1248  * Error handling is assigned for the nonexistance of the $taxonomy and $term
1249  * parameters before inserting. If both the term id and taxonomy exist
1250  * previously, then an array will be returned that contains the term id and the
1251  * contents of what is returned. The keys of the array are 'term_id' and
1252  * 'term_taxonomy_id' containing numeric values.
1253  *
1254  * It is assumed that the term does not yet exist or the above will apply. The
1255  * term will be first added to the term table and then related to the taxonomy
1256  * if everything is well. If everything is correct, then several actions will be
1257  * run prior to a filter and then several actions will be run after the filter
1258  * is run.
1259  *
1260  * The arguments decide how the term is handled based on the $args parameter.
1261  * The following is a list of the available overrides and the defaults.
1262  *
1263  * 'alias_of'. There is no default, but if added, expected is the slug that the
1264  * term will be an alias of. Expected to be a string.
1265  *
1266  * 'description'. There is no default. If exists, will be added to the database
1267  * along with the term. Expected to be a string.
1268  *
1269  * 'parent'. Expected to be numeric and default is 0 (zero). Will assign value
1270  * of 'parent' to the term.
1271  *
1272  * 'slug'. Expected to be a string. There is no default.
1273  *
1274  * If 'slug' argument exists then the slug will be checked to see if it is not
1275  * a valid term. If that check succeeds (it is not a valid term), then it is
1276  * added and the term id is given. If it fails, then a check is made to whether
1277  * the taxonomy is hierarchical and the parent argument is not empty. If the
1278  * second check succeeds, the term will be inserted and the term id will be
1279  * given.
1280  *
1281  * @package WordPress
1282  * @subpackage Taxonomy
1283  * @since 2.3.0
1284  * @uses $wpdb
1285  *
1286  * @uses do_action() Calls 'create_term' hook with the term id and taxonomy id as parameters.
1287  * @uses do_action() Calls 'create_$taxonomy' hook with term id and taxonomy id as parameters.
1288  * @uses apply_filters() Calls 'term_id_filter' hook with term id and taxonomy id as parameters.
1289  * @uses do_action() Calls 'created_term' hook with the term id and taxonomy id as parameters.
1290  * @uses do_action() Calls 'created_$taxonomy' hook with term id and taxonomy id as parameters.
1291  *
1292  * @param int|string $term The term to add or update.
1293  * @param string $taxonomy The taxonomy to which to add the term
1294  * @param array|string $args Change the values of the inserted term
1295  * @return array|WP_Error The Term ID and Term Taxonomy ID
1296  */
1297 function wp_insert_term( $term, $taxonomy, $args = array() ) {
1298         global $wpdb;
1299
1300         if ( ! is_taxonomy($taxonomy) )
1301                 return new WP_Error('invalid_taxonomy', __('Invalid taxonomy'));
1302
1303         if ( is_int($term) && 0 == $term )
1304                 return new WP_Error('invalid_term_id', __('Invalid term ID'));
1305
1306         if ( '' == trim($term) )
1307                 return new WP_Error('empty_term_name', __('A name is required for this term'));
1308
1309         $defaults = array( 'alias_of' => '', 'description' => '', 'parent' => 0, 'slug' => '');
1310         $args = wp_parse_args($args, $defaults);
1311         $args['name'] = $term;
1312         $args['taxonomy'] = $taxonomy;
1313         $args = sanitize_term($args, $taxonomy, 'db');
1314         extract($args, EXTR_SKIP);
1315
1316         // expected_slashed ($name)
1317         $name = stripslashes($name);
1318         $description = stripslashes($description);
1319
1320         if ( empty($slug) )
1321                 $slug = sanitize_title($name);
1322
1323         $term_group = 0;
1324         if ( $alias_of ) {
1325                 $alias = $wpdb->get_row( $wpdb->prepare( "SELECT term_id, term_group FROM $wpdb->terms WHERE slug = %s", $alias_of) );
1326                 if ( $alias->term_group ) {
1327                         // The alias we want is already in a group, so let's use that one.
1328                         $term_group = $alias->term_group;
1329                 } else {
1330                         // The alias isn't in a group, so let's create a new one and firstly add the alias term to it.
1331                         $term_group = $wpdb->get_var("SELECT MAX(term_group) FROM $wpdb->terms") + 1;
1332                         $wpdb->query( $wpdb->prepare( "UPDATE $wpdb->terms SET term_group = %d WHERE term_id = %d", $term_group, $alias->term_id ) );
1333                 }
1334         }
1335
1336         if ( ! $term_id = is_term($slug) ) {
1337                 if ( false === $wpdb->insert( $wpdb->terms, compact( 'name', 'slug', 'term_group' ) ) )
1338                         return new WP_Error('db_insert_error', __('Could not insert term into the database'), $wpdb->last_error);
1339                 $term_id = (int) $wpdb->insert_id;
1340         } else if ( is_taxonomy_hierarchical($taxonomy) && !empty($parent) ) {
1341                 // If the taxonomy supports hierarchy and the term has a parent, make the slug unique
1342                 // by incorporating parent slugs.
1343                 $slug = wp_unique_term_slug($slug, (object) $args);
1344                 if ( false === $wpdb->insert( $wpdb->terms, compact( 'name', 'slug', 'term_group' ) ) )
1345                         return new WP_Error('db_insert_error', __('Could not insert term into the database'), $wpdb->last_error);
1346                 $term_id = (int) $wpdb->insert_id;
1347         }
1348
1349         if ( empty($slug) ) {
1350                 $slug = sanitize_title($slug, $term_id);
1351                 $wpdb->update( $wpdb->terms, compact( 'slug' ), compact( 'term_id' ) );
1352         }
1353
1354         $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 ) );
1355
1356         if ( !empty($tt_id) )
1357                 return array('term_id' => $term_id, 'term_taxonomy_id' => $tt_id);
1358
1359         $wpdb->insert( $wpdb->term_taxonomy, compact( 'term_id', 'taxonomy', 'description', 'parent') + array( 'count' => 0 ) );
1360         $tt_id = (int) $wpdb->insert_id;
1361
1362         do_action("create_term", $term_id, $tt_id);
1363         do_action("create_$taxonomy", $term_id, $tt_id);
1364
1365         $term_id = apply_filters('term_id_filter', $term_id, $tt_id);
1366
1367         clean_term_cache($term_id, $taxonomy);
1368
1369         do_action("created_term", $term_id, $tt_id);
1370         do_action("created_$taxonomy", $term_id, $tt_id);
1371
1372         return array('term_id' => $term_id, 'term_taxonomy_id' => $tt_id);
1373 }
1374
1375 /**
1376  * Create Term and Taxonomy Relationships.
1377  *
1378  * Relates an object (post, link etc) to a term and taxonomy type. Creates the
1379  * term and taxonomy relationship if it doesn't already exist. Creates a term if
1380  * it doesn't exist (using the slug).
1381  *
1382  * A relationship means that the term is grouped in or belongs to the taxonomy.
1383  * A term has no meaning until it is given context by defining which taxonomy it
1384  * exists under.
1385  *
1386  * @package WordPress
1387  * @subpackage Taxonomy
1388  * @since 2.3.0
1389  * @uses $wpdb
1390  *
1391  * @param int $object_id The object to relate to.
1392  * @param array|int|string $term The slug or id of the term.
1393  * @param array|string $taxonomy The context in which to relate the term to the object.
1394  * @param bool $append If false will delete difference of terms.
1395  * @return array|WP_Error Affected Term IDs
1396  */
1397 function wp_set_object_terms($object_id, $terms, $taxonomy, $append = false) {
1398         global $wpdb;
1399
1400         $object_id = (int) $object_id;
1401
1402         if ( ! is_taxonomy($taxonomy) )
1403                 return new WP_Error('invalid_taxonomy', __('Invalid Taxonomy'));
1404
1405         if ( !is_array($terms) )
1406                 $terms = array($terms);
1407
1408         if ( ! $append )
1409                 $old_tt_ids =  wp_get_object_terms($object_id, $taxonomy, 'fields=tt_ids');
1410
1411         $tt_ids = array();
1412         $term_ids = array();
1413
1414         foreach ( (array) $terms as $term) {
1415                 if ( !strlen(trim($term)) )
1416                         continue;
1417
1418                 if ( !$term_info = is_term($term, $taxonomy) )
1419                         $term_info = wp_insert_term($term, $taxonomy);
1420                 if ( is_wp_error($term_info) )
1421                         return $term_info;
1422                 $term_ids[] = $term_info['term_id'];
1423                 $tt_id = $term_info['term_taxonomy_id'];
1424                 $tt_ids[] = $tt_id;
1425
1426                 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 ) ) )
1427                         continue;
1428                 $wpdb->insert( $wpdb->term_relationships, array( 'object_id' => $object_id, 'term_taxonomy_id' => $tt_id ) );
1429         }
1430
1431         wp_update_term_count($tt_ids, $taxonomy);
1432
1433         if ( ! $append ) {
1434                 $delete_terms = array_diff($old_tt_ids, $tt_ids);
1435                 if ( $delete_terms ) {
1436                         $in_delete_terms = "'" . implode("', '", $delete_terms) . "'";
1437                         $wpdb->query( $wpdb->prepare("DELETE FROM $wpdb->term_relationships WHERE object_id = %d AND term_taxonomy_id IN ($in_delete_terms)", $object_id) );
1438                         wp_update_term_count($delete_terms, $taxonomy);
1439                 }
1440         }
1441
1442         $t = get_taxonomy($taxonomy);
1443         if ( ! $append && isset($t->sort) && $t->sort ) {
1444                 $values = array();
1445                 $term_order = 0;
1446                 $final_tt_ids = wp_get_object_terms($object_id, $taxonomy, 'fields=tt_ids');
1447                 foreach ( $tt_ids as $tt_id )
1448                         if ( in_array($tt_id, $final_tt_ids) )
1449                                 $values[] = $wpdb->prepare( "(%d, %d, %d)", $object_id, $tt_id, ++$term_order);
1450                 if ( $values )
1451                         $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)");
1452         }
1453
1454         return $tt_ids;
1455 }
1456
1457 /**
1458  * Will make slug unique, if it isn't already.
1459  *
1460  * The $slug has to be unique global to every taxonomy, meaning that one
1461  * taxonomy term can't have a matching slug with another taxonomy term. Each
1462  * slug has to be globally unique for every taxonomy.
1463  *
1464  * The way this works is that if the taxonomy that the term belongs to is
1465  * heirarchical and has a parent, it will append that parent to the $slug.
1466  *
1467  * If that still doesn't return an unique slug, then it try to append a number
1468  * until it finds a number that is truely unique.
1469  *
1470  * The only purpose for $term is for appending a parent, if one exists.
1471  *
1472  * @package WordPress
1473  * @subpackage Taxonomy
1474  * @since 2.3.0
1475  * @uses $wpdb
1476  *
1477  * @param string $slug The string that will be tried for a unique slug
1478  * @param object $term The term object that the $slug will belong too
1479  * @return string Will return a true unique slug.
1480  */
1481 function wp_unique_term_slug($slug, $term) {
1482         global $wpdb;
1483
1484         // If the taxonomy supports hierarchy and the term has a parent, make the slug unique
1485         // by incorporating parent slugs.
1486         if ( is_taxonomy_hierarchical($term->taxonomy) && !empty($term->parent) ) {
1487                 $the_parent = $term->parent;
1488                 while ( ! empty($the_parent) ) {
1489                         $parent_term = get_term($the_parent, $term->taxonomy);
1490                         if ( is_wp_error($parent_term) || empty($parent_term) )
1491                                 break;
1492                                 $slug .= '-' . $parent_term->slug;
1493                         if ( empty($parent_term->parent) )
1494                                 break;
1495                         $the_parent = $parent_term->parent;
1496                 }
1497         }
1498
1499         // If we didn't get a unique slug, try appending a number to make it unique.
1500         if ( !empty($args['term_id']) )
1501                 $query = $wpdb->prepare( "SELECT slug FROM $wpdb->terms WHERE slug = %s AND term_id != %d", $slug, $args['term_id'] );
1502         else
1503                 $query = $wpdb->prepare( "SELECT slug FROM $wpdb->terms WHERE slug = %s", $slug );
1504
1505         if ( $wpdb->get_var( $query ) ) {
1506                 $num = 2;
1507                 do {
1508                         $alt_slug = $slug . "-$num";
1509                         $num++;
1510                         $slug_check = $wpdb->get_var( $wpdb->prepare( "SELECT slug FROM $wpdb->terms WHERE slug = %s", $alt_slug ) );
1511                 } while ( $slug_check );
1512                 $slug = $alt_slug;
1513         }
1514
1515         return $slug;
1516 }
1517
1518 /**
1519  * Update term based on arguments provided.
1520  *
1521  * The $args will indiscriminately override all values with the same field name.
1522  * Care must be taken to not override important information need to update or
1523  * update will fail (or perhaps create a new term, neither would be acceptable).
1524  *
1525  * Defaults will set 'alias_of', 'description', 'parent', and 'slug' if not
1526  * defined in $args already.
1527  *
1528  * 'alias_of' will create a term group, if it doesn't already exist, and update
1529  * it for the $term.
1530  *
1531  * If the 'slug' argument in $args is missing, then the 'name' in $args will be
1532  * used. It should also be noted that if you set 'slug' and it isn't unique then
1533  * a WP_Error will be passed back. If you don't pass any slug, then a unique one
1534  * will be created for you.
1535  *
1536  * For what can be overrode in $args, check the term scheme can contain and stay
1537  * away from the term keys.
1538  *
1539  * @package WordPress
1540  * @subpackage Taxonomy
1541  * @since 2.3.0
1542  *
1543  * @uses $wpdb
1544  * @uses do_action() Will call both 'edit_term' and 'edit_$taxonomy' twice.
1545  * @uses apply_filters() Will call the 'term_id_filter' filter and pass the term
1546  *      id and taxonomy id.
1547  *
1548  * @param int $term The ID of the term
1549  * @param string $taxonomy The context in which to relate the term to the object.
1550  * @param array|string $args Overwrite term field values
1551  * @return array|WP_Error Returns Term ID and Taxonomy Term ID
1552  */
1553 function wp_update_term( $term, $taxonomy, $args = array() ) {
1554         global $wpdb;
1555
1556         if ( ! is_taxonomy($taxonomy) )
1557                 return new WP_Error('invalid_taxonomy', __('Invalid taxonomy'));
1558
1559         $term_id = (int) $term;
1560
1561         // First, get all of the original args
1562         $term = get_term ($term_id, $taxonomy, ARRAY_A);
1563
1564         // Escape data pulled from DB.
1565         $term = add_magic_quotes($term);
1566
1567         // Merge old and new args with new args overwriting old ones.
1568         $args = array_merge($term, $args);
1569
1570         $defaults = array( 'alias_of' => '', 'description' => '', 'parent' => 0, 'slug' => '');
1571         $args = wp_parse_args($args, $defaults);
1572         $args = sanitize_term($args, $taxonomy, 'db');
1573         extract($args, EXTR_SKIP);
1574
1575         // expected_slashed ($name)
1576         $name = stripslashes($name);
1577         $description = stripslashes($description);
1578
1579         if ( '' == trim($name) )
1580                 return new WP_Error('empty_term_name', __('A name is required for this term'));
1581
1582         $empty_slug = false;
1583         if ( empty($slug) ) {
1584                 $empty_slug = true;
1585                 $slug = sanitize_title($name);
1586         }
1587
1588         if ( $alias_of ) {
1589                 $alias = $wpdb->get_row( $wpdb->prepare( "SELECT term_id, term_group FROM $wpdb->terms WHERE slug = %s", $alias_of) );
1590                 if ( $alias->term_group ) {
1591                         // The alias we want is already in a group, so let's use that one.
1592                         $term_group = $alias->term_group;
1593                 } else {
1594                         // The alias isn't in a group, so let's create a new one and firstly add the alias term to it.
1595                         $term_group = $wpdb->get_var("SELECT MAX(term_group) FROM $wpdb->terms") + 1;
1596                         $wpdb->update( $wpdb->terms, compact('term_group'), array( 'term_id' => $alias->term_id ) );
1597                 }
1598         }
1599
1600         // Check for duplicate slug
1601         $id = $wpdb->get_var( $wpdb->prepare( "SELECT term_id FROM $wpdb->terms WHERE slug = %s", $slug ) );
1602         if ( $id && ($id != $term_id) ) {
1603                 // If an empty slug was passed or the parent changed, reset the slug to something unique.
1604                 // Otherwise, bail.
1605                 if ( $empty_slug || ( $parent != $term->parent) )
1606                         $slug = wp_unique_term_slug($slug, (object) $args);
1607                 else
1608                         return new WP_Error('duplicate_term_slug', sprintf(__('The slug "%s" is already in use by another term'), $slug));
1609         }
1610
1611         $wpdb->update($wpdb->terms, compact( 'name', 'slug', 'term_group' ), compact( 'term_id' ) );
1612
1613         if ( empty($slug) ) {
1614                 $slug = sanitize_title($name, $term_id);
1615                 $wpdb->update( $wpdb->terms, compact( 'slug' ), compact( 'term_id' ) );
1616         }
1617
1618         $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) );
1619
1620         $wpdb->update( $wpdb->term_taxonomy, compact( 'term_id', 'taxonomy', 'description', 'parent' ), array( 'term_taxonomy_id' => $tt_id ) );
1621
1622         do_action("edit_term", $term_id, $tt_id);
1623         do_action("edit_$taxonomy", $term_id, $tt_id);
1624
1625         $term_id = apply_filters('term_id_filter', $term_id, $tt_id);
1626
1627         clean_term_cache($term_id, $taxonomy);
1628
1629         do_action("edited_term", $term_id, $tt_id);
1630         do_action("edited_$taxonomy", $term_id, $tt_id);
1631
1632         return array('term_id' => $term_id, 'term_taxonomy_id' => $tt_id);
1633 }
1634
1635 /**
1636  * Enable or disable term counting.
1637  *
1638  * @since 2.5.0
1639  *
1640  * @param bool $defer Optional. Enable if true, disable if false.
1641  * @return bool Whether term counting is enabled or disabled.
1642  */
1643 function wp_defer_term_counting($defer=null) {
1644         static $_defer = false;
1645
1646         if ( is_bool($defer) ) {
1647                 $_defer = $defer;
1648                 // flush any deferred counts
1649                 if ( !$defer )
1650                         wp_update_term_count( null, null, true );
1651         }
1652
1653         return $_defer;
1654 }
1655
1656 /**
1657  * Updates the amount of terms in taxonomy.
1658  *
1659  * If there is a taxonomy callback applyed, then it will be called for updating
1660  * the count.
1661  *
1662  * The default action is to count what the amount of terms have the relationship
1663  * of term ID. Once that is done, then update the database.
1664  *
1665  * @package WordPress
1666  * @subpackage Taxonomy
1667  * @since 2.3.0
1668  * @uses $wpdb
1669  *
1670  * @param int|array $terms The term_taxonomy_id of the terms
1671  * @param string $taxonomy The context of the term.
1672  * @return bool If no terms will return false, and if successful will return true.
1673  */
1674 function wp_update_term_count( $terms, $taxonomy, $do_deferred=false ) {
1675         static $_deferred = array();
1676
1677         if ( $do_deferred ) {
1678                 foreach ( (array) array_keys($_deferred) as $tax ) {
1679                         wp_update_term_count_now( $_deferred[$tax], $tax );
1680                         unset( $_deferred[$tax] );
1681                 }
1682         }
1683
1684         if ( empty($terms) )
1685                 return false;
1686
1687         if ( !is_array($terms) )
1688                 $terms = array($terms);
1689
1690         if ( wp_defer_term_counting() ) {
1691                 if ( !isset($_deferred[$taxonomy]) )
1692                         $_deferred[$taxonomy] = array();
1693                 $_deferred[$taxonomy] = array_unique( array_merge($_deferred[$taxonomy], $terms) );
1694                 return true;
1695         }
1696
1697         return wp_update_term_count_now( $terms, $taxonomy );
1698 }
1699
1700 /**
1701  * Perform term count update immediately.
1702  *
1703  * @since 2.5.0
1704  *
1705  * @param array $terms The term_taxonomy_id of terms to update.
1706  * @param string $taxonomy The context of the term.
1707  * @return bool Always true when complete.
1708  */
1709 function wp_update_term_count_now( $terms, $taxonomy ) {
1710         global $wpdb;
1711
1712         $terms = array_map('intval', $terms);
1713
1714         $taxonomy = get_taxonomy($taxonomy);
1715         if ( !empty($taxonomy->update_count_callback) ) {
1716                 call_user_func($taxonomy->update_count_callback, $terms);
1717         } else {
1718                 // Default count updater
1719                 foreach ( (array) $terms as $term) {
1720                         $count = $wpdb->get_var( $wpdb->prepare( "SELECT COUNT(*) FROM $wpdb->term_relationships WHERE term_taxonomy_id = %d", $term) );
1721                         $wpdb->update( $wpdb->term_taxonomy, compact( 'count' ), array( 'term_taxonomy_id' => $term ) );
1722                 }
1723
1724         }
1725
1726         clean_term_cache($terms);
1727
1728         return true;
1729 }
1730
1731 //
1732 // Cache
1733 //
1734
1735
1736 /**
1737  * Removes the taxonomy relationship to terms from the cache.
1738  *
1739  * Will remove the entire taxonomy relationship containing term $object_id. The
1740  * term IDs have to exist within the taxonomy $object_type for the deletion to
1741  * take place.
1742  *
1743  * @package WordPress
1744  * @subpackage Taxonomy
1745  * @since 2.3.0
1746  *
1747  * @see get_object_taxonomies() for more on $object_type
1748  * @uses do_action() Will call action hook named, 'clean_object_term_cache' after completion.
1749  *      Passes, function params in same order.
1750  *
1751  * @param int|array $object_ids Single or list of term object ID(s)
1752  * @param array|string $object_type The taxonomy object type
1753  */
1754 function clean_object_term_cache($object_ids, $object_type) {
1755         if ( !is_array($object_ids) )
1756                 $object_ids = array($object_ids);
1757
1758         foreach ( $object_ids as $id )
1759                 foreach ( get_object_taxonomies($object_type) as $taxonomy )
1760                         wp_cache_delete($id, "{$taxonomy}_relationships");
1761
1762         do_action('clean_object_term_cache', $object_ids, $object_type);
1763 }
1764
1765
1766 /**
1767  * Will remove all of the term ids from the cache.
1768  *
1769  * @package WordPress
1770  * @subpackage Taxonomy
1771  * @since 2.3.0
1772  * @uses $wpdb
1773  *
1774  * @param int|array $ids Single or list of Term IDs
1775  * @param string $taxonomy Can be empty and will assume tt_ids, else will use for context.
1776  */
1777 function clean_term_cache($ids, $taxonomy = '') {
1778         global $wpdb;
1779         static $cleaned = array();
1780
1781         if ( !is_array($ids) )
1782                 $ids = array($ids);
1783
1784         $taxonomies = array();
1785         // If no taxonomy, assume tt_ids.
1786         if ( empty($taxonomy) ) {
1787                 $tt_ids = implode(', ', $ids);
1788                 $terms = $wpdb->get_results("SELECT term_id, taxonomy FROM $wpdb->term_taxonomy WHERE term_taxonomy_id IN ($tt_ids)");
1789                 foreach ( (array) $terms as $term ) {
1790                         $taxonomies[] = $term->taxonomy;
1791                         wp_cache_delete($term->term_id, $term->taxonomy);
1792                 }
1793                 $taxonomies = array_unique($taxonomies);
1794         } else {
1795                 foreach ( $ids as $id ) {
1796                         wp_cache_delete($id, $taxonomy);
1797                 }
1798                 $taxonomies = array($taxonomy);
1799         }
1800
1801         foreach ( $taxonomies as $taxonomy ) {
1802                 if ( isset($cleaned[$taxonomy]) )
1803                         continue;
1804                 $cleaned[$taxonomy] = true;
1805                 wp_cache_delete('all_ids', $taxonomy);
1806                 wp_cache_delete('get', $taxonomy);
1807                 delete_option("{$taxonomy}_children");
1808         }
1809
1810         wp_cache_set('last_changed', time(), 'terms');
1811
1812         do_action('clean_term_cache', $ids, $taxonomy);
1813 }
1814
1815
1816 /**
1817  * Retrieves the taxonomy relationship to the term object id.
1818  *
1819  * @package WordPress
1820  * @subpackage Taxonomy
1821  * @since 2.3.0
1822  *
1823  * @uses wp_cache_get() Retrieves taxonomy relationship from cache
1824  *
1825  * @param int|array $id Term object ID
1826  * @param string $taxonomy Taxonomy Name
1827  * @return bool|array Empty array if $terms found, but not $taxonomy. False if nothing is in cache for $taxonomy and $id.
1828  */
1829 function &get_object_term_cache($id, $taxonomy) {
1830         $cache = wp_cache_get($id, "{$taxonomy}_relationships");
1831         return $cache;
1832 }
1833
1834
1835 /**
1836  * Updates the cache for Term ID(s).
1837  *
1838  * Will only update the cache for terms not already cached.
1839  *
1840  * The $object_ids expects that the ids be separated by commas, if it is a
1841  * string.
1842  *
1843  * It should be noted that update_object_term_cache() is very time extensive. It
1844  * is advised that the function is not called very often or at least not for a
1845  * lot of terms that exist in a lot of taxonomies. The amount of time increases
1846  * for each term and it also increases for each taxonomy the term belongs to.
1847  *
1848  * @package WordPress
1849  * @subpackage Taxonomy
1850  * @since 2.3.0
1851  * @uses wp_get_object_terms() Used to get terms from the database to update
1852  *
1853  * @param string|array $object_ids Single or list of term object ID(s)
1854  * @param array|string $object_type The taxonomy object type
1855  * @return null|bool Null value is given with empty $object_ids. False if
1856  */
1857 function update_object_term_cache($object_ids, $object_type) {
1858         if ( empty($object_ids) )
1859                 return;
1860
1861         if ( !is_array($object_ids) )
1862                 $object_ids = explode(',', $object_ids);
1863
1864         $object_ids = array_map('intval', $object_ids);
1865
1866         $taxonomies = get_object_taxonomies($object_type);
1867
1868         $ids = array();
1869         foreach ( (array) $object_ids as $id ) {
1870                 foreach ( $taxonomies as $taxonomy ) {
1871                         if ( false === wp_cache_get($id, "{$taxonomy}_relationships") ) {
1872                                 $ids[] = $id;
1873                                 break;
1874                         }
1875                 }
1876         }
1877
1878         if ( empty( $ids ) )
1879                 return false;
1880
1881         $terms = wp_get_object_terms($ids, $taxonomies, 'fields=all_with_object_id');
1882
1883         $object_terms = array();
1884         foreach ( (array) $terms as $term )
1885                 $object_terms[$term->object_id][$term->taxonomy][$term->term_id] = $term;
1886
1887         foreach ( $ids as $id ) {
1888                 foreach ( $taxonomies  as $taxonomy ) {
1889                         if ( ! isset($object_terms[$id][$taxonomy]) ) {
1890                                 if ( !isset($object_terms[$id]) )
1891                                         $object_terms[$id] = array();
1892                                 $object_terms[$id][$taxonomy] = array();
1893                         }
1894                 }
1895         }
1896
1897         foreach ( $object_terms as $id => $value ) {
1898                 foreach ( $value as $taxonomy => $terms ) {
1899                         wp_cache_set($id, $terms, "{$taxonomy}_relationships");
1900                 }
1901         }
1902 }
1903
1904
1905 /**
1906  * Updates Terms to Taxonomy in cache.
1907  *
1908  * @package WordPress
1909  * @subpackage Taxonomy
1910  * @since 2.3.0
1911  *
1912  * @param array $terms List of Term objects to change
1913  * @param string $taxonomy Optional. Update Term to this taxonomy in cache
1914  */
1915 function update_term_cache($terms, $taxonomy = '') {
1916         foreach ( (array) $terms as $term ) {
1917                 $term_taxonomy = $taxonomy;
1918                 if ( empty($term_taxonomy) )
1919                         $term_taxonomy = $term->taxonomy;
1920
1921                 wp_cache_add($term->term_id, $term, $term_taxonomy);
1922         }
1923 }
1924
1925 //
1926 // Private
1927 //
1928
1929
1930 /**
1931  * Retrieves children of taxonomy.
1932  *
1933  * @package WordPress
1934  * @subpackage Taxonomy
1935  * @access private
1936  * @since 2.3.0
1937  *
1938  * @uses update_option() Stores all of the children in "$taxonomy_children"
1939  *       option. That is the name of the taxonomy, immediately followed by '_children'.
1940  *
1941  * @param string $taxonomy Taxonomy Name
1942  * @return array Empty if $taxonomy isn't hierarachical or returns children.
1943  */
1944 function _get_term_hierarchy($taxonomy) {
1945         if ( !is_taxonomy_hierarchical($taxonomy) )
1946                 return array();
1947         $children = get_option("{$taxonomy}_children");
1948         if ( is_array($children) )
1949                 return $children;
1950
1951         $children = array();
1952         $terms = get_terms($taxonomy, 'get=all');
1953         foreach ( $terms as $term ) {
1954                 if ( $term->parent > 0 )
1955                         $children[$term->parent][] = $term->term_id;
1956         }
1957         update_option("{$taxonomy}_children", $children);
1958
1959         return $children;
1960 }
1961
1962
1963 /**
1964  * Get the subset of $terms that are descendants of $term_id.
1965  *
1966  * If $terms is an array of objects, then _get_term_children returns an array of objects.
1967  * If $terms is an array of IDs, then _get_term_children returns an array of IDs.
1968  *
1969  * @package WordPress
1970  * @subpackage Taxonomy
1971  * @access private
1972  * @since 2.3.0
1973  *
1974  * @param int $term_id The ancestor term: all returned terms should be descendants of $term_id.
1975  * @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.
1976  * @param string $taxonomy The taxonomy which determines the hierarchy of the terms.
1977  * @return array The subset of $terms that are descendants of $term_id.
1978  */
1979 function &_get_term_children($term_id, $terms, $taxonomy) {
1980         $empty_array = array();
1981         if ( empty($terms) )
1982                 return $empty_array;
1983
1984         $term_list = array();
1985         $has_children = _get_term_hierarchy($taxonomy);
1986
1987         if  ( ( 0 != $term_id ) && ! isset($has_children[$term_id]) )
1988                 return $empty_array;
1989
1990         foreach ( (array) $terms as $term ) {
1991                 $use_id = false;
1992                 if ( !is_object($term) ) {
1993                         $term = get_term($term, $taxonomy);
1994                         if ( is_wp_error( $term ) )
1995                                 return $term;
1996                         $use_id = true;
1997                 }
1998
1999                 if ( $term->term_id == $term_id )
2000                         continue;
2001
2002                 if ( $term->parent == $term_id ) {
2003                         if ( $use_id )
2004                                 $term_list[] = $term->term_id;
2005                         else
2006                                 $term_list[] = $term;
2007
2008                         if ( !isset($has_children[$term->term_id]) )
2009                                 continue;
2010
2011                         if ( $children = _get_term_children($term->term_id, $terms, $taxonomy) )
2012                                 $term_list = array_merge($term_list, $children);
2013                 }
2014         }
2015
2016         return $term_list;
2017 }
2018
2019
2020 /**
2021  * Add count of children to parent count.
2022  *
2023  * Recalculates term counts by including items from child terms. Assumes all
2024  * relevant children are already in the $terms argument.
2025  *
2026  * @package WordPress
2027  * @subpackage Taxonomy
2028  * @access private
2029  * @since 2.3.0
2030  * @uses $wpdb
2031  *
2032  * @param array $terms List of Term IDs
2033  * @param string $taxonomy Term Context
2034  * @return null Will break from function if conditions are not met.
2035  */
2036 function _pad_term_counts(&$terms, $taxonomy) {
2037         global $wpdb;
2038
2039         // This function only works for post categories.
2040         if ( 'category' != $taxonomy )
2041                 return;
2042
2043         $term_hier = _get_term_hierarchy($taxonomy);
2044
2045         if ( empty($term_hier) )
2046                 return;
2047
2048         $term_items = array();
2049
2050         foreach ( (array) $terms as $key => $term ) {
2051                 $terms_by_id[$term->term_id] = & $terms[$key];
2052                 $term_ids[$term->term_taxonomy_id] = $term->term_id;
2053         }
2054
2055         // Get the object and term ids and stick them in a lookup table
2056         $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 (".join(',', array_keys($term_ids)).") AND post_type = 'post' AND post_status = 'publish'");
2057         foreach ( $results as $row ) {
2058                 $id = $term_ids[$row->term_taxonomy_id];
2059                 $term_items[$id][$row->object_id] = isset($term_items[$id][$row->object_id]) ? ++$term_items[$id][$row->object_id] : 1;
2060         }
2061
2062         // Touch every ancestor's lookup row for each post in each term
2063         foreach ( $term_ids as $term_id ) {
2064                 $child = $term_id;
2065                 while ( $parent = $terms_by_id[$child]->parent ) {
2066                         if ( !empty($term_items[$term_id]) )
2067                                 foreach ( $term_items[$term_id] as $item_id => $touches ) {
2068                                         $term_items[$parent][$item_id] = isset($term_items[$parent][$item_id]) ? ++$term_items[$parent][$item_id]: 1;
2069                                 }
2070                         $child = $parent;
2071                 }
2072         }
2073
2074         // Transfer the touched cells
2075         foreach ( (array) $term_items as $id => $items )
2076                 if ( isset($terms_by_id[$id]) )
2077                         $terms_by_id[$id]->count = count($items);
2078 }
2079
2080 //
2081 // Default callbacks
2082 //
2083
2084 /**
2085  * Will update term count based on posts.
2086  *
2087  * Private function for the default callback for post_tag and category
2088  * taxonomies.
2089  *
2090  * @package WordPress
2091  * @subpackage Taxonomy
2092  * @access private
2093  * @since 2.3.0
2094  * @uses $wpdb
2095  *
2096  * @param array $terms List of Term taxonomy IDs
2097  */
2098 function _update_post_term_count( $terms ) {
2099         global $wpdb;
2100
2101         foreach ( (array) $terms as $term ) {
2102                 $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 = 'post' AND term_taxonomy_id = %d", $term ) );
2103                 $wpdb->update( $wpdb->term_taxonomy, compact( 'count' ), array( 'term_taxonomy_id' => $term ) );
2104         }
2105 }
2106
2107
2108 /**
2109  * Generates a permalink for a taxonomy term archive.
2110  *
2111  * @since 2.5.0
2112  *
2113  * @param object|int|string $term
2114  * @param string $taxonomy
2115  * @return string HTML link to taxonomy term archive
2116  */
2117 function get_term_link( $term, $taxonomy ) {
2118         global $wp_rewrite;
2119
2120         // use legacy functions for core taxonomies until they are fully plugged in
2121         if ( $taxonomy == 'category' )
2122                 return get_category_link($term);
2123         if ( $taxonomy == 'post_tag' )
2124                 return get_tag_link($term);
2125
2126         $termlink = $wp_rewrite->get_extra_permastruct($taxonomy);
2127
2128         if ( !is_object($term) ) {
2129                 if ( is_int($term) ) {
2130                         $term = &get_term($term, $taxonomy);
2131                 } else {
2132                         $term = &get_term_by('slug', $term, $taxonomy);
2133                 }
2134         }
2135         if ( is_wp_error( $term ) )
2136                 return $term;
2137
2138         $slug = $term->slug;
2139
2140         if ( empty($termlink) ) {
2141                 $file = get_option('home') . '/';
2142                 $t = get_taxonomy($taxonomy);
2143                 if ( $t->query_var )
2144                         $termlink = "$file?$t->query_var=$slug";
2145                 else
2146                         $termlink = "$file?taxonomy=$taxonomy&term=$slug";
2147         } else {
2148                 $termlink = str_replace("%$taxonomy%", $slug, $termlink);
2149                 $termlink = get_option('home') . user_trailingslashit($termlink, 'category');
2150         }
2151         return apply_filters('term_link', $termlink, $term, $taxonomy);
2152 }
2153
2154 /**
2155  * Display the taxonomies of a post with available options.
2156  *
2157  * This function can be used within the loop to display the taxonomies for a
2158  * post without specifying the Post ID. You can also use it outside the Loop to
2159  * display the taxonomies for a specific post.
2160  *
2161  * The available defaults are:
2162  * 'post' : default is 0. The post ID to get taxonomies of.
2163  * 'before' : default is empty string. Display before taxonomies list.
2164  * 'sep' : default is empty string. Separate every taxonomy with value in this.
2165  * 'after' : default is empty string. Display this after the taxonomies list.
2166  *
2167  * @since 2.5.0
2168  * @uses get_the_taxonomies()
2169  *
2170  * @param array $args Override the defaults.
2171  */
2172 function the_taxonomies($args = array()) {
2173         $defaults = array(
2174                 'post' => 0,
2175                 'before' => '',
2176                 'sep' => ' ',
2177                 'after' => '',
2178         );
2179
2180         $r = wp_parse_args( $args, $defaults );
2181         extract( $r, EXTR_SKIP );
2182
2183         echo $before . join($sep, get_the_taxonomies($post)) . $after;
2184 }
2185
2186 /**
2187  * Retrieve all taxonomies associated with a post.
2188  *
2189  * This function can be used within the loop. It will also return an array of
2190  * the taxonomies with links to the taxonomy and name.
2191  *
2192  * @since 2.5.0
2193  *
2194  * @param int $post Optional. Post ID or will use Global Post ID (in loop).
2195  * @return array
2196  */
2197 function get_the_taxonomies($post = 0) {
2198         if ( is_int($post) )
2199                 $post =& get_post($post);
2200         elseif ( !is_object($post) )
2201                 $post =& $GLOBALS['post'];
2202
2203         $taxonomies = array();
2204
2205         if ( !$post )
2206                 return $taxonomies;
2207
2208         $template = apply_filters('taxonomy_template', '%s: %l.');
2209
2210         foreach ( get_object_taxonomies($post) as $taxonomy ) {
2211                 $t = (array) get_taxonomy($taxonomy);
2212                 if ( empty($t['label']) )
2213                         $t['label'] = $taxonomy;
2214                 if ( empty($t['args']) )
2215                         $t['args'] = array();
2216                 if ( empty($t['template']) )
2217                         $t['template'] = $template;
2218
2219                 $terms = get_object_term_cache($post->ID, $taxonomy);
2220                 if ( empty($terms) )
2221                         $terms = wp_get_object_terms($post->ID, $taxonomy, $t['args']);
2222
2223                 $links = array();
2224
2225                 foreach ( $terms as $term )
2226                         $links[] = "<a href='" . attribute_escape(get_term_link($term, $taxonomy)) . "'>$term->name</a>";
2227
2228                 if ( $links )
2229                         $taxonomies[$taxonomy] = wp_sprintf($t['template'], $t['label'], $links, $terms);
2230         }
2231         return $taxonomies;
2232 }
2233
2234 /**
2235  * Retrieve all taxonomies of a post with just the names.
2236  *
2237  * @since 2.5.0
2238  * @uses get_object_taxonomies()
2239  *
2240  * @param int $post Optional. Post ID
2241  * @return array
2242  */
2243 function get_post_taxonomies($post = 0) {
2244         $post =& get_post($post);
2245
2246         return get_object_taxonomies($post);
2247 }
2248
2249 /**
2250  * Determine if the given object is associated with any of the given terms.
2251  *
2252  * The given terms are checked against the object's terms' term_ids, names and slugs.
2253  * Terms given as integers will only be checked against the object's terms' term_ids.
2254  * If no terms are given, determines if object is associated with any terms in the given taxonomy.
2255  *
2256  * @since 2.7.0
2257  * @uses get_object_term_cache()
2258  * @uses wp_get_object_terms()
2259  *
2260  * @param int $object_id.  ID of the object (post ID, link ID, ...)
2261  * @param string $taxonomy.  Single taxonomy name
2262  * @param int|string|array $terms Optional.  Term term_id, name, slug or array of said
2263  * @return bool|WP_Error. WP_Error on input error.
2264  */
2265 function is_object_in_term( $object_id, $taxonomy, $terms = null ) {
2266         if ( !$object_id = (int) $object_id )
2267                 return new WP_Error( 'invalid_object', __( 'Invalid object ID' ) );
2268
2269         $object_terms = get_object_term_cache( $object_id, $taxonomy );
2270         if ( empty( $object_terms ) )
2271                  $object_terms = wp_get_object_terms( $object_id, $taxonomy );
2272
2273         if ( is_wp_error( $object_terms ) )
2274                 return $object_terms;
2275         if ( empty( $object_terms ) )
2276                 return false;
2277         if ( empty( $terms ) )
2278                 return ( !empty( $object_terms ) );
2279
2280         $terms = (array) $terms;
2281
2282         if ( $ints = array_filter( $terms, 'is_int' ) )
2283                 $strs = array_diff( $terms, $ints );
2284         else
2285                 $strs =& $terms;
2286
2287         foreach ( $object_terms as $object_term ) {
2288                 if ( $ints && in_array( $object_term->term_id, $ints ) ) return true; // If int, check against term_id
2289                 if ( $strs ) {
2290                         if ( in_array( $object_term->term_id, $strs ) ) return true;
2291                         if ( in_array( $object_term->name, $strs ) )    return true;
2292                         if ( in_array( $object_term->slug, $strs ) )    return true;
2293                 }
2294         }
2295
2296         return false;
2297 }
2298
2299 ?>