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