]> scripts.mit.edu Git - autoinstalls/wordpress.git/blob - wp-includes/taxonomy.php
WordPress 3.6.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(
321                 'hierarchical' => false,
322                 'update_count_callback' => '',
323                 'rewrite' => true,
324                 'query_var' => $taxonomy,
325                 'public' => true,
326                 'show_ui' => null,
327                 'show_tagcloud' => null,
328                 '_builtin' => false,
329                 'labels' => array(),
330                 'capabilities' => array(),
331                 'show_in_nav_menus' => null,
332         );
333         $args = wp_parse_args($args, $defaults);
334
335         if ( strlen( $taxonomy ) > 32 )
336                 return new WP_Error( 'taxonomy_too_long', __( 'Taxonomies cannot exceed 32 characters in length' ) );
337
338         if ( false !== $args['query_var'] && !empty($wp) ) {
339                 if ( true === $args['query_var'] )
340                         $args['query_var'] = $taxonomy;
341                 else
342                         $args['query_var'] = sanitize_title_with_dashes($args['query_var']);
343                 $wp->add_query_var($args['query_var']);
344         }
345
346         if ( false !== $args['rewrite'] && ( is_admin() || '' != get_option('permalink_structure') ) ) {
347                 $args['rewrite'] = wp_parse_args($args['rewrite'], array(
348                         'slug' => sanitize_title_with_dashes($taxonomy),
349                         'with_front' => true,
350                         'hierarchical' => false,
351                         'ep_mask' => EP_NONE,
352                 ));
353
354                 if ( $args['hierarchical'] && $args['rewrite']['hierarchical'] )
355                         $tag = '(.+?)';
356                 else
357                         $tag = '([^/]+)';
358
359                 add_rewrite_tag( "%$taxonomy%", $tag, $args['query_var'] ? "{$args['query_var']}=" : "taxonomy=$taxonomy&term=" );
360                 add_permastruct( $taxonomy, "{$args['rewrite']['slug']}/%$taxonomy%", $args['rewrite'] );
361         }
362
363         if ( is_null($args['show_ui']) )
364                 $args['show_ui'] = $args['public'];
365
366         // Whether to show this type in nav-menus.php. Defaults to the setting for public.
367         if ( null === $args['show_in_nav_menus'] )
368                 $args['show_in_nav_menus'] = $args['public'];
369
370         if ( is_null($args['show_tagcloud']) )
371                 $args['show_tagcloud'] = $args['show_ui'];
372
373         $default_caps = array(
374                 'manage_terms' => 'manage_categories',
375                 'edit_terms'   => 'manage_categories',
376                 'delete_terms' => 'manage_categories',
377                 'assign_terms' => 'edit_posts',
378         );
379         $args['cap'] = (object) array_merge( $default_caps, $args['capabilities'] );
380         unset( $args['capabilities'] );
381
382         $args['name'] = $taxonomy;
383         $args['object_type'] =  array_unique( (array)$object_type );
384
385         $args['labels'] = get_taxonomy_labels( (object) $args );
386         $args['label'] = $args['labels']->name;
387
388         $wp_taxonomies[$taxonomy] = (object) $args;
389
390         // register callback handling for metabox
391         add_filter('wp_ajax_add-' . $taxonomy, '_wp_ajax_add_hierarchical_term');
392
393         do_action( 'registered_taxonomy', $taxonomy, $object_type, $args );
394 }
395
396 /**
397  * Builds an object with all taxonomy labels out of a taxonomy object
398  *
399  * Accepted keys of the label array in the taxonomy object:
400  * - name - general name for the taxonomy, usually plural. The same as and overridden by $tax->label. Default is Tags/Categories
401  * - singular_name - name for one object of this taxonomy. Default is Tag/Category
402  * - search_items - Default is Search Tags/Search Categories
403  * - popular_items - This string isn't used on hierarchical taxonomies. Default is Popular Tags
404  * - all_items - Default is All Tags/All Categories
405  * - parent_item - This string isn't used on non-hierarchical taxonomies. In hierarchical ones the default is Parent Category
406  * - parent_item_colon - The same as <code>parent_item</code>, but with colon <code>:</code> in the end
407  * - edit_item - Default is Edit Tag/Edit Category
408  * - view_item - Default is View Tag/View Category
409  * - update_item - Default is Update Tag/Update Category
410  * - add_new_item - Default is Add New Tag/Add New Category
411  * - new_item_name - Default is New Tag Name/New Category Name
412  * - separate_items_with_commas - This string isn't used on hierarchical taxonomies. Default is "Separate tags with commas", used in the meta box.
413  * - 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.
414  * - 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.
415  * - not_found - This string isn't used on hierarchical taxonomies. Default is "No tags found", used in the meta box.
416  *
417  * Above, the first default value is for non-hierarchical taxonomies (like tags) and the second one is for hierarchical taxonomies (like categories).
418  *
419  * @since 3.0.0
420  * @param object $tax Taxonomy object
421  * @return object object with all the labels as member variables
422  */
423
424 function get_taxonomy_labels( $tax ) {
425         if ( isset( $tax->helps ) && empty( $tax->labels['separate_items_with_commas'] ) )
426                 $tax->labels['separate_items_with_commas'] = $tax->helps;
427
428         if ( isset( $tax->no_tagcloud ) && empty( $tax->labels['not_found'] ) )
429                 $tax->labels['not_found'] = $tax->no_tagcloud;
430
431         $nohier_vs_hier_defaults = array(
432                 'name' => array( _x( 'Tags', 'taxonomy general name' ), _x( 'Categories', 'taxonomy general name' ) ),
433                 'singular_name' => array( _x( 'Tag', 'taxonomy singular name' ), _x( 'Category', 'taxonomy singular name' ) ),
434                 'search_items' => array( __( 'Search Tags' ), __( 'Search Categories' ) ),
435                 'popular_items' => array( __( 'Popular Tags' ), null ),
436                 'all_items' => array( __( 'All Tags' ), __( 'All Categories' ) ),
437                 'parent_item' => array( null, __( 'Parent Category' ) ),
438                 'parent_item_colon' => array( null, __( 'Parent Category:' ) ),
439                 'edit_item' => array( __( 'Edit Tag' ), __( 'Edit Category' ) ),
440                 'view_item' => array( __( 'View Tag' ), __( 'View Category' ) ),
441                 'update_item' => array( __( 'Update Tag' ), __( 'Update Category' ) ),
442                 'add_new_item' => array( __( 'Add New Tag' ), __( 'Add New Category' ) ),
443                 'new_item_name' => array( __( 'New Tag Name' ), __( 'New Category Name' ) ),
444                 'separate_items_with_commas' => array( __( 'Separate tags with commas' ), null ),
445                 'add_or_remove_items' => array( __( 'Add or remove tags' ), null ),
446                 'choose_from_most_used' => array( __( 'Choose from the most used tags' ), null ),
447                 'not_found' => array( __( 'No tags found.' ), null ),
448         );
449         $nohier_vs_hier_defaults['menu_name'] = $nohier_vs_hier_defaults['name'];
450
451         return _get_custom_object_labels( $tax, $nohier_vs_hier_defaults );
452 }
453
454 /**
455  * Add an already registered taxonomy to an object type.
456  *
457  * @package WordPress
458  * @subpackage Taxonomy
459  * @since 3.0.0
460  * @uses $wp_taxonomies Modifies taxonomy object
461  *
462  * @param string $taxonomy Name of taxonomy object
463  * @param string $object_type Name of the object type
464  * @return bool True if successful, false if not
465  */
466 function register_taxonomy_for_object_type( $taxonomy, $object_type) {
467         global $wp_taxonomies;
468
469         if ( !isset($wp_taxonomies[$taxonomy]) )
470                 return false;
471
472         if ( ! get_post_type_object($object_type) )
473                 return false;
474
475         if ( ! in_array( $object_type, $wp_taxonomies[$taxonomy]->object_type ) )
476                 $wp_taxonomies[$taxonomy]->object_type[] = $object_type;
477
478         return true;
479 }
480
481 //
482 // Term API
483 //
484
485 /**
486  * Retrieve object_ids of valid taxonomy and term.
487  *
488  * The strings of $taxonomies must exist before this function will continue. On
489  * failure of finding a valid taxonomy, it will return an WP_Error class, kind
490  * of like Exceptions in PHP 5, except you can't catch them. Even so, you can
491  * still test for the WP_Error class and get the error message.
492  *
493  * The $terms aren't checked the same as $taxonomies, but still need to exist
494  * for $object_ids to be returned.
495  *
496  * It is possible to change the order that object_ids is returned by either
497  * using PHP sort family functions or using the database by using $args with
498  * either ASC or DESC array. The value should be in the key named 'order'.
499  *
500  * @package WordPress
501  * @subpackage Taxonomy
502  * @since 2.3.0
503  *
504  * @uses $wpdb
505  * @uses wp_parse_args() Creates an array from string $args.
506  *
507  * @param int|array $term_ids Term id or array of term ids of terms that will be used
508  * @param string|array $taxonomies String of taxonomy name or Array of string values of taxonomy names
509  * @param array|string $args Change the order of the object_ids, either ASC or DESC
510  * @return WP_Error|array If the taxonomy does not exist, then WP_Error will be returned. On success
511  *      the array can be empty meaning that there are no $object_ids found or it will return the $object_ids found.
512  */
513 function get_objects_in_term( $term_ids, $taxonomies, $args = array() ) {
514         global $wpdb;
515
516         if ( ! is_array( $term_ids ) )
517                 $term_ids = array( $term_ids );
518
519         if ( ! is_array( $taxonomies ) )
520                 $taxonomies = array( $taxonomies );
521
522         foreach ( (array) $taxonomies as $taxonomy ) {
523                 if ( ! taxonomy_exists( $taxonomy ) )
524                         return new WP_Error( 'invalid_taxonomy', __( 'Invalid taxonomy' ) );
525         }
526
527         $defaults = array( 'order' => 'ASC' );
528         $args = wp_parse_args( $args, $defaults );
529         extract( $args, EXTR_SKIP );
530
531         $order = ( 'desc' == strtolower( $order ) ) ? 'DESC' : 'ASC';
532
533         $term_ids = array_map('intval', $term_ids );
534
535         $taxonomies = "'" . implode( "', '", $taxonomies ) . "'";
536         $term_ids = "'" . implode( "', '", $term_ids ) . "'";
537
538         $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");
539
540         if ( ! $object_ids )
541                 return array();
542
543         return $object_ids;
544 }
545
546 /**
547  * Given a taxonomy query, generates SQL to be appended to a main query.
548  *
549  * @since 3.1.0
550  *
551  * @see WP_Tax_Query
552  *
553  * @param array $tax_query A compact tax query
554  * @param string $primary_table
555  * @param string $primary_id_column
556  * @return array
557  */
558 function get_tax_sql( $tax_query, $primary_table, $primary_id_column ) {
559         $tax_query_obj = new WP_Tax_Query( $tax_query );
560         return $tax_query_obj->get_sql( $primary_table, $primary_id_column );
561 }
562
563 /**
564  * Container class for a multiple taxonomy query.
565  *
566  * @since 3.1.0
567  */
568 class WP_Tax_Query {
569
570         /**
571          * List of taxonomy queries. A single taxonomy query is an associative array:
572          * - 'taxonomy' string The taxonomy being queried
573          * - 'terms' string|array The list of terms
574          * - 'field' string (optional) Which term field is being used.
575          *              Possible values: 'term_id', 'slug' or 'name'
576          *              Default: 'term_id'
577          * - 'operator' string (optional)
578          *              Possible values: 'AND', 'IN' or 'NOT IN'.
579          *              Default: 'IN'
580          * - 'include_children' bool (optional) Whether to include child terms.
581          *              Default: true
582          *
583          * @since 3.1.0
584          * @access public
585          * @var array
586          */
587         public $queries = array();
588
589         /**
590          * The relation between the queries. Can be one of 'AND' or 'OR'.
591          *
592          * @since 3.1.0
593          * @access public
594          * @var string
595          */
596         public $relation;
597
598         /**
599          * Standard response when the query should not return any rows.
600          *
601          * @since 3.2.0
602          * @access private
603          * @var string
604          */
605         private static $no_results = array( 'join' => '', 'where' => ' AND 0 = 1' );
606
607         /**
608          * Constructor.
609          *
610          * Parses a compact tax query and sets defaults.
611          *
612          * @since 3.1.0
613          * @access public
614          *
615          * @param array $tax_query A compact tax query:
616          *  array(
617          *    'relation' => 'OR',
618          *    array(
619          *      'taxonomy' => 'tax1',
620          *      'terms' => array( 'term1', 'term2' ),
621          *      'field' => 'slug',
622          *    ),
623          *    array(
624          *      'taxonomy' => 'tax2',
625          *      'terms' => array( 'term-a', 'term-b' ),
626          *      'field' => 'slug',
627          *    ),
628          *  )
629          */
630         public function __construct( $tax_query ) {
631                 if ( isset( $tax_query['relation'] ) && strtoupper( $tax_query['relation'] ) == 'OR' ) {
632                         $this->relation = 'OR';
633                 } else {
634                         $this->relation = 'AND';
635                 }
636
637                 $defaults = array(
638                         'taxonomy' => '',
639                         'terms' => array(),
640                         'include_children' => true,
641                         'field' => 'term_id',
642                         'operator' => 'IN',
643                 );
644
645                 foreach ( $tax_query as $query ) {
646                         if ( ! is_array( $query ) )
647                                 continue;
648
649                         $query = array_merge( $defaults, $query );
650
651                         $query['terms'] = (array) $query['terms'];
652
653                         $this->queries[] = $query;
654                 }
655         }
656
657         /**
658          * Generates SQL clauses to be appended to a main query.
659          *
660          * @since 3.1.0
661          * @access public
662          *
663          * @param string $primary_table
664          * @param string $primary_id_column
665          * @return array
666          */
667         public function get_sql( $primary_table, $primary_id_column ) {
668                 global $wpdb;
669
670                 $join = '';
671                 $where = array();
672                 $i = 0;
673                 $count = count( $this->queries );
674
675                 foreach ( $this->queries as $index => $query ) {
676                         $this->clean_query( $query );
677
678                         if ( is_wp_error( $query ) )
679                                 return self::$no_results;
680
681                         extract( $query );
682
683                         if ( 'IN' == $operator ) {
684
685                                 if ( empty( $terms ) ) {
686                                         if ( 'OR' == $this->relation ) {
687                                                 if ( ( $index + 1 === $count ) && empty( $where ) )
688                                                         return self::$no_results;
689                                                 continue;
690                                         } else {
691                                                 return self::$no_results;
692                                         }
693                                 }
694
695                                 $terms = implode( ',', $terms );
696
697                                 $alias = $i ? 'tt' . $i : $wpdb->term_relationships;
698
699                                 $join .= " INNER JOIN $wpdb->term_relationships";
700                                 $join .= $i ? " AS $alias" : '';
701                                 $join .= " ON ($primary_table.$primary_id_column = $alias.object_id)";
702
703                                 $where[] = "$alias.term_taxonomy_id $operator ($terms)";
704                         } elseif ( 'NOT IN' == $operator ) {
705
706                                 if ( empty( $terms ) )
707                                         continue;
708
709                                 $terms = implode( ',', $terms );
710
711                                 $where[] = "$primary_table.$primary_id_column NOT IN (
712                                         SELECT object_id
713                                         FROM $wpdb->term_relationships
714                                         WHERE term_taxonomy_id IN ($terms)
715                                 )";
716                         } elseif ( 'AND' == $operator ) {
717
718                                 if ( empty( $terms ) )
719                                         continue;
720
721                                 $num_terms = count( $terms );
722
723                                 $terms = implode( ',', $terms );
724
725                                 $where[] = "(
726                                         SELECT COUNT(1)
727                                         FROM $wpdb->term_relationships
728                                         WHERE term_taxonomy_id IN ($terms)
729                                         AND object_id = $primary_table.$primary_id_column
730                                 ) = $num_terms";
731                         }
732
733                         $i++;
734                 }
735
736                 if ( ! empty( $where ) )
737                         $where = ' AND ( ' . implode( " $this->relation ", $where ) . ' )';
738                 else
739                         $where = '';
740
741                 return compact( 'join', 'where' );
742         }
743
744         /**
745          * Validates a single query.
746          *
747          * @since 3.2.0
748          * @access private
749          *
750          * @param array &$query The single query
751          */
752         private function clean_query( &$query ) {
753                 if ( ! taxonomy_exists( $query['taxonomy'] ) ) {
754                         $query = new WP_Error( 'Invalid taxonomy' );
755                         return;
756                 }
757
758                 $query['terms'] = array_unique( (array) $query['terms'] );
759
760                 if ( is_taxonomy_hierarchical( $query['taxonomy'] ) && $query['include_children'] ) {
761                         $this->transform_query( $query, 'term_id' );
762
763                         if ( is_wp_error( $query ) )
764                                 return;
765
766                         $children = array();
767                         foreach ( $query['terms'] as $term ) {
768                                 $children = array_merge( $children, get_term_children( $term, $query['taxonomy'] ) );
769                                 $children[] = $term;
770                         }
771                         $query['terms'] = $children;
772                 }
773
774                 $this->transform_query( $query, 'term_taxonomy_id' );
775         }
776
777         /**
778          * Transforms a single query, from one field to another.
779          *
780          * @since 3.2.0
781          *
782          * @param array &$query The single query
783          * @param string $resulting_field The resulting field
784          */
785         public function transform_query( &$query, $resulting_field ) {
786                 global $wpdb;
787
788                 if ( empty( $query['terms'] ) )
789                         return;
790
791                 if ( $query['field'] == $resulting_field )
792                         return;
793
794                 $resulting_field = sanitize_key( $resulting_field );
795
796                 switch ( $query['field'] ) {
797                         case 'slug':
798                         case 'name':
799                                 $terms = "'" . implode( "','", array_map( 'sanitize_title_for_query', $query['terms'] ) ) . "'";
800                                 $terms = $wpdb->get_col( "
801                                         SELECT $wpdb->term_taxonomy.$resulting_field
802                                         FROM $wpdb->term_taxonomy
803                                         INNER JOIN $wpdb->terms USING (term_id)
804                                         WHERE taxonomy = '{$query['taxonomy']}'
805                                         AND $wpdb->terms.{$query['field']} IN ($terms)
806                                 " );
807                                 break;
808                         case 'term_taxonomy_id':
809                                 $terms = implode( ',', array_map( 'intval', $query['terms'] ) );
810                                 $terms = $wpdb->get_col( "
811                                         SELECT $resulting_field
812                                         FROM $wpdb->term_taxonomy
813                                         WHERE term_taxonomy_id IN ($terms)
814                                 " );
815                                 break;
816                         default:
817                                 $terms = implode( ',', array_map( 'intval', $query['terms'] ) );
818                                 $terms = $wpdb->get_col( "
819                                         SELECT $resulting_field
820                                         FROM $wpdb->term_taxonomy
821                                         WHERE taxonomy = '{$query['taxonomy']}'
822                                         AND term_id IN ($terms)
823                                 " );
824                 }
825
826                 if ( 'AND' == $query['operator'] && count( $terms ) < count( $query['terms'] ) ) {
827                         $query = new WP_Error( 'Inexistent terms' );
828                         return;
829                 }
830
831                 $query['terms'] = $terms;
832                 $query['field'] = $resulting_field;
833         }
834 }
835
836 /**
837  * Get all Term data from database by Term ID.
838  *
839  * The usage of the get_term function is to apply filters to a term object. It
840  * is possible to get a term object from the database before applying the
841  * filters.
842  *
843  * $term ID must be part of $taxonomy, to get from the database. Failure, might
844  * be able to be captured by the hooks. Failure would be the same value as $wpdb
845  * returns for the get_row method.
846  *
847  * There are two hooks, one is specifically for each term, named 'get_term', and
848  * the second is for the taxonomy name, 'term_$taxonomy'. Both hooks gets the
849  * term object, and the taxonomy name as parameters. Both hooks are expected to
850  * return a Term object.
851  *
852  * 'get_term' hook - Takes two parameters the term Object and the taxonomy name.
853  * Must return term object. Used in get_term() as a catch-all filter for every
854  * $term.
855  *
856  * 'get_$taxonomy' hook - Takes two parameters the term Object and the taxonomy
857  * name. Must return term object. $taxonomy will be the taxonomy name, so for
858  * example, if 'category', it would be 'get_category' as the filter name. Useful
859  * for custom taxonomies or plugging into default taxonomies.
860  *
861  * @package WordPress
862  * @subpackage Taxonomy
863  * @since 2.3.0
864  *
865  * @uses $wpdb
866  * @uses sanitize_term() Cleanses the term based on $filter context before returning.
867  * @see sanitize_term_field() The $context param lists the available values for get_term_by() $filter param.
868  *
869  * @param int|object $term If integer, will get from database. If object will apply filters and return $term.
870  * @param string $taxonomy Taxonomy name that $term is part of.
871  * @param string $output Constant OBJECT, ARRAY_A, or ARRAY_N
872  * @param string $filter Optional, default is raw or no WordPress defined filter will applied.
873  * @return mixed|null|WP_Error Term Row from database. Will return null if $term is empty. If taxonomy does not
874  * exist then WP_Error will be returned.
875  */
876 function get_term($term, $taxonomy, $output = OBJECT, $filter = 'raw') {
877         global $wpdb;
878         $null = null;
879
880         if ( empty($term) ) {
881                 $error = new WP_Error('invalid_term', __('Empty Term'));
882                 return $error;
883         }
884
885         if ( ! taxonomy_exists($taxonomy) ) {
886                 $error = new WP_Error('invalid_taxonomy', __('Invalid taxonomy'));
887                 return $error;
888         }
889
890         if ( is_object($term) && empty($term->filter) ) {
891                 wp_cache_add($term->term_id, $term, $taxonomy);
892                 $_term = $term;
893         } else {
894                 if ( is_object($term) )
895                         $term = $term->term_id;
896                 if ( !$term = (int) $term )
897                         return $null;
898                 if ( ! $_term = wp_cache_get($term, $taxonomy) ) {
899                         $_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) );
900                         if ( ! $_term )
901                                 return $null;
902                         wp_cache_add($term, $_term, $taxonomy);
903                 }
904         }
905
906         $_term = apply_filters('get_term', $_term, $taxonomy);
907         $_term = apply_filters("get_$taxonomy", $_term, $taxonomy);
908         $_term = sanitize_term($_term, $taxonomy, $filter);
909
910         if ( $output == OBJECT ) {
911                 return $_term;
912         } elseif ( $output == ARRAY_A ) {
913                 $__term = get_object_vars($_term);
914                 return $__term;
915         } elseif ( $output == ARRAY_N ) {
916                 $__term = array_values(get_object_vars($_term));
917                 return $__term;
918         } else {
919                 return $_term;
920         }
921 }
922
923 /**
924  * Get all Term data from database by Term field and data.
925  *
926  * Warning: $value is not escaped for 'name' $field. You must do it yourself, if
927  * required.
928  *
929  * The default $field is 'id', therefore it is possible to also use null for
930  * field, but not recommended that you do so.
931  *
932  * If $value does not exist, the return value will be false. If $taxonomy exists
933  * and $field and $value combinations exist, the Term will be returned.
934  *
935  * @package WordPress
936  * @subpackage Taxonomy
937  * @since 2.3.0
938  *
939  * @uses $wpdb
940  * @uses sanitize_term() Cleanses the term based on $filter context before returning.
941  * @see sanitize_term_field() The $context param lists the available values for get_term_by() $filter param.
942  *
943  * @param string $field Either 'slug', 'name', or 'id'
944  * @param string|int $value Search for this term value
945  * @param string $taxonomy Taxonomy Name
946  * @param string $output Constant OBJECT, ARRAY_A, or ARRAY_N
947  * @param string $filter Optional, default is raw or no WordPress defined filter will applied.
948  * @return mixed Term Row from database. Will return false if $taxonomy does not exist or $term was not found.
949  */
950 function get_term_by($field, $value, $taxonomy, $output = OBJECT, $filter = 'raw') {
951         global $wpdb;
952
953         if ( ! taxonomy_exists($taxonomy) )
954                 return false;
955
956         if ( 'slug' == $field ) {
957                 $field = 't.slug';
958                 $value = sanitize_title($value);
959                 if ( empty($value) )
960                         return false;
961         } else if ( 'name' == $field ) {
962                 // Assume already escaped
963                 $value = wp_unslash($value);
964                 $field = 't.name';
965         } else {
966                 $term = get_term( (int) $value, $taxonomy, $output, $filter);
967                 if ( is_wp_error( $term ) )
968                         $term = false;
969                 return $term;
970         }
971
972         $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) );
973         if ( !$term )
974                 return false;
975
976         wp_cache_add($term->term_id, $term, $taxonomy);
977
978         $term = apply_filters('get_term', $term, $taxonomy);
979         $term = apply_filters("get_$taxonomy", $term, $taxonomy);
980         $term = sanitize_term($term, $taxonomy, $filter);
981
982         if ( $output == OBJECT ) {
983                 return $term;
984         } elseif ( $output == ARRAY_A ) {
985                 return get_object_vars($term);
986         } elseif ( $output == ARRAY_N ) {
987                 return array_values(get_object_vars($term));
988         } else {
989                 return $term;
990         }
991 }
992
993 /**
994  * Merge all term children into a single array of their IDs.
995  *
996  * This recursive function will merge all of the children of $term into the same
997  * array of term IDs. Only useful for taxonomies which are hierarchical.
998  *
999  * Will return an empty array if $term does not exist in $taxonomy.
1000  *
1001  * @package WordPress
1002  * @subpackage Taxonomy
1003  * @since 2.3.0
1004  *
1005  * @uses $wpdb
1006  * @uses _get_term_hierarchy()
1007  * @uses get_term_children() Used to get the children of both $taxonomy and the parent $term
1008  *
1009  * @param string $term_id ID of Term to get children
1010  * @param string $taxonomy Taxonomy Name
1011  * @return array|WP_Error List of Term Objects. WP_Error returned if $taxonomy does not exist
1012  */
1013 function get_term_children( $term_id, $taxonomy ) {
1014         if ( ! taxonomy_exists($taxonomy) )
1015                 return new WP_Error('invalid_taxonomy', __('Invalid taxonomy'));
1016
1017         $term_id = intval( $term_id );
1018
1019         $terms = _get_term_hierarchy($taxonomy);
1020
1021         if ( ! isset($terms[$term_id]) )
1022                 return array();
1023
1024         $children = $terms[$term_id];
1025
1026         foreach ( (array) $terms[$term_id] as $child ) {
1027                 if ( isset($terms[$child]) )
1028                         $children = array_merge($children, get_term_children($child, $taxonomy));
1029         }
1030
1031         return $children;
1032 }
1033
1034 /**
1035  * Get sanitized Term field.
1036  *
1037  * Does checks for $term, based on the $taxonomy. The function is for contextual
1038  * reasons and for simplicity of usage. See sanitize_term_field() for more
1039  * information.
1040  *
1041  * @package WordPress
1042  * @subpackage Taxonomy
1043  * @since 2.3.0
1044  *
1045  * @uses sanitize_term_field() Passes the return value in sanitize_term_field on success.
1046  *
1047  * @param string $field Term field to fetch
1048  * @param int $term Term ID
1049  * @param string $taxonomy Taxonomy Name
1050  * @param string $context Optional, default is display. Look at sanitize_term_field() for available options.
1051  * @return mixed Will return an empty string if $term is not an object or if $field is not set in $term.
1052  */
1053 function get_term_field( $field, $term, $taxonomy, $context = 'display' ) {
1054         $term = (int) $term;
1055         $term = get_term( $term, $taxonomy );
1056         if ( is_wp_error($term) )
1057                 return $term;
1058
1059         if ( !is_object($term) )
1060                 return '';
1061
1062         if ( !isset($term->$field) )
1063                 return '';
1064
1065         return sanitize_term_field($field, $term->$field, $term->term_id, $taxonomy, $context);
1066 }
1067
1068 /**
1069  * Sanitizes Term for editing.
1070  *
1071  * Return value is sanitize_term() and usage is for sanitizing the term for
1072  * editing. Function is for contextual and simplicity.
1073  *
1074  * @package WordPress
1075  * @subpackage Taxonomy
1076  * @since 2.3.0
1077  *
1078  * @uses sanitize_term() Passes the return value on success
1079  *
1080  * @param int|object $id Term ID or Object
1081  * @param string $taxonomy Taxonomy Name
1082  * @return mixed|null|WP_Error Will return empty string if $term is not an object.
1083  */
1084 function get_term_to_edit( $id, $taxonomy ) {
1085         $term = get_term( $id, $taxonomy );
1086
1087         if ( is_wp_error($term) )
1088                 return $term;
1089
1090         if ( !is_object($term) )
1091                 return '';
1092
1093         return sanitize_term($term, $taxonomy, 'edit');
1094 }
1095
1096 /**
1097  * Retrieve the terms in a given taxonomy or list of taxonomies.
1098  *
1099  * You can fully inject any customizations to the query before it is sent, as
1100  * well as control the output with a filter.
1101  *
1102  * The 'get_terms' filter will be called when the cache has the term and will
1103  * pass the found term along with the array of $taxonomies and array of $args.
1104  * This filter is also called before the array of terms is passed and will pass
1105  * the array of terms, along with the $taxonomies and $args.
1106  *
1107  * The 'list_terms_exclusions' filter passes the compiled exclusions along with
1108  * the $args.
1109  *
1110  * The 'get_terms_orderby' filter passes the ORDER BY clause for the query
1111  * along with the $args array.
1112  *
1113  * The 'get_terms_fields' filter passes the fields for the SELECT query
1114  * along with the $args array.
1115  *
1116  * The list of arguments that $args can contain, which will overwrite the defaults:
1117  *
1118  * orderby - Default is 'name'. Can be name, count, term_group, slug or nothing
1119  * (will use term_id), Passing a custom value other than these will cause it to
1120  * order based on the custom value.
1121  *
1122  * order - Default is ASC. Can use DESC.
1123  *
1124  * hide_empty - Default is true. Will not return empty terms, which means
1125  * terms whose count is 0 according to the given taxonomy.
1126  *
1127  * exclude - Default is an empty array. An array, comma- or space-delimited string
1128  * of term ids to exclude from the return array. If 'include' is non-empty,
1129  * 'exclude' is ignored.
1130  *
1131  * exclude_tree - Default is an empty array. An array, comma- or space-delimited
1132  * string of term ids to exclude from the return array, along with all of their
1133  * descendant terms according to the primary taxonomy. If 'include' is non-empty,
1134  * 'exclude_tree' is ignored.
1135  *
1136  * include - Default is an empty array. An array, comma- or space-delimited string
1137  * of term ids to include in the return array.
1138  *
1139  * number - The maximum number of terms to return. Default is to return them all.
1140  *
1141  * offset - The number by which to offset the terms query.
1142  *
1143  * fields - Default is 'all', which returns an array of term objects.
1144  * If 'fields' is 'ids' or 'names', returns an array of
1145  * integers or strings, respectively.
1146  *
1147  * slug - Returns terms whose "slug" matches this value. Default is empty string.
1148  *
1149  * hierarchical - Whether to include terms that have non-empty descendants
1150  * (even if 'hide_empty' is set to true).
1151  *
1152  * search - Returned terms' names will contain the value of 'search',
1153  * case-insensitive. Default is an empty string.
1154  *
1155  * name__like - Returned terms' names will begin with the value of 'name__like',
1156  * case-insensitive. Default is empty string.
1157  *
1158  * The argument 'pad_counts', if set to true will include the quantity of a term's
1159  * children in the quantity of each term's "count" object variable.
1160  *
1161  * The 'get' argument, if set to 'all' instead of its default empty string,
1162  * returns terms regardless of ancestry or whether the terms are empty.
1163  *
1164  * The 'child_of' argument, when used, should be set to the integer of a term ID. Its default
1165  * is 0. If set to a non-zero value, all returned terms will be descendants
1166  * of that term according to the given taxonomy. Hence 'child_of' is set to 0
1167  * if more than one taxonomy is passed in $taxonomies, because multiple taxonomies
1168  * make term ancestry ambiguous.
1169  *
1170  * The 'parent' argument, when used, should be set to the integer of a term ID. Its default is
1171  * the empty string '', which has a different meaning from the integer 0.
1172  * If set to an integer value, all returned terms will have as an immediate
1173  * ancestor the term whose ID is specified by that integer according to the given taxonomy.
1174  * The 'parent' argument is different from 'child_of' in that a term X is considered a 'parent'
1175  * of term Y only if term X is the father of term Y, not its grandfather or great-grandfather, etc.
1176  *
1177  * The 'cache_domain' argument enables a unique cache key to be produced when this query is stored
1178  * in object cache. For instance, if you are using one of this function's filters to modify the
1179  * query (such as 'terms_clauses'), setting 'cache_domain' to a unique value will not overwrite
1180  * the cache for similar queries. Default value is 'core'.
1181  *
1182  * @package WordPress
1183  * @subpackage Taxonomy
1184  * @since 2.3.0
1185  *
1186  * @uses $wpdb
1187  * @uses wp_parse_args() Merges the defaults with those defined by $args and allows for strings.
1188  *
1189  * @param string|array $taxonomies Taxonomy name or list of Taxonomy names
1190  * @param string|array $args The values of what to search for when returning terms
1191  * @return array|WP_Error List of Term Objects and their children. Will return WP_Error, if any of $taxonomies do not exist.
1192  */
1193 function get_terms($taxonomies, $args = '') {
1194         global $wpdb;
1195         $empty_array = array();
1196
1197         $single_taxonomy = ! is_array( $taxonomies ) || 1 === count( $taxonomies );
1198         if ( ! is_array( $taxonomies ) )
1199                 $taxonomies = array( $taxonomies );
1200
1201         foreach ( $taxonomies as $taxonomy ) {
1202                 if ( ! taxonomy_exists($taxonomy) ) {
1203                         $error = new WP_Error('invalid_taxonomy', __('Invalid taxonomy'));
1204                         return $error;
1205                 }
1206         }
1207
1208         $defaults = array('orderby' => 'name', 'order' => 'ASC',
1209                 'hide_empty' => true, 'exclude' => array(), 'exclude_tree' => array(), 'include' => array(),
1210                 'number' => '', 'fields' => 'all', 'slug' => '', 'parent' => '',
1211                 'hierarchical' => true, 'child_of' => 0, 'get' => '', 'name__like' => '',
1212                 'pad_counts' => false, 'offset' => '', 'search' => '', 'cache_domain' => 'core' );
1213         $args = wp_parse_args( $args, $defaults );
1214         $args['number'] = absint( $args['number'] );
1215         $args['offset'] = absint( $args['offset'] );
1216         if ( !$single_taxonomy || !is_taxonomy_hierarchical($taxonomies[0]) ||
1217                 '' !== $args['parent'] ) {
1218                 $args['child_of'] = 0;
1219                 $args['hierarchical'] = false;
1220                 $args['pad_counts'] = false;
1221         }
1222
1223         if ( 'all' == $args['get'] ) {
1224                 $args['child_of'] = 0;
1225                 $args['hide_empty'] = 0;
1226                 $args['hierarchical'] = false;
1227                 $args['pad_counts'] = false;
1228         }
1229
1230         $args = apply_filters( 'get_terms_args', $args, $taxonomies );
1231
1232         extract($args, EXTR_SKIP);
1233
1234         if ( $child_of ) {
1235                 $hierarchy = _get_term_hierarchy($taxonomies[0]);
1236                 if ( !isset($hierarchy[$child_of]) )
1237                         return $empty_array;
1238         }
1239
1240         if ( $parent ) {
1241                 $hierarchy = _get_term_hierarchy($taxonomies[0]);
1242                 if ( !isset($hierarchy[$parent]) )
1243                         return $empty_array;
1244         }
1245
1246         // $args can be whatever, only use the args defined in defaults to compute the key
1247         $filter_key = ( has_filter('list_terms_exclusions') ) ? serialize($GLOBALS['wp_filter']['list_terms_exclusions']) : '';
1248         $key = md5( serialize( compact(array_keys($defaults)) ) . serialize( $taxonomies ) . $filter_key );
1249         $last_changed = wp_cache_get( 'last_changed', 'terms' );
1250         if ( ! $last_changed ) {
1251                 $last_changed = microtime();
1252                 wp_cache_set( 'last_changed', $last_changed, 'terms' );
1253         }
1254         $cache_key = "get_terms:$key:$last_changed";
1255         $cache = wp_cache_get( $cache_key, 'terms' );
1256         if ( false !== $cache ) {
1257                 $cache = apply_filters('get_terms', $cache, $taxonomies, $args);
1258                 return $cache;
1259         }
1260
1261         $_orderby = strtolower($orderby);
1262         if ( 'count' == $_orderby )
1263                 $orderby = 'tt.count';
1264         else if ( 'name' == $_orderby )
1265                 $orderby = 't.name';
1266         else if ( 'slug' == $_orderby )
1267                 $orderby = 't.slug';
1268         else if ( 'term_group' == $_orderby )
1269                 $orderby = 't.term_group';
1270         else if ( 'none' == $_orderby )
1271                 $orderby = '';
1272         elseif ( empty($_orderby) || 'id' == $_orderby )
1273                 $orderby = 't.term_id';
1274         else
1275                 $orderby = 't.name';
1276
1277         $orderby = apply_filters( 'get_terms_orderby', $orderby, $args );
1278
1279         if ( !empty($orderby) )
1280                 $orderby = "ORDER BY $orderby";
1281         else
1282                 $order = '';
1283
1284         $order = strtoupper( $order );
1285         if ( '' !== $order && !in_array( $order, array( 'ASC', 'DESC' ) ) )
1286                 $order = 'ASC';
1287
1288         $where = "tt.taxonomy IN ('" . implode("', '", $taxonomies) . "')";
1289         $inclusions = '';
1290         if ( !empty($include) ) {
1291                 $exclude = '';
1292                 $exclude_tree = '';
1293                 $interms = wp_parse_id_list($include);
1294                 foreach ( $interms as $interm ) {
1295                         if ( empty($inclusions) )
1296                                 $inclusions = ' AND ( t.term_id = ' . intval($interm) . ' ';
1297                         else
1298                                 $inclusions .= ' OR t.term_id = ' . intval($interm) . ' ';
1299                 }
1300         }
1301
1302         if ( !empty($inclusions) )
1303                 $inclusions .= ')';
1304         $where .= $inclusions;
1305
1306         $exclusions = '';
1307         if ( !empty( $exclude_tree ) ) {
1308                 $excluded_trunks = wp_parse_id_list($exclude_tree);
1309                 foreach ( $excluded_trunks as $extrunk ) {
1310                         $excluded_children = (array) get_terms($taxonomies[0], array('child_of' => intval($extrunk), 'fields' => 'ids', 'hide_empty' => 0));
1311                         $excluded_children[] = $extrunk;
1312                         foreach( $excluded_children as $exterm ) {
1313                                 if ( empty($exclusions) )
1314                                         $exclusions = ' AND ( t.term_id <> ' . intval($exterm) . ' ';
1315                                 else
1316                                         $exclusions .= ' AND t.term_id <> ' . intval($exterm) . ' ';
1317                         }
1318                 }
1319         }
1320
1321         if ( !empty($exclude) ) {
1322                 $exterms = wp_parse_id_list($exclude);
1323                 foreach ( $exterms as $exterm ) {
1324                         if ( empty($exclusions) )
1325                                 $exclusions = ' AND ( t.term_id <> ' . intval($exterm) . ' ';
1326                         else
1327                                 $exclusions .= ' AND t.term_id <> ' . intval($exterm) . ' ';
1328                 }
1329         }
1330
1331         if ( !empty($exclusions) )
1332                 $exclusions .= ')';
1333         $exclusions = apply_filters('list_terms_exclusions', $exclusions, $args );
1334         $where .= $exclusions;
1335
1336         if ( !empty($slug) ) {
1337                 $slug = sanitize_title($slug);
1338                 $where .= " AND t.slug = '$slug'";
1339         }
1340
1341         if ( !empty($name__like) ) {
1342                 $name__like = like_escape( $name__like );
1343                 $where .= $wpdb->prepare( " AND t.name LIKE %s", $name__like . '%' );
1344         }
1345
1346         if ( '' !== $parent ) {
1347                 $parent = (int) $parent;
1348                 $where .= " AND tt.parent = '$parent'";
1349         }
1350
1351         if ( $hide_empty && !$hierarchical )
1352                 $where .= ' AND tt.count > 0';
1353
1354         // don't limit the query results when we have to descend the family tree
1355         if ( $number && ! $hierarchical && ! $child_of && '' === $parent ) {
1356                 if ( $offset )
1357                         $limits = 'LIMIT ' . $offset . ',' . $number;
1358                 else
1359                         $limits = 'LIMIT ' . $number;
1360         } else {
1361                 $limits = '';
1362         }
1363
1364         if ( !empty($search) ) {
1365                 $search = like_escape($search);
1366                 $where .= $wpdb->prepare( " AND (t.name LIKE %s)", '%' . $search . '%');
1367         }
1368
1369         $selects = array();
1370         switch ( $fields ) {
1371                 case 'all':
1372                         $selects = array('t.*', 'tt.*');
1373                         break;
1374                 case 'ids':
1375                 case 'id=>parent':
1376                         $selects = array('t.term_id', 'tt.parent', 'tt.count');
1377                         break;
1378                 case 'names':
1379                         $selects = array('t.term_id', 'tt.parent', 'tt.count', 't.name');
1380                         break;
1381                 case 'count':
1382                         $orderby = '';
1383                         $order = '';
1384                         $selects = array('COUNT(*)');
1385         }
1386
1387         $_fields = $fields;
1388
1389         $fields = implode(', ', apply_filters( 'get_terms_fields', $selects, $args ));
1390
1391         $join = "INNER JOIN $wpdb->term_taxonomy AS tt ON t.term_id = tt.term_id";
1392
1393         $pieces = array( 'fields', 'join', 'where', 'orderby', 'order', 'limits' );
1394         $clauses = apply_filters( 'terms_clauses', compact( $pieces ), $taxonomies, $args );
1395         foreach ( $pieces as $piece )
1396                 $$piece = isset( $clauses[ $piece ] ) ? $clauses[ $piece ] : '';
1397
1398         $query = "SELECT $fields FROM $wpdb->terms AS t $join WHERE $where $orderby $order $limits";
1399
1400         $fields = $_fields;
1401
1402         if ( 'count' == $fields ) {
1403                 $term_count = $wpdb->get_var($query);
1404                 return $term_count;
1405         }
1406
1407         $terms = $wpdb->get_results($query);
1408         if ( 'all' == $fields ) {
1409                 update_term_cache($terms);
1410         }
1411
1412         if ( empty($terms) ) {
1413                 wp_cache_add( $cache_key, array(), 'terms', DAY_IN_SECONDS );
1414                 $terms = apply_filters('get_terms', array(), $taxonomies, $args);
1415                 return $terms;
1416         }
1417
1418         if ( $child_of ) {
1419                 $children = _get_term_hierarchy($taxonomies[0]);
1420                 if ( ! empty($children) )
1421                         $terms = _get_term_children($child_of, $terms, $taxonomies[0]);
1422         }
1423
1424         // Update term counts to include children.
1425         if ( $pad_counts && 'all' == $fields )
1426                 _pad_term_counts($terms, $taxonomies[0]);
1427
1428         // Make sure we show empty categories that have children.
1429         if ( $hierarchical && $hide_empty && is_array($terms) ) {
1430                 foreach ( $terms as $k => $term ) {
1431                         if ( ! $term->count ) {
1432                                 $children = _get_term_children($term->term_id, $terms, $taxonomies[0]);
1433                                 if ( is_array($children) )
1434                                         foreach ( $children as $child )
1435                                                 if ( $child->count )
1436                                                         continue 2;
1437
1438                                 // It really is empty
1439                                 unset($terms[$k]);
1440                         }
1441                 }
1442         }
1443         reset ( $terms );
1444
1445         $_terms = array();
1446         if ( 'id=>parent' == $fields ) {
1447                 while ( $term = array_shift($terms) )
1448                         $_terms[$term->term_id] = $term->parent;
1449                 $terms = $_terms;
1450         } elseif ( 'ids' == $fields ) {
1451                 while ( $term = array_shift($terms) )
1452                         $_terms[] = $term->term_id;
1453                 $terms = $_terms;
1454         } elseif ( 'names' == $fields ) {
1455                 while ( $term = array_shift($terms) )
1456                         $_terms[] = $term->name;
1457                 $terms = $_terms;
1458         }
1459
1460         if ( $number && is_array( $terms ) && count( $terms ) > $number )
1461                 $terms = array_slice( $terms, $offset, $number );
1462
1463         wp_cache_add( $cache_key, $terms, 'terms', DAY_IN_SECONDS );
1464
1465         $terms = apply_filters('get_terms', $terms, $taxonomies, $args);
1466         return $terms;
1467 }
1468
1469 /**
1470  * Check if Term exists.
1471  *
1472  * Formerly is_term(), introduced in 2.3.0.
1473  *
1474  * @package WordPress
1475  * @subpackage Taxonomy
1476  * @since 3.0.0
1477  *
1478  * @uses $wpdb
1479  *
1480  * @param int|string $term The term to check
1481  * @param string $taxonomy The taxonomy name to use
1482  * @param int $parent ID of parent term under which to confine the exists search.
1483  * @return mixed Returns 0 if the term does not exist. Returns the term ID if no taxonomy is specified
1484  *      and the term ID exists. Returns an array of the term ID and the taxonomy if the pairing exists.
1485  */
1486 function term_exists($term, $taxonomy = '', $parent = 0) {
1487         global $wpdb;
1488
1489         $select = "SELECT term_id FROM $wpdb->terms as t WHERE ";
1490         $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 ";
1491
1492         if ( is_int($term) ) {
1493                 if ( 0 == $term )
1494                         return 0;
1495                 $where = 't.term_id = %d';
1496                 if ( !empty($taxonomy) )
1497                         return $wpdb->get_row( $wpdb->prepare( $tax_select . $where . " AND tt.taxonomy = %s", $term, $taxonomy ), ARRAY_A );
1498                 else
1499                         return $wpdb->get_var( $wpdb->prepare( $select . $where, $term ) );
1500         }
1501
1502         $term = trim( wp_unslash( $term ) );
1503
1504         if ( '' === $slug = sanitize_title($term) )
1505                 return 0;
1506
1507         $where = 't.slug = %s';
1508         $else_where = 't.name = %s';
1509         $where_fields = array($slug);
1510         $else_where_fields = array($term);
1511         if ( !empty($taxonomy) ) {
1512                 $parent = (int) $parent;
1513                 if ( $parent > 0 ) {
1514                         $where_fields[] = $parent;
1515                         $else_where_fields[] = $parent;
1516                         $where .= ' AND tt.parent = %d';
1517                         $else_where .= ' AND tt.parent = %d';
1518                 }
1519
1520                 $where_fields[] = $taxonomy;
1521                 $else_where_fields[] = $taxonomy;
1522
1523                 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) )
1524                         return $result;
1525
1526                 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);
1527         }
1528
1529         if ( $result = $wpdb->get_var( $wpdb->prepare("SELECT term_id FROM $wpdb->terms as t WHERE $where", $where_fields) ) )
1530                 return $result;
1531
1532         return $wpdb->get_var( $wpdb->prepare("SELECT term_id FROM $wpdb->terms as t WHERE $else_where", $else_where_fields) );
1533 }
1534
1535 /**
1536  * Check if a term is an ancestor of another term.
1537  *
1538  * You can use either an id or the term object for both parameters.
1539  *
1540  * @since 3.4.0
1541  *
1542  * @param int|object $term1 ID or object to check if this is the parent term.
1543  * @param int|object $term2 The child term.
1544  * @param string $taxonomy Taxonomy name that $term1 and $term2 belong to.
1545  * @return bool Whether $term2 is child of $term1
1546  */
1547 function term_is_ancestor_of( $term1, $term2, $taxonomy ) {
1548         if ( ! isset( $term1->term_id ) )
1549                 $term1 = get_term( $term1, $taxonomy );
1550         if ( ! isset( $term2->parent ) )
1551                 $term2 = get_term( $term2, $taxonomy );
1552
1553         if ( empty( $term1->term_id ) || empty( $term2->parent ) )
1554                 return false;
1555         if ( $term2->parent == $term1->term_id )
1556                 return true;
1557
1558         return term_is_ancestor_of( $term1, get_term( $term2->parent, $taxonomy ), $taxonomy );
1559 }
1560
1561 /**
1562  * Sanitize Term all fields.
1563  *
1564  * Relies on sanitize_term_field() to sanitize the term. The difference is that
1565  * this function will sanitize <strong>all</strong> fields. The context is based
1566  * on sanitize_term_field().
1567  *
1568  * The $term is expected to be either an array or an object.
1569  *
1570  * @package WordPress
1571  * @subpackage Taxonomy
1572  * @since 2.3.0
1573  *
1574  * @uses sanitize_term_field Used to sanitize all fields in a term
1575  *
1576  * @param array|object $term The term to check
1577  * @param string $taxonomy The taxonomy name to use
1578  * @param string $context Default is 'display'.
1579  * @return array|object Term with all fields sanitized
1580  */
1581 function sanitize_term($term, $taxonomy, $context = 'display') {
1582
1583         if ( 'raw' == $context )
1584                 return $term;
1585
1586         $fields = array('term_id', 'name', 'description', 'slug', 'count', 'parent', 'term_group');
1587
1588         $do_object = false;
1589         if ( is_object($term) )
1590                 $do_object = true;
1591
1592         $term_id = $do_object ? $term->term_id : (isset($term['term_id']) ? $term['term_id'] : 0);
1593
1594         foreach ( (array) $fields as $field ) {
1595                 if ( $do_object ) {
1596                         if ( isset($term->$field) )
1597                                 $term->$field = sanitize_term_field($field, $term->$field, $term_id, $taxonomy, $context);
1598                 } else {
1599                         if ( isset($term[$field]) )
1600                                 $term[$field] = sanitize_term_field($field, $term[$field], $term_id, $taxonomy, $context);
1601                 }
1602         }
1603
1604         if ( $do_object )
1605                 $term->filter = $context;
1606         else
1607                 $term['filter'] = $context;
1608
1609         return $term;
1610 }
1611
1612 /**
1613  * Cleanse the field value in the term based on the context.
1614  *
1615  * Passing a term field value through the function should be assumed to have
1616  * cleansed the value for whatever context the term field is going to be used.
1617  *
1618  * If no context or an unsupported context is given, then default filters will
1619  * be applied.
1620  *
1621  * There are enough filters for each context to support a custom filtering
1622  * without creating your own filter function. Simply create a function that
1623  * hooks into the filter you need.
1624  *
1625  * @package WordPress
1626  * @subpackage Taxonomy
1627  * @since 2.3.0
1628  *
1629  * @uses $wpdb
1630  *
1631  * @param string $field Term field to sanitize
1632  * @param string $value Search for this term value
1633  * @param int $term_id Term ID
1634  * @param string $taxonomy Taxonomy Name
1635  * @param string $context Either edit, db, display, attribute, or js.
1636  * @return mixed sanitized field
1637  */
1638 function sanitize_term_field($field, $value, $term_id, $taxonomy, $context) {
1639         if ( 'parent' == $field  || 'term_id' == $field || 'count' == $field || 'term_group' == $field ) {
1640                 $value = (int) $value;
1641                 if ( $value < 0 )
1642                         $value = 0;
1643         }
1644
1645         if ( 'raw' == $context )
1646                 return $value;
1647
1648         if ( 'edit' == $context ) {
1649                 $value = apply_filters("edit_term_{$field}", $value, $term_id, $taxonomy);
1650                 $value = apply_filters("edit_{$taxonomy}_{$field}", $value, $term_id);
1651                 if ( 'description' == $field )
1652                         $value = esc_html($value); // textarea_escaped
1653                 else
1654                         $value = esc_attr($value);
1655         } else if ( 'db' == $context ) {
1656                 $value = apply_filters("pre_term_{$field}", $value, $taxonomy);
1657                 $value = apply_filters("pre_{$taxonomy}_{$field}", $value);
1658                 // Back compat filters
1659                 if ( 'slug' == $field )
1660                         $value = apply_filters('pre_category_nicename', $value);
1661
1662         } else if ( 'rss' == $context ) {
1663                 $value = apply_filters("term_{$field}_rss", $value, $taxonomy);
1664                 $value = apply_filters("{$taxonomy}_{$field}_rss", $value);
1665         } else {
1666                 // Use display filters by default.
1667                 $value = apply_filters("term_{$field}", $value, $term_id, $taxonomy, $context);
1668                 $value = apply_filters("{$taxonomy}_{$field}", $value, $term_id, $context);
1669         }
1670
1671         if ( 'attribute' == $context )
1672                 $value = esc_attr($value);
1673         else if ( 'js' == $context )
1674                 $value = esc_js($value);
1675
1676         return $value;
1677 }
1678
1679 /**
1680  * Count how many terms are in Taxonomy.
1681  *
1682  * Default $args is 'hide_empty' which can be 'hide_empty=true' or array('hide_empty' => true).
1683  *
1684  * @package WordPress
1685  * @subpackage Taxonomy
1686  * @since 2.3.0
1687  *
1688  * @uses get_terms()
1689  * @uses wp_parse_args() Turns strings into arrays and merges defaults into an array.
1690  *
1691  * @param string $taxonomy Taxonomy name
1692  * @param array|string $args Overwrite defaults. See get_terms()
1693  * @return int|WP_Error How many terms are in $taxonomy. WP_Error if $taxonomy does not exist.
1694  */
1695 function wp_count_terms( $taxonomy, $args = array() ) {
1696         $defaults = array('hide_empty' => false);
1697         $args = wp_parse_args($args, $defaults);
1698
1699         // backwards compatibility
1700         if ( isset($args['ignore_empty']) ) {
1701                 $args['hide_empty'] = $args['ignore_empty'];
1702                 unset($args['ignore_empty']);
1703         }
1704
1705         $args['fields'] = 'count';
1706
1707         return get_terms($taxonomy, $args);
1708 }
1709
1710 /**
1711  * Will unlink the object from the taxonomy or taxonomies.
1712  *
1713  * Will remove all relationships between the object and any terms in
1714  * a particular taxonomy or taxonomies. Does not remove the term or
1715  * taxonomy itself.
1716  *
1717  * @package WordPress
1718  * @subpackage Taxonomy
1719  * @since 2.3.0
1720  * @uses wp_remove_object_terms()
1721  *
1722  * @param int $object_id The term Object Id that refers to the term
1723  * @param string|array $taxonomies List of Taxonomy Names or single Taxonomy name.
1724  */
1725 function wp_delete_object_term_relationships( $object_id, $taxonomies ) {
1726         $object_id = (int) $object_id;
1727
1728         if ( !is_array($taxonomies) )
1729                 $taxonomies = array($taxonomies);
1730
1731         foreach ( (array) $taxonomies as $taxonomy ) {
1732                 $term_ids = wp_get_object_terms( $object_id, $taxonomy, array( 'fields' => 'ids' ) );
1733                 $term_ids = array_map( 'intval', $term_ids );
1734                 wp_remove_object_terms( $object_id, $term_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 ID, term taxonomy ID, and deleted term object. 'delete_term'
1756  *      also gets taxonomy as the third 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 = wp_unslash($name);
2066         $description = wp_unslash($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 wp_remove_object_terms()
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_tt_ids = array_diff( $old_tt_ids, $tt_ids );
2219
2220                 if ( $delete_tt_ids ) {
2221                         $in_delete_tt_ids = "'" . implode( "', '", $delete_tt_ids ) . "'";
2222                         $delete_term_ids = $wpdb->get_col( $wpdb->prepare( "SELECT tt.term_id FROM $wpdb->term_taxonomy AS tt WHERE tt.taxonomy = %s AND tt.term_taxonomy_id IN ($in_delete_tt_ids)", $taxonomy ) );
2223                         $delete_term_ids = array_map( 'intval', $delete_term_ids );
2224
2225                         $remove = wp_remove_object_terms( $object_id, $delete_term_ids, $taxonomy );
2226                         if ( is_wp_error( $remove ) ) {
2227                                 return $remove;
2228                         }
2229                 }
2230         }
2231
2232         $t = get_taxonomy($taxonomy);
2233         if ( ! $append && isset($t->sort) && $t->sort ) {
2234                 $values = array();
2235                 $term_order = 0;
2236                 $final_tt_ids = wp_get_object_terms($object_id, $taxonomy, array('fields' => 'tt_ids'));
2237                 foreach ( $tt_ids as $tt_id )
2238                         if ( in_array($tt_id, $final_tt_ids) )
2239                                 $values[] = $wpdb->prepare( "(%d, %d, %d)", $object_id, $tt_id, ++$term_order);
2240                 if ( $values )
2241                         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)" ) )
2242                                 return new WP_Error( 'db_insert_error', __( 'Could not insert term relationship into the database' ), $wpdb->last_error );
2243         }
2244
2245         wp_cache_delete( $object_id, $taxonomy . '_relationships' );
2246
2247         do_action('set_object_terms', $object_id, $terms, $tt_ids, $taxonomy, $append, $old_tt_ids);
2248         return $tt_ids;
2249 }
2250
2251 /**
2252  * Add term(s) associated with a given object.
2253  *
2254  * @package WordPress
2255  * @subpackage Taxonomy
2256  * @since 3.6
2257  * @uses wp_set_object_terms()
2258  *
2259  * @param int $object_id The ID of the object to which the terms will be added.
2260  * @param array|int|string $terms The slug(s) or ID(s) of the term(s) to add.
2261  * @param array|string $taxonomy Taxonomy name.
2262  * @return array|WP_Error Affected Term IDs
2263  */
2264 function wp_add_object_terms( $object_id, $terms, $taxonomy ) {
2265         return wp_set_object_terms( $object_id, $terms, $taxonomy, true );
2266 }
2267
2268 /**
2269  * Remove term(s) associated with a given object.
2270  *
2271  * @package WordPress
2272  * @subpackage Taxonomy
2273  * @since 3.6
2274  * @uses $wpdb
2275  *
2276  * @uses apply_filters() Calls 'delete_term_relationships' hook with object_id and tt_ids as parameters.
2277  * @uses apply_filters() Calls 'deleted_term_relationships' hook with object_id and tt_ids as parameters.
2278  *
2279  * @param int $object_id The ID of the object from which the terms will be removed.
2280  * @param array|int|string $terms The slug(s) or ID(s) of the term(s) to remove.
2281  * @param array|string $taxonomy Taxonomy name.
2282  * @return bool|WP_Error True on success, false or WP_Error on failure.
2283  */
2284 function wp_remove_object_terms( $object_id, $terms, $taxonomy ) {
2285         global $wpdb;
2286
2287         $object_id = (int) $object_id;
2288
2289         if ( ! taxonomy_exists( $taxonomy ) ) {
2290                 return new WP_Error( 'invalid_taxonomy', __( 'Invalid Taxonomy' ) );
2291         }
2292
2293         if ( ! is_array( $terms ) ) {
2294                 $terms = array( $terms );
2295         }
2296
2297         $tt_ids = array();
2298
2299         foreach ( (array) $terms as $term ) {
2300                 if ( ! strlen( trim( $term ) ) ) {
2301                         continue;
2302                 }
2303
2304                 if ( ! $term_info = term_exists( $term, $taxonomy ) ) {
2305                         // Skip if a non-existent term ID is passed.
2306                         if ( is_int( $term ) ) {
2307                                 continue;
2308                         }
2309                 }
2310
2311                 if ( is_wp_error( $term_info ) ) {
2312                         return $term_info;
2313                 }
2314
2315                 $tt_ids[] = $term_info['term_taxonomy_id'];
2316         }
2317
2318         if ( $tt_ids ) {
2319                 $in_tt_ids = "'" . implode( "', '", $tt_ids ) . "'";
2320                 do_action( 'delete_term_relationships', $object_id, $tt_ids );
2321                 $deleted = $wpdb->query( $wpdb->prepare( "DELETE FROM $wpdb->term_relationships WHERE object_id = %d AND term_taxonomy_id IN ($in_tt_ids)", $object_id ) );
2322                 do_action( 'deleted_term_relationships', $object_id, $tt_ids );
2323                 wp_update_term_count( $tt_ids, $taxonomy );
2324
2325                 return (bool) $deleted;
2326         }
2327
2328         return false;
2329 }
2330
2331 /**
2332  * Will make slug unique, if it isn't already.
2333  *
2334  * The $slug has to be unique global to every taxonomy, meaning that one
2335  * taxonomy term can't have a matching slug with another taxonomy term. Each
2336  * slug has to be globally unique for every taxonomy.
2337  *
2338  * The way this works is that if the taxonomy that the term belongs to is
2339  * hierarchical and has a parent, it will append that parent to the $slug.
2340  *
2341  * If that still doesn't return an unique slug, then it try to append a number
2342  * until it finds a number that is truly unique.
2343  *
2344  * The only purpose for $term is for appending a parent, if one exists.
2345  *
2346  * @package WordPress
2347  * @subpackage Taxonomy
2348  * @since 2.3.0
2349  * @uses $wpdb
2350  *
2351  * @param string $slug The string that will be tried for a unique slug
2352  * @param object $term The term object that the $slug will belong too
2353  * @return string Will return a true unique slug.
2354  */
2355 function wp_unique_term_slug($slug, $term) {
2356         global $wpdb;
2357
2358         if ( ! term_exists( $slug ) )
2359                 return $slug;
2360
2361         // If the taxonomy supports hierarchy and the term has a parent, make the slug unique
2362         // by incorporating parent slugs.
2363         if ( is_taxonomy_hierarchical($term->taxonomy) && !empty($term->parent) ) {
2364                 $the_parent = $term->parent;
2365                 while ( ! empty($the_parent) ) {
2366                         $parent_term = get_term($the_parent, $term->taxonomy);
2367                         if ( is_wp_error($parent_term) || empty($parent_term) )
2368                                 break;
2369                         $slug .= '-' . $parent_term->slug;
2370                         if ( ! term_exists( $slug ) )
2371                                 return $slug;
2372
2373                         if ( empty($parent_term->parent) )
2374                                 break;
2375                         $the_parent = $parent_term->parent;
2376                 }
2377         }
2378
2379         // If we didn't get a unique slug, try appending a number to make it unique.
2380         if ( !empty($args['term_id']) )
2381                 $query = $wpdb->prepare( "SELECT slug FROM $wpdb->terms WHERE slug = %s AND term_id != %d", $slug, $args['term_id'] );
2382         else
2383                 $query = $wpdb->prepare( "SELECT slug FROM $wpdb->terms WHERE slug = %s", $slug );
2384
2385         if ( $wpdb->get_var( $query ) ) {
2386                 $num = 2;
2387                 do {
2388                         $alt_slug = $slug . "-$num";
2389                         $num++;
2390                         $slug_check = $wpdb->get_var( $wpdb->prepare( "SELECT slug FROM $wpdb->terms WHERE slug = %s", $alt_slug ) );
2391                 } while ( $slug_check );
2392                 $slug = $alt_slug;
2393         }
2394
2395         return $slug;
2396 }
2397
2398 /**
2399  * Update term based on arguments provided.
2400  *
2401  * The $args will indiscriminately override all values with the same field name.
2402  * Care must be taken to not override important information need to update or
2403  * update will fail (or perhaps create a new term, neither would be acceptable).
2404  *
2405  * Defaults will set 'alias_of', 'description', 'parent', and 'slug' if not
2406  * defined in $args already.
2407  *
2408  * 'alias_of' will create a term group, if it doesn't already exist, and update
2409  * it for the $term.
2410  *
2411  * If the 'slug' argument in $args is missing, then the 'name' in $args will be
2412  * used. It should also be noted that if you set 'slug' and it isn't unique then
2413  * a WP_Error will be passed back. If you don't pass any slug, then a unique one
2414  * will be created for you.
2415  *
2416  * For what can be overrode in $args, check the term scheme can contain and stay
2417  * away from the term keys.
2418  *
2419  * @package WordPress
2420  * @subpackage Taxonomy
2421  * @since 2.3.0
2422  *
2423  * @uses $wpdb
2424  * @uses do_action() Will call both 'edit_term' and 'edit_$taxonomy' twice.
2425  * @uses apply_filters() Will call the 'term_id_filter' filter and pass the term
2426  *      id and taxonomy id.
2427  *
2428  * @param int $term_id The ID of the term
2429  * @param string $taxonomy The context in which to relate the term to the object.
2430  * @param array|string $args Overwrite term field values
2431  * @return array|WP_Error Returns Term ID and Taxonomy Term ID
2432  */
2433 function wp_update_term( $term_id, $taxonomy, $args = array() ) {
2434         global $wpdb;
2435
2436         if ( ! taxonomy_exists($taxonomy) )
2437                 return new WP_Error('invalid_taxonomy', __('Invalid taxonomy'));
2438
2439         $term_id = (int) $term_id;
2440
2441         // First, get all of the original args
2442         $term = get_term ($term_id, $taxonomy, ARRAY_A);
2443
2444         if ( is_wp_error( $term ) )
2445                 return $term;
2446
2447         // Escape data pulled from DB.
2448         $term = wp_slash($term);
2449
2450         // Merge old and new args with new args overwriting old ones.
2451         $args = array_merge($term, $args);
2452
2453         $defaults = array( 'alias_of' => '', 'description' => '', 'parent' => 0, 'slug' => '');
2454         $args = wp_parse_args($args, $defaults);
2455         $args = sanitize_term($args, $taxonomy, 'db');
2456         extract($args, EXTR_SKIP);
2457
2458         // expected_slashed ($name)
2459         $name = wp_unslash($name);
2460         $description = wp_unslash($description);
2461
2462         if ( '' == trim($name) )
2463                 return new WP_Error('empty_term_name', __('A name is required for this term'));
2464
2465         $empty_slug = false;
2466         if ( empty($slug) ) {
2467                 $empty_slug = true;
2468                 $slug = sanitize_title($name);
2469         }
2470
2471         if ( $alias_of ) {
2472                 $alias = $wpdb->get_row( $wpdb->prepare( "SELECT term_id, term_group FROM $wpdb->terms WHERE slug = %s", $alias_of) );
2473                 if ( $alias->term_group ) {
2474                         // The alias we want is already in a group, so let's use that one.
2475                         $term_group = $alias->term_group;
2476                 } else {
2477                         // The alias isn't in a group, so let's create a new one and firstly add the alias term to it.
2478                         $term_group = $wpdb->get_var("SELECT MAX(term_group) FROM $wpdb->terms") + 1;
2479                         do_action( 'edit_terms', $alias->term_id );
2480                         $wpdb->update( $wpdb->terms, compact('term_group'), array( 'term_id' => $alias->term_id ) );
2481                         do_action( 'edited_terms', $alias->term_id );
2482                 }
2483         }
2484
2485         // Check $parent to see if it will cause a hierarchy loop
2486         $parent = apply_filters( 'wp_update_term_parent', $parent, $term_id, $taxonomy, compact( array_keys( $args ) ), $args );
2487
2488         // Check for duplicate slug
2489         $id = $wpdb->get_var( $wpdb->prepare( "SELECT term_id FROM $wpdb->terms WHERE slug = %s", $slug ) );
2490         if ( $id && ($id != $term_id) ) {
2491                 // If an empty slug was passed or the parent changed, reset the slug to something unique.
2492                 // Otherwise, bail.
2493                 if ( $empty_slug || ( $parent != $term['parent']) )
2494                         $slug = wp_unique_term_slug($slug, (object) $args);
2495                 else
2496                         return new WP_Error('duplicate_term_slug', sprintf(__('The slug &#8220;%s&#8221; is already in use by another term'), $slug));
2497         }
2498         do_action( 'edit_terms', $term_id );
2499         $wpdb->update($wpdb->terms, compact( 'name', 'slug', 'term_group' ), compact( 'term_id' ) );
2500         if ( empty($slug) ) {
2501                 $slug = sanitize_title($name, $term_id);
2502                 $wpdb->update( $wpdb->terms, compact( 'slug' ), compact( 'term_id' ) );
2503         }
2504         do_action( 'edited_terms', $term_id );
2505
2506         $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) );
2507         do_action( 'edit_term_taxonomy', $tt_id, $taxonomy );
2508         $wpdb->update( $wpdb->term_taxonomy, compact( 'term_id', 'taxonomy', 'description', 'parent' ), array( 'term_taxonomy_id' => $tt_id ) );
2509         do_action( 'edited_term_taxonomy', $tt_id, $taxonomy );
2510
2511         do_action("edit_term", $term_id, $tt_id, $taxonomy);
2512         do_action("edit_$taxonomy", $term_id, $tt_id);
2513
2514         $term_id = apply_filters('term_id_filter', $term_id, $tt_id);
2515
2516         clean_term_cache($term_id, $taxonomy);
2517
2518         do_action("edited_term", $term_id, $tt_id, $taxonomy);
2519         do_action("edited_$taxonomy", $term_id, $tt_id);
2520
2521         return array('term_id' => $term_id, 'term_taxonomy_id' => $tt_id);
2522 }
2523
2524 /**
2525  * Enable or disable term counting.
2526  *
2527  * @since 2.5.0
2528  *
2529  * @param bool $defer Optional. Enable if true, disable if false.
2530  * @return bool Whether term counting is enabled or disabled.
2531  */
2532 function wp_defer_term_counting($defer=null) {
2533         static $_defer = false;
2534
2535         if ( is_bool($defer) ) {
2536                 $_defer = $defer;
2537                 // flush any deferred counts
2538                 if ( !$defer )
2539                         wp_update_term_count( null, null, true );
2540         }
2541
2542         return $_defer;
2543 }
2544
2545 /**
2546  * Updates the amount of terms in taxonomy.
2547  *
2548  * If there is a taxonomy callback applied, then it will be called for updating
2549  * the count.
2550  *
2551  * The default action is to count what the amount of terms have the relationship
2552  * of term ID. Once that is done, then update the database.
2553  *
2554  * @package WordPress
2555  * @subpackage Taxonomy
2556  * @since 2.3.0
2557  * @uses $wpdb
2558  *
2559  * @param int|array $terms The term_taxonomy_id of the terms
2560  * @param string $taxonomy The context of the term.
2561  * @return bool If no terms will return false, and if successful will return true.
2562  */
2563 function wp_update_term_count( $terms, $taxonomy, $do_deferred=false ) {
2564         static $_deferred = array();
2565
2566         if ( $do_deferred ) {
2567                 foreach ( (array) array_keys($_deferred) as $tax ) {
2568                         wp_update_term_count_now( $_deferred[$tax], $tax );
2569                         unset( $_deferred[$tax] );
2570                 }
2571         }
2572
2573         if ( empty($terms) )
2574                 return false;
2575
2576         if ( !is_array($terms) )
2577                 $terms = array($terms);
2578
2579         if ( wp_defer_term_counting() ) {
2580                 if ( !isset($_deferred[$taxonomy]) )
2581                         $_deferred[$taxonomy] = array();
2582                 $_deferred[$taxonomy] = array_unique( array_merge($_deferred[$taxonomy], $terms) );
2583                 return true;
2584         }
2585
2586         return wp_update_term_count_now( $terms, $taxonomy );
2587 }
2588
2589 /**
2590  * Perform term count update immediately.
2591  *
2592  * @since 2.5.0
2593  *
2594  * @param array $terms The term_taxonomy_id of terms to update.
2595  * @param string $taxonomy The context of the term.
2596  * @return bool Always true when complete.
2597  */
2598 function wp_update_term_count_now( $terms, $taxonomy ) {
2599         global $wpdb;
2600
2601         $terms = array_map('intval', $terms);
2602
2603         $taxonomy = get_taxonomy($taxonomy);
2604         if ( !empty($taxonomy->update_count_callback) ) {
2605                 call_user_func($taxonomy->update_count_callback, $terms, $taxonomy);
2606         } else {
2607                 $object_types = (array) $taxonomy->object_type;
2608                 foreach ( $object_types as &$object_type ) {
2609                         if ( 0 === strpos( $object_type, 'attachment:' ) )
2610                                 list( $object_type ) = explode( ':', $object_type );
2611                 }
2612
2613                 if ( $object_types == array_filter( $object_types, 'post_type_exists' ) ) {
2614                         // Only post types are attached to this taxonomy
2615                         _update_post_term_count( $terms, $taxonomy );
2616                 } else {
2617                         // Default count updater
2618                         _update_generic_term_count( $terms, $taxonomy );
2619                 }
2620         }
2621
2622         clean_term_cache($terms, '', false);
2623
2624         return true;
2625 }
2626
2627 //
2628 // Cache
2629 //
2630
2631 /**
2632  * Removes the taxonomy relationship to terms from the cache.
2633  *
2634  * Will remove the entire taxonomy relationship containing term $object_id. The
2635  * term IDs have to exist within the taxonomy $object_type for the deletion to
2636  * take place.
2637  *
2638  * @package WordPress
2639  * @subpackage Taxonomy
2640  * @since 2.3.0
2641  *
2642  * @see get_object_taxonomies() for more on $object_type
2643  * @uses do_action() Will call action hook named, 'clean_object_term_cache' after completion.
2644  *      Passes, function params in same order.
2645  *
2646  * @param int|array $object_ids Single or list of term object ID(s)
2647  * @param array|string $object_type The taxonomy object type
2648  */
2649 function clean_object_term_cache($object_ids, $object_type) {
2650         if ( !is_array($object_ids) )
2651                 $object_ids = array($object_ids);
2652
2653         $taxonomies = get_object_taxonomies( $object_type );
2654
2655         foreach ( $object_ids as $id )
2656                 foreach ( $taxonomies as $taxonomy )
2657                         wp_cache_delete($id, "{$taxonomy}_relationships");
2658
2659         do_action('clean_object_term_cache', $object_ids, $object_type);
2660 }
2661
2662 /**
2663  * Will remove all of the term ids from the cache.
2664  *
2665  * @package WordPress
2666  * @subpackage Taxonomy
2667  * @since 2.3.0
2668  * @uses $wpdb
2669  *
2670  * @param int|array $ids Single or list of Term IDs
2671  * @param string $taxonomy Can be empty and will assume tt_ids, else will use for context.
2672  * @param bool $clean_taxonomy Whether to clean taxonomy wide caches (true), or just individual term object caches (false). Default is true.
2673  */
2674 function clean_term_cache($ids, $taxonomy = '', $clean_taxonomy = true) {
2675         global $wpdb;
2676         static $cleaned = array();
2677
2678         if ( !is_array($ids) )
2679                 $ids = array($ids);
2680
2681         $taxonomies = array();
2682         // If no taxonomy, assume tt_ids.
2683         if ( empty($taxonomy) ) {
2684                 $tt_ids = array_map('intval', $ids);
2685                 $tt_ids = implode(', ', $tt_ids);
2686                 $terms = $wpdb->get_results("SELECT term_id, taxonomy FROM $wpdb->term_taxonomy WHERE term_taxonomy_id IN ($tt_ids)");
2687                 $ids = array();
2688                 foreach ( (array) $terms as $term ) {
2689                         $taxonomies[] = $term->taxonomy;
2690                         $ids[] = $term->term_id;
2691                         wp_cache_delete($term->term_id, $term->taxonomy);
2692                 }
2693                 $taxonomies = array_unique($taxonomies);
2694         } else {
2695                 $taxonomies = array($taxonomy);
2696                 foreach ( $taxonomies as $taxonomy ) {
2697                         foreach ( $ids as $id ) {
2698                                 wp_cache_delete($id, $taxonomy);
2699                         }
2700                 }
2701         }
2702
2703         foreach ( $taxonomies as $taxonomy ) {
2704                 if ( isset($cleaned[$taxonomy]) )
2705                         continue;
2706                 $cleaned[$taxonomy] = true;
2707
2708                 if ( $clean_taxonomy ) {
2709                         wp_cache_delete('all_ids', $taxonomy);
2710                         wp_cache_delete('get', $taxonomy);
2711                         delete_option("{$taxonomy}_children");
2712                         // Regenerate {$taxonomy}_children
2713                         _get_term_hierarchy($taxonomy);
2714                 }
2715
2716                 do_action('clean_term_cache', $ids, $taxonomy);
2717         }
2718
2719         wp_cache_set( 'last_changed', microtime(), 'terms' );
2720 }
2721
2722 /**
2723  * Retrieves the taxonomy relationship to the term object id.
2724  *
2725  * @package WordPress
2726  * @subpackage Taxonomy
2727  * @since 2.3.0
2728  *
2729  * @uses wp_cache_get() Retrieves taxonomy relationship from cache
2730  *
2731  * @param int|array $id Term object ID
2732  * @param string $taxonomy Taxonomy Name
2733  * @return bool|array Empty array if $terms found, but not $taxonomy. False if nothing is in cache for $taxonomy and $id.
2734  */
2735 function get_object_term_cache($id, $taxonomy) {
2736         $cache = wp_cache_get($id, "{$taxonomy}_relationships");
2737         return $cache;
2738 }
2739
2740 /**
2741  * Updates the cache for Term ID(s).
2742  *
2743  * Will only update the cache for terms not already cached.
2744  *
2745  * The $object_ids expects that the ids be separated by commas, if it is a
2746  * string.
2747  *
2748  * It should be noted that update_object_term_cache() is very time extensive. It
2749  * is advised that the function is not called very often or at least not for a
2750  * lot of terms that exist in a lot of taxonomies. The amount of time increases
2751  * for each term and it also increases for each taxonomy the term belongs to.
2752  *
2753  * @package WordPress
2754  * @subpackage Taxonomy
2755  * @since 2.3.0
2756  * @uses wp_get_object_terms() Used to get terms from the database to update
2757  *
2758  * @param string|array $object_ids Single or list of term object ID(s)
2759  * @param array|string $object_type The taxonomy object type
2760  * @return null|bool Null value is given with empty $object_ids. False if
2761  */
2762 function update_object_term_cache($object_ids, $object_type) {
2763         if ( empty($object_ids) )
2764                 return;
2765
2766         if ( !is_array($object_ids) )
2767                 $object_ids = explode(',', $object_ids);
2768
2769         $object_ids = array_map('intval', $object_ids);
2770
2771         $taxonomies = get_object_taxonomies($object_type);
2772
2773         $ids = array();
2774         foreach ( (array) $object_ids as $id ) {
2775                 foreach ( $taxonomies as $taxonomy ) {
2776                         if ( false === wp_cache_get($id, "{$taxonomy}_relationships") ) {
2777                                 $ids[] = $id;
2778                                 break;
2779                         }
2780                 }
2781         }
2782
2783         if ( empty( $ids ) )
2784                 return false;
2785
2786         $terms = wp_get_object_terms($ids, $taxonomies, array('fields' => 'all_with_object_id'));
2787
2788         $object_terms = array();
2789         foreach ( (array) $terms as $term )
2790                 $object_terms[$term->object_id][$term->taxonomy][$term->term_id] = $term;
2791
2792         foreach ( $ids as $id ) {
2793                 foreach ( $taxonomies as $taxonomy ) {
2794                         if ( ! isset($object_terms[$id][$taxonomy]) ) {
2795                                 if ( !isset($object_terms[$id]) )
2796                                         $object_terms[$id] = array();
2797                                 $object_terms[$id][$taxonomy] = array();
2798                         }
2799                 }
2800         }
2801
2802         foreach ( $object_terms as $id => $value ) {
2803                 foreach ( $value as $taxonomy => $terms ) {
2804                         wp_cache_add( $id, $terms, "{$taxonomy}_relationships" );
2805                 }
2806         }
2807 }
2808
2809 /**
2810  * Updates Terms to Taxonomy in cache.
2811  *
2812  * @package WordPress
2813  * @subpackage Taxonomy
2814  * @since 2.3.0
2815  *
2816  * @param array $terms List of Term objects to change
2817  * @param string $taxonomy Optional. Update Term to this taxonomy in cache
2818  */
2819 function update_term_cache($terms, $taxonomy = '') {
2820         foreach ( (array) $terms as $term ) {
2821                 $term_taxonomy = $taxonomy;
2822                 if ( empty($term_taxonomy) )
2823                         $term_taxonomy = $term->taxonomy;
2824
2825                 wp_cache_add($term->term_id, $term, $term_taxonomy);
2826         }
2827 }
2828
2829 //
2830 // Private
2831 //
2832
2833 /**
2834  * Retrieves children of taxonomy as Term IDs.
2835  *
2836  * @package WordPress
2837  * @subpackage Taxonomy
2838  * @access private
2839  * @since 2.3.0
2840  *
2841  * @uses update_option() Stores all of the children in "$taxonomy_children"
2842  *       option. That is the name of the taxonomy, immediately followed by '_children'.
2843  *
2844  * @param string $taxonomy Taxonomy Name
2845  * @return array Empty if $taxonomy isn't hierarchical or returns children as Term IDs.
2846  */
2847 function _get_term_hierarchy($taxonomy) {
2848         if ( !is_taxonomy_hierarchical($taxonomy) )
2849                 return array();
2850         $children = get_option("{$taxonomy}_children");
2851
2852         if ( is_array($children) )
2853                 return $children;
2854         $children = array();
2855         $terms = get_terms($taxonomy, array('get' => 'all', 'orderby' => 'id', 'fields' => 'id=>parent'));
2856         foreach ( $terms as $term_id => $parent ) {
2857                 if ( $parent > 0 )
2858                         $children[$parent][] = $term_id;
2859         }
2860         update_option("{$taxonomy}_children", $children);
2861
2862         return $children;
2863 }
2864
2865 /**
2866  * Get the subset of $terms that are descendants of $term_id.
2867  *
2868  * If $terms is an array of objects, then _get_term_children returns an array of objects.
2869  * If $terms is an array of IDs, then _get_term_children returns an array of IDs.
2870  *
2871  * @package WordPress
2872  * @subpackage Taxonomy
2873  * @access private
2874  * @since 2.3.0
2875  *
2876  * @param int $term_id The ancestor term: all returned terms should be descendants of $term_id.
2877  * @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.
2878  * @param string $taxonomy The taxonomy which determines the hierarchy of the terms.
2879  * @return array The subset of $terms that are descendants of $term_id.
2880  */
2881 function _get_term_children($term_id, $terms, $taxonomy) {
2882         $empty_array = array();
2883         if ( empty($terms) )
2884                 return $empty_array;
2885
2886         $term_list = array();
2887         $has_children = _get_term_hierarchy($taxonomy);
2888
2889         if  ( ( 0 != $term_id ) && ! isset($has_children[$term_id]) )
2890                 return $empty_array;
2891
2892         foreach ( (array) $terms as $term ) {
2893                 $use_id = false;
2894                 if ( !is_object($term) ) {
2895                         $term = get_term($term, $taxonomy);
2896                         if ( is_wp_error( $term ) )
2897                                 return $term;
2898                         $use_id = true;
2899                 }
2900
2901                 if ( $term->term_id == $term_id )
2902                         continue;
2903
2904                 if ( $term->parent == $term_id ) {
2905                         if ( $use_id )
2906                                 $term_list[] = $term->term_id;
2907                         else
2908                                 $term_list[] = $term;
2909
2910                         if ( !isset($has_children[$term->term_id]) )
2911                                 continue;
2912
2913                         if ( $children = _get_term_children($term->term_id, $terms, $taxonomy) )
2914                                 $term_list = array_merge($term_list, $children);
2915                 }
2916         }
2917
2918         return $term_list;
2919 }
2920
2921 /**
2922  * Add count of children to parent count.
2923  *
2924  * Recalculates term counts by including items from child terms. Assumes all
2925  * relevant children are already in the $terms argument.
2926  *
2927  * @package WordPress
2928  * @subpackage Taxonomy
2929  * @access private
2930  * @since 2.3.0
2931  * @uses $wpdb
2932  *
2933  * @param array $terms List of Term IDs
2934  * @param string $taxonomy Term Context
2935  * @return null Will break from function if conditions are not met.
2936  */
2937 function _pad_term_counts(&$terms, $taxonomy) {
2938         global $wpdb;
2939
2940         // This function only works for hierarchical taxonomies like post categories.
2941         if ( !is_taxonomy_hierarchical( $taxonomy ) )
2942                 return;
2943
2944         $term_hier = _get_term_hierarchy($taxonomy);
2945
2946         if ( empty($term_hier) )
2947                 return;
2948
2949         $term_items = array();
2950
2951         foreach ( (array) $terms as $key => $term ) {
2952                 $terms_by_id[$term->term_id] = & $terms[$key];
2953                 $term_ids[$term->term_taxonomy_id] = $term->term_id;
2954         }
2955
2956         // Get the object and term ids and stick them in a lookup table
2957         $tax_obj = get_taxonomy($taxonomy);
2958         $object_types = esc_sql($tax_obj->object_type);
2959         $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'");
2960         foreach ( $results as $row ) {
2961                 $id = $term_ids[$row->term_taxonomy_id];
2962                 $term_items[$id][$row->object_id] = isset($term_items[$id][$row->object_id]) ? ++$term_items[$id][$row->object_id] : 1;
2963         }
2964
2965         // Touch every ancestor's lookup row for each post in each term
2966         foreach ( $term_ids as $term_id ) {
2967                 $child = $term_id;
2968                 while ( !empty( $terms_by_id[$child] ) && $parent = $terms_by_id[$child]->parent ) {
2969                         if ( !empty( $term_items[$term_id] ) )
2970                                 foreach ( $term_items[$term_id] as $item_id => $touches ) {
2971                                         $term_items[$parent][$item_id] = isset($term_items[$parent][$item_id]) ? ++$term_items[$parent][$item_id]: 1;
2972                                 }
2973                         $child = $parent;
2974                 }
2975         }
2976
2977         // Transfer the touched cells
2978         foreach ( (array) $term_items as $id => $items )
2979                 if ( isset($terms_by_id[$id]) )
2980                         $terms_by_id[$id]->count = count($items);
2981 }
2982
2983 //
2984 // Default callbacks
2985 //
2986
2987 /**
2988  * Will update term count based on object types of the current taxonomy.
2989  *
2990  * Private function for the default callback for post_tag and category
2991  * taxonomies.
2992  *
2993  * @package WordPress
2994  * @subpackage Taxonomy
2995  * @access private
2996  * @since 2.3.0
2997  * @uses $wpdb
2998  *
2999  * @param array $terms List of Term taxonomy IDs
3000  * @param object $taxonomy Current taxonomy object of terms
3001  */
3002 function _update_post_term_count( $terms, $taxonomy ) {
3003         global $wpdb;
3004
3005         $object_types = (array) $taxonomy->object_type;
3006
3007         foreach ( $object_types as &$object_type )
3008                 list( $object_type ) = explode( ':', $object_type );
3009
3010         $object_types = array_unique( $object_types );
3011
3012         if ( false !== ( $check_attachments = array_search( 'attachment', $object_types ) ) ) {
3013                 unset( $object_types[ $check_attachments ] );
3014                 $check_attachments = true;
3015         }
3016
3017         if ( $object_types )
3018                 $object_types = esc_sql( array_filter( $object_types, 'post_type_exists' ) );
3019
3020         foreach ( (array) $terms as $term ) {
3021                 $count = 0;
3022
3023                 // Attachments can be 'inherit' status, we need to base count off the parent's status if so
3024                 if ( $check_attachments )
3025                         $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 ) );
3026
3027                 if ( $object_types )
3028                         $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 ) );
3029
3030                 do_action( 'edit_term_taxonomy', $term, $taxonomy );
3031                 $wpdb->update( $wpdb->term_taxonomy, compact( 'count' ), array( 'term_taxonomy_id' => $term ) );
3032                 do_action( 'edited_term_taxonomy', $term, $taxonomy );
3033         }
3034 }
3035
3036 /**
3037  * Will update term count based on number of objects.
3038  *
3039  * Default callback for the link_category taxonomy.
3040  *
3041  * @package WordPress
3042  * @subpackage Taxonomy
3043  * @since 3.3.0
3044  * @uses $wpdb
3045  *
3046  * @param array $terms List of Term taxonomy IDs
3047  * @param object $taxonomy Current taxonomy object of terms
3048  */
3049 function _update_generic_term_count( $terms, $taxonomy ) {
3050         global $wpdb;
3051
3052         foreach ( (array) $terms as $term ) {
3053                 $count = $wpdb->get_var( $wpdb->prepare( "SELECT COUNT(*) FROM $wpdb->term_relationships WHERE term_taxonomy_id = %d", $term ) );
3054
3055                 do_action( 'edit_term_taxonomy', $term, $taxonomy );
3056                 $wpdb->update( $wpdb->term_taxonomy, compact( 'count' ), array( 'term_taxonomy_id' => $term ) );
3057                 do_action( 'edited_term_taxonomy', $term, $taxonomy );
3058         }
3059 }
3060
3061 /**
3062  * Generates a permalink for a taxonomy term archive.
3063  *
3064  * @since 2.5.0
3065  *
3066  * @uses apply_filters() Calls 'term_link' with term link and term object, and taxonomy parameters.
3067  * @uses apply_filters() For the post_tag Taxonomy, Calls 'tag_link' with tag link and tag ID as parameters.
3068  * @uses apply_filters() For the category Taxonomy, Calls 'category_link' filter on category link and category ID.
3069  *
3070  * @param object|int|string $term
3071  * @param string $taxonomy (optional if $term is object)
3072  * @return string|WP_Error HTML link to taxonomy term archive on success, WP_Error if term does not exist.
3073  */
3074 function get_term_link( $term, $taxonomy = '') {
3075         global $wp_rewrite;
3076
3077         if ( !is_object($term) ) {
3078                 if ( is_int($term) ) {
3079                         $term = get_term($term, $taxonomy);
3080                 } else {
3081                         $term = get_term_by('slug', $term, $taxonomy);
3082                 }
3083         }
3084
3085         if ( !is_object($term) )
3086                 $term = new WP_Error('invalid_term', __('Empty Term'));
3087
3088         if ( is_wp_error( $term ) )
3089                 return $term;
3090
3091         $taxonomy = $term->taxonomy;
3092
3093         $termlink = $wp_rewrite->get_extra_permastruct($taxonomy);
3094
3095         $slug = $term->slug;
3096         $t = get_taxonomy($taxonomy);
3097
3098         if ( empty($termlink) ) {
3099                 if ( 'category' == $taxonomy )
3100                         $termlink = '?cat=' . $term->term_id;
3101                 elseif ( $t->query_var )
3102                         $termlink = "?$t->query_var=$slug";
3103                 else
3104                         $termlink = "?taxonomy=$taxonomy&term=$slug";
3105                 $termlink = home_url($termlink);
3106         } else {
3107                 if ( $t->rewrite['hierarchical'] ) {
3108                         $hierarchical_slugs = array();
3109                         $ancestors = get_ancestors($term->term_id, $taxonomy);
3110                         foreach ( (array)$ancestors as $ancestor ) {
3111                                 $ancestor_term = get_term($ancestor, $taxonomy);
3112                                 $hierarchical_slugs[] = $ancestor_term->slug;
3113                         }
3114                         $hierarchical_slugs = array_reverse($hierarchical_slugs);
3115                         $hierarchical_slugs[] = $slug;
3116                         $termlink = str_replace("%$taxonomy%", implode('/', $hierarchical_slugs), $termlink);
3117                 } else {
3118                         $termlink = str_replace("%$taxonomy%", $slug, $termlink);
3119                 }
3120                 $termlink = home_url( user_trailingslashit($termlink, 'category') );
3121         }
3122         // Back Compat filters.
3123         if ( 'post_tag' == $taxonomy )
3124                 $termlink = apply_filters( 'tag_link', $termlink, $term->term_id );
3125         elseif ( 'category' == $taxonomy )
3126                 $termlink = apply_filters( 'category_link', $termlink, $term->term_id );
3127
3128         return apply_filters('term_link', $termlink, $term, $taxonomy);
3129 }
3130
3131 /**
3132  * Display the taxonomies of a post with available options.
3133  *
3134  * This function can be used within the loop to display the taxonomies for a
3135  * post without specifying the Post ID. You can also use it outside the Loop to
3136  * display the taxonomies for a specific post.
3137  *
3138  * The available defaults are:
3139  * 'post' : default is 0. The post ID to get taxonomies of.
3140  * 'before' : default is empty string. Display before taxonomies list.
3141  * 'sep' : default is empty string. Separate every taxonomy with value in this.
3142  * 'after' : default is empty string. Display this after the taxonomies list.
3143  * 'template' : The template to use for displaying the taxonomy terms.
3144  *
3145  * @since 2.5.0
3146  * @uses get_the_taxonomies()
3147  *
3148  * @param array $args Override the defaults.
3149  */
3150 function the_taxonomies($args = array()) {
3151         $defaults = array(
3152                 'post' => 0,
3153                 'before' => '',
3154                 'sep' => ' ',
3155                 'after' => '',
3156                 'template' => '%s: %l.'
3157         );
3158
3159         $r = wp_parse_args( $args, $defaults );
3160         extract( $r, EXTR_SKIP );
3161
3162         echo $before . join($sep, get_the_taxonomies($post, $r)) . $after;
3163 }
3164
3165 /**
3166  * Retrieve all taxonomies associated with a post.
3167  *
3168  * This function can be used within the loop. It will also return an array of
3169  * the taxonomies with links to the taxonomy and name.
3170  *
3171  * @since 2.5.0
3172  *
3173  * @param int $post Optional. Post ID or will use Global Post ID (in loop).
3174  * @param array $args Override the defaults.
3175  * @return array
3176  */
3177 function get_the_taxonomies($post = 0, $args = array() ) {
3178         $post = get_post( $post );
3179
3180         $args = wp_parse_args( $args, array(
3181                 'template' => '%s: %l.',
3182         ) );
3183         extract( $args, EXTR_SKIP );
3184
3185         $taxonomies = array();
3186
3187         if ( !$post )
3188                 return $taxonomies;
3189
3190         foreach ( get_object_taxonomies($post) as $taxonomy ) {
3191                 $t = (array) get_taxonomy($taxonomy);
3192                 if ( empty($t['label']) )
3193                         $t['label'] = $taxonomy;
3194                 if ( empty($t['args']) )
3195                         $t['args'] = array();
3196                 if ( empty($t['template']) )
3197                         $t['template'] = $template;
3198
3199                 $terms = get_object_term_cache($post->ID, $taxonomy);
3200                 if ( false === $terms )
3201                         $terms = wp_get_object_terms($post->ID, $taxonomy, $t['args']);
3202
3203                 $links = array();
3204
3205                 foreach ( $terms as $term )
3206                         $links[] = "<a href='" . esc_attr( get_term_link($term) ) . "'>$term->name</a>";
3207
3208                 if ( $links )
3209                         $taxonomies[$taxonomy] = wp_sprintf($t['template'], $t['label'], $links, $terms);
3210         }
3211         return $taxonomies;
3212 }
3213
3214 /**
3215  * Retrieve all taxonomies of a post with just the names.
3216  *
3217  * @since 2.5.0
3218  * @uses get_object_taxonomies()
3219  *
3220  * @param int $post Optional. Post ID
3221  * @return array
3222  */
3223 function get_post_taxonomies($post = 0) {
3224         $post = get_post( $post );
3225
3226         return get_object_taxonomies($post);
3227 }
3228
3229 /**
3230  * Determine if the given object is associated with any of the given terms.
3231  *
3232  * The given terms are checked against the object's terms' term_ids, names and slugs.
3233  * Terms given as integers will only be checked against the object's terms' term_ids.
3234  * If no terms are given, determines if object is associated with any terms in the given taxonomy.
3235  *
3236  * @since 2.7.0
3237  * @uses get_object_term_cache()
3238  * @uses wp_get_object_terms()
3239  *
3240  * @param int $object_id ID of the object (post ID, link ID, ...)
3241  * @param string $taxonomy Single taxonomy name
3242  * @param int|string|array $terms Optional. Term term_id, name, slug or array of said
3243  * @return bool|WP_Error. WP_Error on input error.
3244  */
3245 function is_object_in_term( $object_id, $taxonomy, $terms = null ) {
3246         if ( !$object_id = (int) $object_id )
3247                 return new WP_Error( 'invalid_object', __( 'Invalid object ID' ) );
3248
3249         $object_terms = get_object_term_cache( $object_id, $taxonomy );
3250         if ( false === $object_terms )
3251                  $object_terms = wp_get_object_terms( $object_id, $taxonomy );
3252
3253         if ( is_wp_error( $object_terms ) )
3254                 return $object_terms;
3255         if ( empty( $object_terms ) )
3256                 return false;
3257         if ( empty( $terms ) )
3258                 return ( !empty( $object_terms ) );
3259
3260         $terms = (array) $terms;
3261
3262         if ( $ints = array_filter( $terms, 'is_int' ) )
3263                 $strs = array_diff( $terms, $ints );
3264         else
3265                 $strs =& $terms;
3266
3267         foreach ( $object_terms as $object_term ) {
3268                 if ( $ints && in_array( $object_term->term_id, $ints ) ) return true; // If int, check against term_id
3269                 if ( $strs ) {
3270                         if ( in_array( $object_term->term_id, $strs ) ) return true;
3271                         if ( in_array( $object_term->name, $strs ) )    return true;
3272                         if ( in_array( $object_term->slug, $strs ) )    return true;
3273                 }
3274         }
3275
3276         return false;
3277 }
3278
3279 /**
3280  * Determine if the given object type is associated with the given taxonomy.
3281  *
3282  * @since 3.0.0
3283  * @uses get_object_taxonomies()
3284  *
3285  * @param string $object_type Object type string
3286  * @param string $taxonomy Single taxonomy name
3287  * @return bool True if object is associated with the taxonomy, otherwise false.
3288  */
3289 function is_object_in_taxonomy($object_type, $taxonomy) {
3290         $taxonomies = get_object_taxonomies($object_type);
3291
3292         if ( empty($taxonomies) )
3293                 return false;
3294
3295         if ( in_array($taxonomy, $taxonomies) )
3296                 return true;
3297
3298         return false;
3299 }
3300
3301 /**
3302  * Get an array of ancestor IDs for a given object.
3303  *
3304  * @param int $object_id The ID of the object
3305  * @param string $object_type The type of object for which we'll be retrieving ancestors.
3306  * @return array of ancestors from lowest to highest in the hierarchy.
3307  */
3308 function get_ancestors($object_id = 0, $object_type = '') {
3309         $object_id = (int) $object_id;
3310
3311         $ancestors = array();
3312
3313         if ( empty( $object_id ) ) {
3314                 return apply_filters('get_ancestors', $ancestors, $object_id, $object_type);
3315         }
3316
3317         if ( is_taxonomy_hierarchical( $object_type ) ) {
3318                 $term = get_term($object_id, $object_type);
3319                 while ( ! is_wp_error($term) && ! empty( $term->parent ) && ! in_array( $term->parent, $ancestors ) ) {
3320                         $ancestors[] = (int) $term->parent;
3321                         $term = get_term($term->parent, $object_type);
3322                 }
3323         } elseif ( post_type_exists( $object_type ) ) {
3324                 $ancestors = get_post_ancestors($object_id);
3325         }
3326
3327         return apply_filters('get_ancestors', $ancestors, $object_id, $object_type);
3328 }
3329
3330 /**
3331  * Returns the term's parent's term_ID
3332  *
3333  * @since 3.1.0
3334  *
3335  * @param int $term_id
3336  * @param string $taxonomy
3337  *
3338  * @return int|bool false on error
3339  */
3340 function wp_get_term_taxonomy_parent_id( $term_id, $taxonomy ) {
3341         $term = get_term( $term_id, $taxonomy );
3342         if ( !$term || is_wp_error( $term ) )
3343                 return false;
3344         return (int) $term->parent;
3345 }
3346
3347 /**
3348  * Checks the given subset of the term hierarchy for hierarchy loops.
3349  * Prevents loops from forming and breaks those that it finds.
3350  *
3351  * Attached to the wp_update_term_parent filter.
3352  *
3353  * @since 3.1.0
3354  * @uses wp_find_hierarchy_loop()
3355  *
3356  * @param int $parent term_id of the parent for the term we're checking.
3357  * @param int $term_id The term we're checking.
3358  * @param string $taxonomy The taxonomy of the term we're checking.
3359  *
3360  * @return int The new parent for the term.
3361  */
3362 function wp_check_term_hierarchy_for_loops( $parent, $term_id, $taxonomy ) {
3363         // Nothing fancy here - bail
3364         if ( !$parent )
3365                 return 0;
3366
3367         // Can't be its own parent
3368         if ( $parent == $term_id )
3369                 return 0;
3370
3371         // Now look for larger loops
3372
3373         if ( !$loop = wp_find_hierarchy_loop( 'wp_get_term_taxonomy_parent_id', $term_id, $parent, array( $taxonomy ) ) )
3374                 return $parent; // No loop
3375
3376         // Setting $parent to the given value causes a loop
3377         if ( isset( $loop[$term_id] ) )
3378                 return 0;
3379
3380         // There's a loop, but it doesn't contain $term_id. Break the loop.
3381         foreach ( array_keys( $loop ) as $loop_member )
3382                 wp_update_term( $loop_member, $taxonomy, array( 'parent' => 0 ) );
3383
3384         return $parent;
3385 }