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