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