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