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