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