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