11 // Taxonomy Registration
15 * Creates the initial taxonomies when 'init' action is fired.
17 function create_initial_taxonomies() {
18 register_taxonomy( 'category', 'post', array(
19 'hierarchical' => true,
20 'update_count_callback' => '_update_post_term_count',
28 register_taxonomy( 'post_tag', 'post', array(
29 'hierarchical' => false,
30 'update_count_callback' => '_update_post_term_count',
38 register_taxonomy( 'nav_menu', 'nav_menu_item', array(
39 'hierarchical' => false,
41 'name' => __( 'Navigation Menus' ),
42 'singular_name' => __( 'Navigation Menu' ),
48 'show_in_nav_menus' => false,
51 register_taxonomy( 'link_category', 'link', array(
52 'hierarchical' => false,
54 'name' => __( 'Categories' ),
55 'singular_name' => __( 'Category' ),
56 'update_item' => __( 'Update Category' ),
65 add_action( 'init', 'create_initial_taxonomies', 0 ); // highest priority
68 * Get a list of registered taxonomy objects.
71 * @subpackage Taxonomy
73 * @uses $wp_taxonomies
74 * @see register_taxonomy
76 * @param array $args An array of key => value arguments to match against the taxonomy objects.
77 * @param string $output The type of output to return, either taxonomy 'names' or 'objects'. 'names' is the default.
78 * @param string $operator The logical operation to perform. 'or' means only one element
79 * from the array needs to match; 'and' means all elements must match. The default is 'and'.
80 * @return array A list of taxonomy names or objects
82 function get_taxonomies( $args = array(), $output = 'names', $operator = 'and' ) {
83 global $wp_taxonomies;
85 $field = ('names' == $output) ? 'name' : false;
87 return wp_filter_object_list($wp_taxonomies, $args, $operator, $field);
92 * Return all of the taxonomy names that are of $object_type.
94 * It appears that this function can be used to find all of the names inside of
95 * $wp_taxonomies global variable.
97 * <code><?php $taxonomies = get_object_taxonomies('post'); ?></code> Should
98 * result in <code>Array('category', 'post_tag')</code>
101 * @subpackage Taxonomy
104 * @uses $wp_taxonomies
106 * @param array|string|object $object Name of the type of taxonomy object, or an object (row from posts)
107 * @param string $output The type of output to return, either taxonomy 'names' or 'objects'. 'names' is the default.
108 * @return array The names of all taxonomy of $object_type.
110 function get_object_taxonomies($object, $output = 'names') {
111 global $wp_taxonomies;
113 if ( is_object($object) ) {
114 if ( $object->post_type == 'attachment' )
115 return get_attachment_taxonomies($object);
116 $object = $object->post_type;
119 $object = (array) $object;
121 $taxonomies = array();
122 foreach ( (array) $wp_taxonomies as $tax_name => $tax_obj ) {
123 if ( array_intersect($object, (array) $tax_obj->object_type) ) {
124 if ( 'names' == $output )
125 $taxonomies[] = $tax_name;
127 $taxonomies[ $tax_name ] = $tax_obj;
135 * Retrieves the taxonomy object of $taxonomy.
137 * The get_taxonomy function will first check that the parameter string given
138 * is a taxonomy object and if it is, it will return it.
141 * @subpackage Taxonomy
144 * @uses $wp_taxonomies
145 * @uses taxonomy_exists() Checks whether taxonomy exists
147 * @param string $taxonomy Name of taxonomy object to return
148 * @return object|bool The Taxonomy Object or false if $taxonomy doesn't exist
150 function get_taxonomy( $taxonomy ) {
151 global $wp_taxonomies;
153 if ( ! taxonomy_exists( $taxonomy ) )
156 return $wp_taxonomies[$taxonomy];
160 * Checks that the taxonomy name exists.
162 * Formerly is_taxonomy(), introduced in 2.3.0.
165 * @subpackage Taxonomy
168 * @uses $wp_taxonomies
170 * @param string $taxonomy Name of taxonomy object
171 * @return bool Whether the taxonomy exists.
173 function taxonomy_exists( $taxonomy ) {
174 global $wp_taxonomies;
176 return isset( $wp_taxonomies[$taxonomy] );
180 * Whether the taxonomy object is hierarchical.
182 * Checks to make sure that the taxonomy is an object first. Then Gets the
183 * object, and finally returns the hierarchical value in the object.
185 * A false return value might also mean that the taxonomy does not exist.
188 * @subpackage Taxonomy
191 * @uses taxonomy_exists() Checks whether taxonomy exists
192 * @uses get_taxonomy() Used to get the taxonomy object
194 * @param string $taxonomy Name of taxonomy object
195 * @return bool Whether the taxonomy is hierarchical
197 function is_taxonomy_hierarchical($taxonomy) {
198 if ( ! taxonomy_exists($taxonomy) )
201 $taxonomy = get_taxonomy($taxonomy);
202 return $taxonomy->hierarchical;
206 * Create or modify a taxonomy object. Do not use before init.
208 * A simple function for creating or modifying a taxonomy object based on the
209 * parameters given. The function will accept an array (third optional
210 * parameter), along with strings for the taxonomy name and another string for
213 * Nothing is returned, so expect error maybe or use taxonomy_exists() to check
214 * whether taxonomy exists.
216 * Optional $args contents:
218 * label - Name of the taxonomy shown in the menu. Usually plural. If not set, labels['name'] will be used.
220 * hierarchical - has some defined purpose at other parts of the API and is a
223 * update_count_callback - works much like a hook, in that it will be called
224 * when the count is updated.
226 * rewrite - false to prevent rewrite, or array('slug'=>$slug) to customize
227 * permastruct; default will use $taxonomy as slug.
229 * query_var - false to prevent queries, or string to customize query var
230 * (?$query_var=$term); default will use $taxonomy as query var.
232 * public - If the taxonomy should be publically queryable; //@TODO not implemented.
235 * show_ui - If the WordPress UI admin tags UI should apply to this taxonomy;
236 * defaults to public.
238 * show_in_nav_menus - true makes this taxonomy available for selection in navigation menus.
239 * Defaults to public.
241 * show_tagcloud - false to prevent the taxonomy being listed in the Tag Cloud Widget;
242 * defaults to show_ui which defalts to public.
244 * 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.
247 * @subpackage Taxonomy
249 * @uses $wp_taxonomies Inserts new taxonomy object into the list
250 * @uses $wp_rewrite Adds rewrite tags and permastructs
251 * @uses $wp Adds query vars
253 * @param string $taxonomy Name of taxonomy object
254 * @param array|string $object_type Name of the object type for the taxonomy object.
255 * @param array|string $args See above description for the two keys values.
257 function register_taxonomy( $taxonomy, $object_type, $args = array() ) {
258 global $wp_taxonomies, $wp_rewrite, $wp;
260 if ( ! is_array($wp_taxonomies) )
261 $wp_taxonomies = array();
263 $defaults = array( 'hierarchical' => false,
264 'update_count_callback' => '',
266 'query_var' => $taxonomy,
269 'show_tagcloud' => null,
272 'capabilities' => array(),
273 'show_in_nav_menus' => null,
275 $args = wp_parse_args($args, $defaults);
277 if ( false !== $args['query_var'] && !empty($wp) ) {
278 if ( true === $args['query_var'] )
279 $args['query_var'] = $taxonomy;
280 $args['query_var'] = sanitize_title_with_dashes($args['query_var']);
281 $wp->add_query_var($args['query_var']);
284 if ( false !== $args['rewrite'] && '' != get_option('permalink_structure') ) {
285 $args['rewrite'] = wp_parse_args($args['rewrite'], array(
286 'slug' => sanitize_title_with_dashes($taxonomy),
287 'with_front' => true,
289 $wp_rewrite->add_rewrite_tag("%$taxonomy%", '([^/]+)', $args['query_var'] ? "{$args['query_var']}=" : "taxonomy=$taxonomy&term=");
290 $wp_rewrite->add_permastruct($taxonomy, "{$args['rewrite']['slug']}/%$taxonomy%", $args['rewrite']['with_front']);
293 if ( is_null($args['show_ui']) )
294 $args['show_ui'] = $args['public'];
296 // Whether to show this type in nav-menus.php. Defaults to the setting for public.
297 if ( null === $args['show_in_nav_menus'] )
298 $args['show_in_nav_menus'] = $args['public'];
300 if ( is_null($args['show_tagcloud']) )
301 $args['show_tagcloud'] = $args['show_ui'];
303 $default_caps = array(
304 'manage_terms' => 'manage_categories',
305 'edit_terms' => 'manage_categories',
306 'delete_terms' => 'manage_categories',
307 'assign_terms' => 'edit_posts',
309 $args['cap'] = (object) array_merge( $default_caps, $args['capabilities'] );
310 unset( $args['capabilities'] );
312 $args['name'] = $taxonomy;
313 $args['object_type'] = (array) $object_type;
315 $args['labels'] = get_taxonomy_labels( (object) $args );
316 $args['label'] = $args['labels']->name;
318 $wp_taxonomies[$taxonomy] = (object) $args;
320 // register callback handling for metabox
321 add_filter('wp_ajax_add-'.$taxonomy, '_wp_ajax_add_hierarchical_term');
325 * Builds an object with all taxonomy labels out of a taxonomy object
327 * Accepted keys of the label array in the taxonomy object:
328 * - name - general name for the taxonomy, usually plural. The same as and overriden by $tax->label. Default is Post Tags/Categories
329 * - singular_name - name for one object of this taxonomy. Default is Post Tag/Category
330 * - search_items - Default is Search Tags/Search Categories
331 * - popular_items - This string isn't used on hierarchical taxonomies. Default is Popular Tags
332 * - all_items - Default is All Tags/All Categories
333 * - parent_item - This string isn't used on non-hierarchical taxonomies. In hierarchical ones the default is Parent Category
334 * - parent_item_colon - The same as <code>parent_item</code>, but with colon <code>:</code> in the end
335 * - edit_item - Default is Edit Tag/Edit Category
336 * - update_item - Default is Update Tag/Update Category
337 * - add_new_item - Default is Add New Tag/Add New Category
338 * - new_item_name - Default is New Tag Name/New Category Name
339 * - separate_items_with_commas - This string isn't used on hierarchical taxonomies. Default is "Separate tags with commas," used in the meta box.
340 * - 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.
341 * - 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.
343 * Above, the first default value is for non-hierarchical taxonomies (like tags) and the second one is for hierarchical taxonomies (like categories.)
346 * @param object $tax Taxonomy object
347 * @return object object with all the labels as member variables
350 function get_taxonomy_labels( $tax ) {
351 if ( isset( $tax->helps ) && empty( $tax->labels['separate_items_with_commas'] ) )
352 $tax->labels['separate_items_with_commas'] = $tax->helps;
354 $nohier_vs_hier_defaults = array(
355 'name' => array( _x( 'Post Tags', 'taxonomy general name' ), _x( 'Categories', 'taxonomy general name' ) ),
356 'singular_name' => array( _x( 'Post Tag', 'taxonomy singular name' ), _x( 'Category', 'taxonomy singular name' ) ),
357 'search_items' => array( __( 'Search Tags' ), __( 'Search Categories' ) ),
358 'popular_items' => array( __( 'Popular Tags' ), null ),
359 'all_items' => array( __( 'All Tags' ), __( 'All Categories' ) ),
360 'parent_item' => array( null, __( 'Parent Category' ) ),
361 'parent_item_colon' => array( null, __( 'Parent Category:' ) ),
362 'edit_item' => array( __( 'Edit Tag' ), __( 'Edit Category' ) ),
363 'update_item' => array( __( 'Update Tag' ), __( 'Update Category' ) ),
364 'add_new_item' => array( __( 'Add New Tag' ), __( 'Add New Category' ) ),
365 'new_item_name' => array( __( 'New Tag Name' ), __( 'New Category Name' ) ),
366 'separate_items_with_commas' => array( __( 'Separate tags with commas' ), null ),
367 'add_or_remove_items' => array( __( 'Add or remove tags' ), null ),
368 'choose_from_most_used' => array( __( 'Choose from the most used tags' ), null ),
371 return _get_custom_object_labels( $tax, $nohier_vs_hier_defaults );
375 * Add an already registered taxonomy to an object type.
378 * @subpackage Taxonomy
380 * @uses $wp_taxonomies Modifies taxonomy object
382 * @param string $taxonomy Name of taxonomy object
383 * @param array|string $object_type Name of the object type
384 * @return bool True if successful, false if not
386 function register_taxonomy_for_object_type( $taxonomy, $object_type) {
387 global $wp_taxonomies;
389 if ( !isset($wp_taxonomies[$taxonomy]) )
392 if ( ! get_post_type_object($object_type) )
395 $wp_taxonomies[$taxonomy]->object_type[] = $object_type;
405 * Retrieve object_ids of valid taxonomy and term.
407 * The strings of $taxonomies must exist before this function will continue. On
408 * failure of finding a valid taxonomy, it will return an WP_Error class, kind
409 * of like Exceptions in PHP 5, except you can't catch them. Even so, you can
410 * still test for the WP_Error class and get the error message.
412 * The $terms aren't checked the same as $taxonomies, but still need to exist
413 * for $object_ids to be returned.
415 * It is possible to change the order that object_ids is returned by either
416 * using PHP sort family functions or using the database by using $args with
417 * either ASC or DESC array. The value should be in the key named 'order'.
420 * @subpackage Taxonomy
424 * @uses wp_parse_args() Creates an array from string $args.
426 * @param int|array $term_ids Term id or array of term ids of terms that will be used
427 * @param string|array $taxonomies String of taxonomy name or Array of string values of taxonomy names
428 * @param array|string $args Change the order of the object_ids, either ASC or DESC
429 * @return WP_Error|array If the taxonomy does not exist, then WP_Error will be returned. On success
430 * the array can be empty meaning that there are no $object_ids found or it will return the $object_ids found.
432 function get_objects_in_term( $term_ids, $taxonomies, $args = array() ) {
435 if ( ! is_array( $term_ids ) )
436 $term_ids = array( $term_ids );
438 if ( ! is_array( $taxonomies ) )
439 $taxonomies = array( $taxonomies );
441 foreach ( (array) $taxonomies as $taxonomy ) {
442 if ( ! taxonomy_exists( $taxonomy ) )
443 return new WP_Error( 'invalid_taxonomy', __( 'Invalid Taxonomy' ) );
446 $defaults = array( 'order' => 'ASC' );
447 $args = wp_parse_args( $args, $defaults );
448 extract( $args, EXTR_SKIP );
450 $order = ( 'desc' == strtolower( $order ) ) ? 'DESC' : 'ASC';
452 $term_ids = array_map('intval', $term_ids );
454 $taxonomies = "'" . implode( "', '", $taxonomies ) . "'";
455 $term_ids = "'" . implode( "', '", $term_ids ) . "'";
457 $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");
466 * Get all Term data from database by Term ID.
468 * The usage of the get_term function is to apply filters to a term object. It
469 * is possible to get a term object from the database before applying the
472 * $term ID must be part of $taxonomy, to get from the database. Failure, might
473 * be able to be captured by the hooks. Failure would be the same value as $wpdb
474 * returns for the get_row method.
476 * There are two hooks, one is specifically for each term, named 'get_term', and
477 * the second is for the taxonomy name, 'term_$taxonomy'. Both hooks gets the
478 * term object, and the taxonomy name as parameters. Both hooks are expected to
479 * return a Term object.
481 * 'get_term' hook - Takes two parameters the term Object and the taxonomy name.
482 * Must return term object. Used in get_term() as a catch-all filter for every
485 * 'get_$taxonomy' hook - Takes two parameters the term Object and the taxonomy
486 * name. Must return term object. $taxonomy will be the taxonomy name, so for
487 * example, if 'category', it would be 'get_category' as the filter name. Useful
488 * for custom taxonomies or plugging into default taxonomies.
491 * @subpackage Taxonomy
495 * @uses sanitize_term() Cleanses the term based on $filter context before returning.
496 * @see sanitize_term_field() The $context param lists the available values for get_term_by() $filter param.
498 * @param int|object $term If integer, will get from database. If object will apply filters and return $term.
499 * @param string $taxonomy Taxonomy name that $term is part of.
500 * @param string $output Constant OBJECT, ARRAY_A, or ARRAY_N
501 * @param string $filter Optional, default is raw or no WordPress defined filter will applied.
502 * @return mixed|null|WP_Error Term Row from database. Will return null if $term is empty. If taxonomy does not
503 * exist then WP_Error will be returned.
505 function &get_term($term, $taxonomy, $output = OBJECT, $filter = 'raw') {
509 if ( empty($term) ) {
510 $error = new WP_Error('invalid_term', __('Empty Term'));
514 if ( ! taxonomy_exists($taxonomy) ) {
515 $error = new WP_Error('invalid_taxonomy', __('Invalid Taxonomy'));
519 if ( is_object($term) && empty($term->filter) ) {
520 wp_cache_add($term->term_id, $term, $taxonomy);
523 if ( is_object($term) )
524 $term = $term->term_id;
526 if ( ! $_term = wp_cache_get($term, $taxonomy) ) {
527 $_term = $wpdb->get_row( $wpdb->prepare( "SELECT t.*, tt.* FROM $wpdb->terms AS t INNER JOIN $wpdb->term_taxonomy AS tt ON t.term_id = tt.term_id WHERE tt.taxonomy = %s AND t.term_id = %s LIMIT 1", $taxonomy, $term) );
530 wp_cache_add($term, $_term, $taxonomy);
534 $_term = apply_filters('get_term', $_term, $taxonomy);
535 $_term = apply_filters("get_$taxonomy", $_term, $taxonomy);
536 $_term = sanitize_term($_term, $taxonomy, $filter);
538 if ( $output == OBJECT ) {
540 } elseif ( $output == ARRAY_A ) {
541 $__term = get_object_vars($_term);
543 } elseif ( $output == ARRAY_N ) {
544 $__term = array_values(get_object_vars($_term));
552 * Get all Term data from database by Term field and data.
554 * Warning: $value is not escaped for 'name' $field. You must do it yourself, if
557 * The default $field is 'id', therefore it is possible to also use null for
558 * field, but not recommended that you do so.
560 * If $value does not exist, the return value will be false. If $taxonomy exists
561 * and $field and $value combinations exist, the Term will be returned.
564 * @subpackage Taxonomy
568 * @uses sanitize_term() Cleanses the term based on $filter context before returning.
569 * @see sanitize_term_field() The $context param lists the available values for get_term_by() $filter param.
571 * @param string $field Either 'slug', 'name', or 'id'
572 * @param string|int $value Search for this term value
573 * @param string $taxonomy Taxonomy Name
574 * @param string $output Constant OBJECT, ARRAY_A, or ARRAY_N
575 * @param string $filter Optional, default is raw or no WordPress defined filter will applied.
576 * @return mixed Term Row from database. Will return false if $taxonomy does not exist or $term was not found.
578 function get_term_by($field, $value, $taxonomy, $output = OBJECT, $filter = 'raw') {
581 if ( ! taxonomy_exists($taxonomy) )
584 if ( 'slug' == $field ) {
586 $value = sanitize_title($value);
589 } else if ( 'name' == $field ) {
590 // Assume already escaped
591 $value = stripslashes($value);
594 return get_term( (int) $value, $taxonomy, $output, $filter);
597 $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) );
601 wp_cache_add($term->term_id, $term, $taxonomy);
603 $term = apply_filters('get_term', $term, $taxonomy);
604 $term = apply_filters("get_$taxonomy", $term, $taxonomy);
605 $term = sanitize_term($term, $taxonomy, $filter);
607 if ( $output == OBJECT ) {
609 } elseif ( $output == ARRAY_A ) {
610 return get_object_vars($term);
611 } elseif ( $output == ARRAY_N ) {
612 return array_values(get_object_vars($term));
619 * Merge all term children into a single array of their IDs.
621 * This recursive function will merge all of the children of $term into the same
622 * array of term IDs. Only useful for taxonomies which are hierarchical.
624 * Will return an empty array if $term does not exist in $taxonomy.
627 * @subpackage Taxonomy
631 * @uses _get_term_hierarchy()
632 * @uses get_term_children() Used to get the children of both $taxonomy and the parent $term
634 * @param string $term ID of Term to get children
635 * @param string $taxonomy Taxonomy Name
636 * @return array|WP_Error List of Term Objects. WP_Error returned if $taxonomy does not exist
638 function get_term_children( $term_id, $taxonomy ) {
639 if ( ! taxonomy_exists($taxonomy) )
640 return new WP_Error('invalid_taxonomy', __('Invalid Taxonomy'));
642 $term_id = intval( $term_id );
644 $terms = _get_term_hierarchy($taxonomy);
646 if ( ! isset($terms[$term_id]) )
649 $children = $terms[$term_id];
651 foreach ( (array) $terms[$term_id] as $child ) {
652 if ( isset($terms[$child]) )
653 $children = array_merge($children, get_term_children($child, $taxonomy));
660 * Get sanitized Term field.
662 * Does checks for $term, based on the $taxonomy. The function is for contextual
663 * reasons and for simplicity of usage. See sanitize_term_field() for more
667 * @subpackage Taxonomy
670 * @uses sanitize_term_field() Passes the return value in sanitize_term_field on success.
672 * @param string $field Term field to fetch
673 * @param int $term Term ID
674 * @param string $taxonomy Taxonomy Name
675 * @param string $context Optional, default is display. Look at sanitize_term_field() for available options.
676 * @return mixed Will return an empty string if $term is not an object or if $field is not set in $term.
678 function get_term_field( $field, $term, $taxonomy, $context = 'display' ) {
680 $term = get_term( $term, $taxonomy );
681 if ( is_wp_error($term) )
684 if ( !is_object($term) )
687 if ( !isset($term->$field) )
690 return sanitize_term_field($field, $term->$field, $term->term_id, $taxonomy, $context);
694 * Sanitizes Term for editing.
696 * Return value is sanitize_term() and usage is for sanitizing the term for
697 * editing. Function is for contextual and simplicity.
700 * @subpackage Taxonomy
703 * @uses sanitize_term() Passes the return value on success
705 * @param int|object $id Term ID or Object
706 * @param string $taxonomy Taxonomy Name
707 * @return mixed|null|WP_Error Will return empty string if $term is not an object.
709 function get_term_to_edit( $id, $taxonomy ) {
710 $term = get_term( $id, $taxonomy );
712 if ( is_wp_error($term) )
715 if ( !is_object($term) )
718 return sanitize_term($term, $taxonomy, 'edit');
722 * Retrieve the terms in a given taxonomy or list of taxonomies.
724 * You can fully inject any customizations to the query before it is sent, as
725 * well as control the output with a filter.
727 * The 'get_terms' filter will be called when the cache has the term and will
728 * pass the found term along with the array of $taxonomies and array of $args.
729 * This filter is also called before the array of terms is passed and will pass
730 * the array of terms, along with the $taxonomies and $args.
732 * The 'list_terms_exclusions' filter passes the compiled exclusions along with
735 * The 'get_terms_orderby' filter passes the ORDER BY clause for the query
736 * along with the $args array.
738 * The 'get_terms_fields' filter passes the fields for the SELECT query
739 * along with the $args array.
741 * The list of arguments that $args can contain, which will overwrite the defaults:
743 * orderby - Default is 'name'. Can be name, count, term_group, slug or nothing
744 * (will use term_id), Passing a custom value other than these will cause it to
745 * order based on the custom value.
747 * order - Default is ASC. Can use DESC.
749 * hide_empty - Default is true. Will not return empty terms, which means
750 * terms whose count is 0 according to the given taxonomy.
752 * exclude - Default is an empty array. An array, comma- or space-delimited string
753 * of term ids to exclude from the return array. If 'include' is non-empty,
754 * 'exclude' is ignored.
756 * exclude_tree - Default is an empty array. An array, comma- or space-delimited
757 * string of term ids to exclude from the return array, along with all of their
758 * descendant terms according to the primary taxonomy. If 'include' is non-empty,
759 * 'exclude_tree' is ignored.
761 * include - Default is an empty array. An array, comma- or space-delimited string
762 * of term ids to include in the return array.
764 * number - The maximum number of terms to return. Default is to return them all.
766 * offset - The number by which to offset the terms query.
768 * fields - Default is 'all', which returns an array of term objects.
769 * If 'fields' is 'ids' or 'names', returns an array of
770 * integers or strings, respectively.
772 * slug - Returns terms whose "slug" matches this value. Default is empty string.
774 * hierarchical - Whether to include terms that have non-empty descendants
775 * (even if 'hide_empty' is set to true).
777 * search - Returned terms' names will contain the value of 'search',
778 * case-insensitive. Default is an empty string.
780 * name__like - Returned terms' names will begin with the value of 'name__like',
781 * case-insensitive. Default is empty string.
783 * The argument 'pad_counts', if set to true will include the quantity of a term's
784 * children in the quantity of each term's "count" object variable.
786 * The 'get' argument, if set to 'all' instead of its default empty string,
787 * returns terms regardless of ancestry or whether the terms are empty.
789 * The 'child_of' argument, when used, should be set to the integer of a term ID. Its default
790 * is 0. If set to a non-zero value, all returned terms will be descendants
791 * of that term according to the given taxonomy. Hence 'child_of' is set to 0
792 * if more than one taxonomy is passed in $taxonomies, because multiple taxonomies
793 * make term ancestry ambiguous.
795 * The 'parent' argument, when used, should be set to the integer of a term ID. Its default is
796 * the empty string '', which has a different meaning from the integer 0.
797 * If set to an integer value, all returned terms will have as an immediate
798 * ancestor the term whose ID is specified by that integer according to the given taxonomy.
799 * The 'parent' argument is different from 'child_of' in that a term X is considered a 'parent'
800 * of term Y only if term X is the father of term Y, not its grandfather or great-grandfather, etc.
803 * @subpackage Taxonomy
807 * @uses wp_parse_args() Merges the defaults with those defined by $args and allows for strings.
809 * @param string|array Taxonomy name or list of Taxonomy names
810 * @param string|array $args The values of what to search for when returning terms
811 * @return array|WP_Error List of Term Objects and their children. Will return WP_Error, if any of $taxonomies do not exist.
813 function &get_terms($taxonomies, $args = '') {
815 $empty_array = array();
817 $single_taxonomy = false;
818 if ( !is_array($taxonomies) ) {
819 $single_taxonomy = true;
820 $taxonomies = array($taxonomies);
823 foreach ( (array) $taxonomies as $taxonomy ) {
824 if ( ! taxonomy_exists($taxonomy) ) {
825 $error = & new WP_Error('invalid_taxonomy', __('Invalid Taxonomy'));
830 $in_taxonomies = "'" . implode("', '", $taxonomies) . "'";
832 $defaults = array('orderby' => 'name', 'order' => 'ASC',
833 'hide_empty' => true, 'exclude' => array(), 'exclude_tree' => array(), 'include' => array(),
834 'number' => '', 'fields' => 'all', 'slug' => '', 'parent' => '',
835 'hierarchical' => true, 'child_of' => 0, 'get' => '', 'name__like' => '',
836 'pad_counts' => false, 'offset' => '', 'search' => '');
837 $args = wp_parse_args( $args, $defaults );
838 $args['number'] = absint( $args['number'] );
839 $args['offset'] = absint( $args['offset'] );
840 if ( !$single_taxonomy || !is_taxonomy_hierarchical($taxonomies[0]) ||
841 '' !== $args['parent'] ) {
842 $args['child_of'] = 0;
843 $args['hierarchical'] = false;
844 $args['pad_counts'] = false;
847 if ( 'all' == $args['get'] ) {
848 $args['child_of'] = 0;
849 $args['hide_empty'] = 0;
850 $args['hierarchical'] = false;
851 $args['pad_counts'] = false;
853 extract($args, EXTR_SKIP);
856 $hierarchy = _get_term_hierarchy($taxonomies[0]);
857 if ( !isset($hierarchy[$child_of]) )
862 $hierarchy = _get_term_hierarchy($taxonomies[0]);
863 if ( !isset($hierarchy[$parent]) )
867 // $args can be whatever, only use the args defined in defaults to compute the key
868 $filter_key = ( has_filter('list_terms_exclusions') ) ? serialize($GLOBALS['wp_filter']['list_terms_exclusions']) : '';
869 $key = md5( serialize( compact(array_keys($defaults)) ) . serialize( $taxonomies ) . $filter_key );
870 $last_changed = wp_cache_get('last_changed', 'terms');
871 if ( !$last_changed ) {
872 $last_changed = time();
873 wp_cache_set('last_changed', $last_changed, 'terms');
875 $cache_key = "get_terms:$key:$last_changed";
876 $cache = wp_cache_get( $cache_key, 'terms' );
877 if ( false !== $cache ) {
878 $cache = apply_filters('get_terms', $cache, $taxonomies, $args);
882 $_orderby = strtolower($orderby);
883 if ( 'count' == $_orderby )
884 $orderby = 'tt.count';
885 else if ( 'name' == $_orderby )
887 else if ( 'slug' == $_orderby )
889 else if ( 'term_group' == $_orderby )
890 $orderby = 't.term_group';
891 else if ( 'none' == $_orderby )
893 elseif ( empty($_orderby) || 'id' == $_orderby )
894 $orderby = 't.term_id';
896 $orderby = apply_filters( 'get_terms_orderby', $orderby, $args );
898 if ( !empty($orderby) )
899 $orderby = "ORDER BY $orderby";
905 if ( !empty($include) ) {
908 $interms = wp_parse_id_list($include);
909 foreach ( $interms as $interm ) {
910 if ( empty($inclusions) )
911 $inclusions = ' AND ( t.term_id = ' . intval($interm) . ' ';
913 $inclusions .= ' OR t.term_id = ' . intval($interm) . ' ';
917 if ( !empty($inclusions) )
919 $where .= $inclusions;
922 if ( !empty( $exclude_tree ) ) {
923 $excluded_trunks = wp_parse_id_list($exclude_tree);
924 foreach ( $excluded_trunks as $extrunk ) {
925 $excluded_children = (array) get_terms($taxonomies[0], array('child_of' => intval($extrunk), 'fields' => 'ids'));
926 $excluded_children[] = $extrunk;
927 foreach( $excluded_children as $exterm ) {
928 if ( empty($exclusions) )
929 $exclusions = ' AND ( t.term_id <> ' . intval($exterm) . ' ';
931 $exclusions .= ' AND t.term_id <> ' . intval($exterm) . ' ';
936 if ( !empty($exclude) ) {
937 $exterms = wp_parse_id_list($exclude);
938 foreach ( $exterms as $exterm ) {
939 if ( empty($exclusions) )
940 $exclusions = ' AND ( t.term_id <> ' . intval($exterm) . ' ';
942 $exclusions .= ' AND t.term_id <> ' . intval($exterm) . ' ';
946 if ( !empty($exclusions) )
948 $exclusions = apply_filters('list_terms_exclusions', $exclusions, $args );
949 $where .= $exclusions;
951 if ( !empty($slug) ) {
952 $slug = sanitize_title($slug);
953 $where .= " AND t.slug = '$slug'";
956 if ( !empty($name__like) )
957 $where .= " AND t.name LIKE '{$name__like}%'";
959 if ( '' !== $parent ) {
960 $parent = (int) $parent;
961 $where .= " AND tt.parent = '$parent'";
964 if ( $hide_empty && !$hierarchical )
965 $where .= ' AND tt.count > 0';
967 // don't limit the query results when we have to descend the family tree
968 if ( ! empty($number) && ! $hierarchical && empty( $child_of ) && '' === $parent ) {
970 $limit = 'LIMIT ' . $offset . ',' . $number;
972 $limit = 'LIMIT ' . $number;
977 if ( !empty($search) ) {
978 $search = like_escape($search);
979 $where .= " AND (t.name LIKE '%$search%')";
985 $selects = array('t.*', 'tt.*');
989 $selects = array('t.term_id', 'tt.parent', 'tt.count');
992 $selects = array('t.term_id', 'tt.parent', 'tt.count', 't.name');
997 $selects = array('COUNT(*)');
999 $select_this = implode(', ', apply_filters( 'get_terms_fields', $selects, $args ));
1001 $query = "SELECT $select_this FROM $wpdb->terms AS t INNER JOIN $wpdb->term_taxonomy AS tt ON t.term_id = tt.term_id WHERE tt.taxonomy IN ($in_taxonomies) $where $orderby $order $limit";
1003 if ( 'count' == $fields ) {
1004 $term_count = $wpdb->get_var($query);
1008 $terms = $wpdb->get_results($query);
1009 if ( 'all' == $fields ) {
1010 update_term_cache($terms);
1013 if ( empty($terms) ) {
1014 wp_cache_add( $cache_key, array(), 'terms' );
1015 $terms = apply_filters('get_terms', array(), $taxonomies, $args);
1020 $children = _get_term_hierarchy($taxonomies[0]);
1021 if ( ! empty($children) )
1022 $terms = & _get_term_children($child_of, $terms, $taxonomies[0]);
1025 // Update term counts to include children.
1026 if ( $pad_counts && 'all' == $fields )
1027 _pad_term_counts($terms, $taxonomies[0]);
1029 // Make sure we show empty categories that have children.
1030 if ( $hierarchical && $hide_empty && is_array($terms) ) {
1031 foreach ( $terms as $k => $term ) {
1032 if ( ! $term->count ) {
1033 $children = _get_term_children($term->term_id, $terms, $taxonomies[0]);
1034 if ( is_array($children) )
1035 foreach ( $children as $child )
1036 if ( $child->count )
1039 // It really is empty
1047 if ( 'id=>parent' == $fields ) {
1048 while ( $term = array_shift($terms) )
1049 $_terms[$term->term_id] = $term->parent;
1051 } elseif ( 'ids' == $fields ) {
1052 while ( $term = array_shift($terms) )
1053 $_terms[] = $term->term_id;
1055 } elseif ( 'names' == $fields ) {
1056 while ( $term = array_shift($terms) )
1057 $_terms[] = $term->name;
1061 if ( 0 < $number && intval(@count($terms)) > $number ) {
1062 $terms = array_slice($terms, $offset, $number);
1065 wp_cache_add( $cache_key, $terms, 'terms' );
1067 $terms = apply_filters('get_terms', $terms, $taxonomies, $args);
1072 * Check if Term exists.
1074 * Returns the index of a defined term, or 0 (false) if the term doesn't exist.
1076 * Formerly is_term(), introduced in 2.3.0.
1078 * @package WordPress
1079 * @subpackage Taxonomy
1084 * @param int|string $term The term to check
1085 * @param string $taxonomy The taxonomy name to use
1086 * @param int $parent ID of parent term under which to confine the exists search.
1087 * @return mixed Get the term id or Term Object, if exists.
1089 function term_exists($term, $taxonomy = '', $parent = 0) {
1092 $select = "SELECT term_id FROM $wpdb->terms as t WHERE ";
1093 $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 ";
1095 if ( is_int($term) ) {
1098 $where = 't.term_id = %d';
1099 if ( !empty($taxonomy) )
1100 return $wpdb->get_row( $wpdb->prepare( $tax_select . $where . " AND tt.taxonomy = %s", $term, $taxonomy ), ARRAY_A );
1102 return $wpdb->get_var( $wpdb->prepare( $select . $where, $term ) );
1105 $term = trim( stripslashes( $term ) );
1107 if ( '' === $slug = sanitize_title($term) )
1110 $where = 't.slug = %s';
1111 $else_where = 't.name = %s';
1112 $where_fields = array($slug);
1113 $else_where_fields = array($term);
1114 if ( !empty($taxonomy) ) {
1115 $parent = (int) $parent;
1116 if ( $parent > 0 ) {
1117 $where_fields[] = $parent;
1118 $else_where_fields[] = $parent;
1119 $where .= ' AND tt.parent = %d';
1120 $else_where .= ' AND tt.parent = %d';
1123 $where_fields[] = $taxonomy;
1124 $else_where_fields[] = $taxonomy;
1126 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) )
1129 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);
1132 if ( $result = $wpdb->get_var( $wpdb->prepare("SELECT term_id FROM $wpdb->terms as t WHERE $where", $where_fields) ) )
1135 return $wpdb->get_var( $wpdb->prepare("SELECT term_id FROM $wpdb->terms as t WHERE $else_where", $else_where_fields) );
1139 * Sanitize Term all fields.
1141 * Relys on sanitize_term_field() to sanitize the term. The difference is that
1142 * this function will sanitize <strong>all</strong> fields. The context is based
1143 * on sanitize_term_field().
1145 * The $term is expected to be either an array or an object.
1147 * @package WordPress
1148 * @subpackage Taxonomy
1151 * @uses sanitize_term_field Used to sanitize all fields in a term
1153 * @param array|object $term The term to check
1154 * @param string $taxonomy The taxonomy name to use
1155 * @param string $context Default is 'display'.
1156 * @return array|object Term with all fields sanitized
1158 function sanitize_term($term, $taxonomy, $context = 'display') {
1160 if ( 'raw' == $context )
1163 $fields = array('term_id', 'name', 'description', 'slug', 'count', 'parent', 'term_group');
1166 if ( is_object($term) )
1169 $term_id = $do_object ? $term->term_id : (isset($term['term_id']) ? $term['term_id'] : 0);
1171 foreach ( (array) $fields as $field ) {
1173 if ( isset($term->$field) )
1174 $term->$field = sanitize_term_field($field, $term->$field, $term_id, $taxonomy, $context);
1176 if ( isset($term[$field]) )
1177 $term[$field] = sanitize_term_field($field, $term[$field], $term_id, $taxonomy, $context);
1182 $term->filter = $context;
1184 $term['filter'] = $context;
1190 * Cleanse the field value in the term based on the context.
1192 * Passing a term field value through the function should be assumed to have
1193 * cleansed the value for whatever context the term field is going to be used.
1195 * If no context or an unsupported context is given, then default filters will
1198 * There are enough filters for each context to support a custom filtering
1199 * without creating your own filter function. Simply create a function that
1200 * hooks into the filter you need.
1202 * @package WordPress
1203 * @subpackage Taxonomy
1208 * @param string $field Term field to sanitize
1209 * @param string $value Search for this term value
1210 * @param int $term_id Term ID
1211 * @param string $taxonomy Taxonomy Name
1212 * @param string $context Either edit, db, display, attribute, or js.
1213 * @return mixed sanitized field
1215 function sanitize_term_field($field, $value, $term_id, $taxonomy, $context) {
1216 if ( 'parent' == $field || 'term_id' == $field || 'count' == $field || 'term_group' == $field ) {
1217 $value = (int) $value;
1222 if ( 'raw' == $context )
1225 if ( 'edit' == $context ) {
1226 $value = apply_filters("edit_term_$field", $value, $term_id, $taxonomy);
1227 $value = apply_filters("edit_${taxonomy}_$field", $value, $term_id);
1228 if ( 'description' == $field )
1229 $value = format_to_edit($value);
1231 $value = esc_attr($value);
1232 } else if ( 'db' == $context ) {
1233 $value = apply_filters("pre_term_$field", $value, $taxonomy);
1234 $value = apply_filters("pre_${taxonomy}_$field", $value);
1235 // Back compat filters
1236 if ( 'slug' == $field )
1237 $value = apply_filters('pre_category_nicename', $value);
1239 } else if ( 'rss' == $context ) {
1240 $value = apply_filters("term_${field}_rss", $value, $taxonomy);
1241 $value = apply_filters("${taxonomy}_${field}_rss", $value);
1243 // Use display filters by default.
1244 $value = apply_filters("term_$field", $value, $term_id, $taxonomy, $context);
1245 $value = apply_filters("${taxonomy}_$field", $value, $term_id, $context);
1248 if ( 'attribute' == $context )
1249 $value = esc_attr($value);
1250 else if ( 'js' == $context )
1251 $value = esc_js($value);
1257 * Count how many terms are in Taxonomy.
1259 * Default $args is 'hide_empty' which can be 'hide_empty=true' or array('hide_empty' => true).
1261 * @package WordPress
1262 * @subpackage Taxonomy
1266 * @uses wp_parse_args() Turns strings into arrays and merges defaults into an array.
1268 * @param string $taxonomy Taxonomy name
1269 * @param array|string $args Overwrite defaults. See get_terms()
1270 * @return int How many terms are in $taxonomy
1272 function wp_count_terms( $taxonomy, $args = array() ) {
1273 $defaults = array('hide_empty' => false);
1274 $args = wp_parse_args($args, $defaults);
1276 // backwards compatibility
1277 if ( isset($args['ignore_empty']) ) {
1278 $args['hide_empty'] = $args['ignore_empty'];
1279 unset($args['ignore_empty']);
1282 $args['fields'] = 'count';
1284 return get_terms($taxonomy, $args);
1288 * Will unlink the term from the taxonomy.
1290 * Will remove the term's relationship to the taxonomy, not the term or taxonomy
1291 * itself. The term and taxonomy will still exist. Will require the term's
1292 * object ID to perform the operation.
1294 * @package WordPress
1295 * @subpackage Taxonomy
1299 * @param int $object_id The term Object Id that refers to the term
1300 * @param string|array $taxonomy List of Taxonomy Names or single Taxonomy name.
1302 function wp_delete_object_term_relationships( $object_id, $taxonomies ) {
1305 $object_id = (int) $object_id;
1307 if ( !is_array($taxonomies) )
1308 $taxonomies = array($taxonomies);
1310 foreach ( (array) $taxonomies as $taxonomy ) {
1311 $tt_ids = wp_get_object_terms($object_id, $taxonomy, array('fields' => 'tt_ids'));
1312 $in_tt_ids = "'" . implode("', '", $tt_ids) . "'";
1313 do_action( 'delete_term_relationships', $object_id, $tt_ids );
1314 $wpdb->query( $wpdb->prepare("DELETE FROM $wpdb->term_relationships WHERE object_id = %d AND term_taxonomy_id IN ($in_tt_ids)", $object_id) );
1315 do_action( 'deleted_term_relationships', $object_id, $tt_ids );
1316 wp_update_term_count($tt_ids, $taxonomy);
1321 * Removes a term from the database.
1323 * If the term is a parent of other terms, then the children will be updated to
1324 * that term's parent.
1326 * The $args 'default' will only override the terms found, if there is only one
1327 * term found. Any other and the found terms are used.
1329 * The $args 'force_default' will force the term supplied as default to be
1330 * assigned even if the object was not going to be termless
1331 * @package WordPress
1332 * @subpackage Taxonomy
1336 * @uses do_action() Calls both 'delete_term' and 'delete_$taxonomy' action
1337 * hooks, passing term object, term id. 'delete_term' gets an additional
1338 * parameter with the $taxonomy parameter.
1340 * @param int $term Term ID
1341 * @param string $taxonomy Taxonomy Name
1342 * @param array|string $args Optional. Change 'default' term id and override found term ids.
1343 * @return bool|WP_Error Returns false if not term; true if completes delete action.
1345 function wp_delete_term( $term, $taxonomy, $args = array() ) {
1348 $term = (int) $term;
1350 if ( ! $ids = term_exists($term, $taxonomy) )
1352 if ( is_wp_error( $ids ) )
1355 $tt_id = $ids['term_taxonomy_id'];
1357 $defaults = array();
1358 $args = wp_parse_args($args, $defaults);
1359 extract($args, EXTR_SKIP);
1361 if ( isset($default) ) {
1362 $default = (int) $default;
1363 if ( ! term_exists($default, $taxonomy) )
1367 // Update children to point to new parent
1368 if ( is_taxonomy_hierarchical($taxonomy) ) {
1369 $term_obj = get_term($term, $taxonomy);
1370 if ( is_wp_error( $term_obj ) )
1372 $parent = $term_obj->parent;
1374 $edit_tt_ids = $wpdb->get_col( "SELECT `term_taxonomy_id` FROM $wpdb->term_taxonomy WHERE `parent` = " . (int)$term_obj->term_id );
1375 do_action( 'edit_term_taxonomies', $edit_tt_ids );
1376 $wpdb->update( $wpdb->term_taxonomy, compact( 'parent' ), array( 'parent' => $term_obj->term_id) + compact( 'taxonomy' ) );
1377 do_action( 'edited_term_taxonomies', $edit_tt_ids );
1380 $objects = $wpdb->get_col( $wpdb->prepare( "SELECT object_id FROM $wpdb->term_relationships WHERE term_taxonomy_id = %d", $tt_id ) );
1382 foreach ( (array) $objects as $object ) {
1383 $terms = wp_get_object_terms($object, $taxonomy, array('fields' => 'ids', 'orderby' => 'none'));
1384 if ( 1 == count($terms) && isset($default) ) {
1385 $terms = array($default);
1387 $terms = array_diff($terms, array($term));
1388 if (isset($default) && isset($force_default) && $force_default)
1389 $terms = array_merge($terms, array($default));
1391 $terms = array_map('intval', $terms);
1392 wp_set_object_terms($object, $terms, $taxonomy);
1395 do_action( 'delete_term_taxonomy', $tt_id );
1396 $wpdb->query( $wpdb->prepare( "DELETE FROM $wpdb->term_taxonomy WHERE term_taxonomy_id = %d", $tt_id ) );
1397 do_action( 'deleted_term_taxonomy', $tt_id );
1399 // Delete the term if no taxonomies use it.
1400 if ( !$wpdb->get_var( $wpdb->prepare( "SELECT COUNT(*) FROM $wpdb->term_taxonomy WHERE term_id = %d", $term) ) )
1401 $wpdb->query( $wpdb->prepare( "DELETE FROM $wpdb->terms WHERE term_id = %d", $term) );
1403 clean_term_cache($term, $taxonomy);
1405 do_action('delete_term', $term, $tt_id, $taxonomy);
1406 do_action("delete_$taxonomy", $term, $tt_id);
1412 * Retrieves the terms associated with the given object(s), in the supplied taxonomies.
1414 * The following information has to do the $args parameter and for what can be
1415 * contained in the string or array of that parameter, if it exists.
1417 * The first argument is called, 'orderby' and has the default value of 'name'.
1418 * The other value that is supported is 'count'.
1420 * The second argument is called, 'order' and has the default value of 'ASC'.
1421 * The only other value that will be acceptable is 'DESC'.
1423 * The final argument supported is called, 'fields' and has the default value of
1424 * 'all'. There are multiple other options that can be used instead. Supported
1425 * values are as follows: 'all', 'ids', 'names', and finally
1426 * 'all_with_object_id'.
1428 * The fields argument also decides what will be returned. If 'all' or
1429 * 'all_with_object_id' is choosen or the default kept intact, then all matching
1430 * terms objects will be returned. If either 'ids' or 'names' is used, then an
1431 * array of all matching term ids or term names will be returned respectively.
1433 * @package WordPress
1434 * @subpackage Taxonomy
1438 * @param int|array $object_id The id of the object(s) to retrieve.
1439 * @param string|array $taxonomies The taxonomies to retrieve terms from.
1440 * @param array|string $args Change what is returned
1441 * @return array|WP_Error The requested term data or empty array if no terms found. WP_Error if $taxonomy does not exist.
1443 function wp_get_object_terms($object_ids, $taxonomies, $args = array()) {
1446 if ( !is_array($taxonomies) )
1447 $taxonomies = array($taxonomies);
1449 foreach ( (array) $taxonomies as $taxonomy ) {
1450 if ( ! taxonomy_exists($taxonomy) )
1451 return new WP_Error('invalid_taxonomy', __('Invalid Taxonomy'));
1454 if ( !is_array($object_ids) )
1455 $object_ids = array($object_ids);
1456 $object_ids = array_map('intval', $object_ids);
1458 $defaults = array('orderby' => 'name', 'order' => 'ASC', 'fields' => 'all');
1459 $args = wp_parse_args( $args, $defaults );
1462 if ( count($taxonomies) > 1 ) {
1463 foreach ( $taxonomies as $index => $taxonomy ) {
1464 $t = get_taxonomy($taxonomy);
1465 if ( isset($t->args) && is_array($t->args) && $args != array_merge($args, $t->args) ) {
1466 unset($taxonomies[$index]);
1467 $terms = array_merge($terms, wp_get_object_terms($object_ids, $taxonomy, array_merge($args, $t->args)));
1471 $t = get_taxonomy($taxonomies[0]);
1472 if ( isset($t->args) && is_array($t->args) )
1473 $args = array_merge($args, $t->args);
1476 extract($args, EXTR_SKIP);
1478 if ( 'count' == $orderby )
1479 $orderby = 'tt.count';
1480 else if ( 'name' == $orderby )
1481 $orderby = 't.name';
1482 else if ( 'slug' == $orderby )
1483 $orderby = 't.slug';
1484 else if ( 'term_group' == $orderby )
1485 $orderby = 't.term_group';
1486 else if ( 'term_order' == $orderby )
1487 $orderby = 'tr.term_order';
1488 else if ( 'none' == $orderby ) {
1492 $orderby = 't.term_id';
1495 // tt_ids queries can only be none or tr.term_taxonomy_id
1496 if ( ('tt_ids' == $fields) && !empty($orderby) )
1497 $orderby = 'tr.term_taxonomy_id';
1499 if ( !empty($orderby) )
1500 $orderby = "ORDER BY $orderby";
1502 $taxonomies = "'" . implode("', '", $taxonomies) . "'";
1503 $object_ids = implode(', ', $object_ids);
1506 if ( 'all' == $fields )
1507 $select_this = 't.*, tt.*';
1508 else if ( 'ids' == $fields )
1509 $select_this = 't.term_id';
1510 else if ( 'names' == $fields )
1511 $select_this = 't.name';
1512 else if ( 'all_with_object_id' == $fields )
1513 $select_this = 't.*, tt.*, tr.object_id';
1515 $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";
1517 if ( 'all' == $fields || 'all_with_object_id' == $fields ) {
1518 $terms = array_merge($terms, $wpdb->get_results($query));
1519 update_term_cache($terms);
1520 } else if ( 'ids' == $fields || 'names' == $fields ) {
1521 $terms = array_merge($terms, $wpdb->get_col($query));
1522 } else if ( 'tt_ids' == $fields ) {
1523 $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");
1529 return apply_filters('wp_get_object_terms', $terms, $object_ids, $taxonomies, $args);
1533 * Adds a new term to the database. Optionally marks it as an alias of an existing term.
1535 * Error handling is assigned for the nonexistance of the $taxonomy and $term
1536 * parameters before inserting. If both the term id and taxonomy exist
1537 * previously, then an array will be returned that contains the term id and the
1538 * contents of what is returned. The keys of the array are 'term_id' and
1539 * 'term_taxonomy_id' containing numeric values.
1541 * It is assumed that the term does not yet exist or the above will apply. The
1542 * term will be first added to the term table and then related to the taxonomy
1543 * if everything is well. If everything is correct, then several actions will be
1544 * run prior to a filter and then several actions will be run after the filter
1547 * The arguments decide how the term is handled based on the $args parameter.
1548 * The following is a list of the available overrides and the defaults.
1550 * 'alias_of'. There is no default, but if added, expected is the slug that the
1551 * term will be an alias of. Expected to be a string.
1553 * 'description'. There is no default. If exists, will be added to the database
1554 * along with the term. Expected to be a string.
1556 * 'parent'. Expected to be numeric and default is 0 (zero). Will assign value
1557 * of 'parent' to the term.
1559 * 'slug'. Expected to be a string. There is no default.
1561 * If 'slug' argument exists then the slug will be checked to see if it is not
1562 * a valid term. If that check succeeds (it is not a valid term), then it is
1563 * added and the term id is given. If it fails, then a check is made to whether
1564 * the taxonomy is hierarchical and the parent argument is not empty. If the
1565 * second check succeeds, the term will be inserted and the term id will be
1568 * @package WordPress
1569 * @subpackage Taxonomy
1573 * @uses apply_filters() Calls 'pre_insert_term' hook with term and taxonomy as parameters.
1574 * @uses do_action() Calls 'create_term' hook with the term id and taxonomy id as parameters.
1575 * @uses do_action() Calls 'create_$taxonomy' hook with term id and taxonomy id as parameters.
1576 * @uses apply_filters() Calls 'term_id_filter' hook with term id and taxonomy id as parameters.
1577 * @uses do_action() Calls 'created_term' hook with the term id and taxonomy id as parameters.
1578 * @uses do_action() Calls 'created_$taxonomy' hook with term id and taxonomy id as parameters.
1580 * @param string $term The term to add or update.
1581 * @param string $taxonomy The taxonomy to which to add the term
1582 * @param array|string $args Change the values of the inserted term
1583 * @return array|WP_Error The Term ID and Term Taxonomy ID
1585 function wp_insert_term( $term, $taxonomy, $args = array() ) {
1588 if ( ! taxonomy_exists($taxonomy) )
1589 return new WP_Error('invalid_taxonomy', __('Invalid taxonomy'));
1591 $term = apply_filters( 'pre_insert_term', $term, $taxonomy );
1592 if ( is_wp_error( $term ) )
1595 if ( is_int($term) && 0 == $term )
1596 return new WP_Error('invalid_term_id', __('Invalid term ID'));
1598 if ( '' == trim($term) )
1599 return new WP_Error('empty_term_name', __('A name is required for this term'));
1601 $defaults = array( 'alias_of' => '', 'description' => '', 'parent' => 0, 'slug' => '');
1602 $args = wp_parse_args($args, $defaults);
1603 $args['name'] = $term;
1604 $args['taxonomy'] = $taxonomy;
1605 $args = sanitize_term($args, $taxonomy, 'db');
1606 extract($args, EXTR_SKIP);
1608 // expected_slashed ($name)
1609 $name = stripslashes($name);
1610 $description = stripslashes($description);
1613 $slug = sanitize_title($name);
1617 $alias = $wpdb->get_row( $wpdb->prepare( "SELECT term_id, term_group FROM $wpdb->terms WHERE slug = %s", $alias_of) );
1618 if ( $alias->term_group ) {
1619 // The alias we want is already in a group, so let's use that one.
1620 $term_group = $alias->term_group;
1622 // The alias isn't in a group, so let's create a new one and firstly add the alias term to it.
1623 $term_group = $wpdb->get_var("SELECT MAX(term_group) FROM $wpdb->terms") + 1;
1624 do_action( 'edit_terms', $alias->term_id );
1625 $wpdb->update($wpdb->terms, compact('term_group'), array('term_id' => $alias->term_id) );
1626 do_action( 'edited_terms', $alias->term_id );
1630 if ( $term_id = term_exists($slug) ) {
1631 $existing_term = $wpdb->get_row( $wpdb->prepare( "SELECT name FROM $wpdb->terms WHERE term_id = %d", $term_id), ARRAY_A );
1632 // We've got an existing term in the same taxonomy, which matches the name of the new term:
1633 if ( is_taxonomy_hierarchical($taxonomy) && $existing_term['name'] == $name && term_exists( (int) $term_id, $taxonomy ) ) {
1634 // Hierarchical, and it matches an existing term, Do not allow same "name" in the same level.
1635 $siblings = get_terms($taxonomy, array('fields' => 'names', 'get' => 'all', 'parent' => (int)$parent) );
1636 if ( in_array($name, $siblings) ) {
1637 return new WP_Error('term_exists', __('A term with the name provided already exists with this parent.'));
1639 $slug = wp_unique_term_slug($slug, (object) $args);
1640 if ( false === $wpdb->insert( $wpdb->terms, compact( 'name', 'slug', 'term_group' ) ) )
1641 return new WP_Error('db_insert_error', __('Could not insert term into the database'), $wpdb->last_error);
1642 $term_id = (int) $wpdb->insert_id;
1644 } elseif ( $existing_term['name'] != $name ) {
1645 // We've got an existing term, with a different name, Create the new term.
1646 $slug = wp_unique_term_slug($slug, (object) $args);
1647 if ( false === $wpdb->insert( $wpdb->terms, compact( 'name', 'slug', 'term_group' ) ) )
1648 return new WP_Error('db_insert_error', __('Could not insert term into the database'), $wpdb->last_error);
1649 $term_id = (int) $wpdb->insert_id;
1650 } elseif ( term_exists( (int) $term_id, $taxonomy ) ) {
1651 // Same name, same slug.
1652 return new WP_Error('term_exists', __('A term with the name provided already exists.'));
1655 // This term does not exist at all in the database, Create it.
1656 $slug = wp_unique_term_slug($slug, (object) $args);
1657 if ( false === $wpdb->insert( $wpdb->terms, compact( 'name', 'slug', 'term_group' ) ) )
1658 return new WP_Error('db_insert_error', __('Could not insert term into the database'), $wpdb->last_error);
1659 $term_id = (int) $wpdb->insert_id;
1662 // Seems unreachable, However, Is used in the case that a term name is provided, which sanitizes to an empty string.
1663 if ( empty($slug) ) {
1664 $slug = sanitize_title($slug, $term_id);
1665 do_action( 'edit_terms', $term_id );
1666 $wpdb->update( $wpdb->terms, compact( 'slug' ), compact( 'term_id' ) );
1667 do_action( 'edited_terms', $term_id );
1670 $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 ) );
1672 if ( !empty($tt_id) )
1673 return array('term_id' => $term_id, 'term_taxonomy_id' => $tt_id);
1675 $wpdb->insert( $wpdb->term_taxonomy, compact( 'term_id', 'taxonomy', 'description', 'parent') + array( 'count' => 0 ) );
1676 $tt_id = (int) $wpdb->insert_id;
1678 do_action("create_term", $term_id, $tt_id, $taxonomy);
1679 do_action("create_$taxonomy", $term_id, $tt_id);
1681 $term_id = apply_filters('term_id_filter', $term_id, $tt_id);
1683 clean_term_cache($term_id, $taxonomy);
1685 do_action("created_term", $term_id, $tt_id, $taxonomy);
1686 do_action("created_$taxonomy", $term_id, $tt_id);
1688 return array('term_id' => $term_id, 'term_taxonomy_id' => $tt_id);
1692 * Create Term and Taxonomy Relationships.
1694 * Relates an object (post, link etc) to a term and taxonomy type. Creates the
1695 * term and taxonomy relationship if it doesn't already exist. Creates a term if
1696 * it doesn't exist (using the slug).
1698 * A relationship means that the term is grouped in or belongs to the taxonomy.
1699 * A term has no meaning until it is given context by defining which taxonomy it
1702 * @package WordPress
1703 * @subpackage Taxonomy
1707 * @param int $object_id The object to relate to.
1708 * @param array|int|string $term The slug or id of the term, will replace all existing
1709 * related terms in this taxonomy.
1710 * @param array|string $taxonomy The context in which to relate the term to the object.
1711 * @param bool $append If false will delete difference of terms.
1712 * @return array|WP_Error Affected Term IDs
1714 function wp_set_object_terms($object_id, $terms, $taxonomy, $append = false) {
1717 $object_id = (int) $object_id;
1719 if ( ! taxonomy_exists($taxonomy) )
1720 return new WP_Error('invalid_taxonomy', __('Invalid Taxonomy'));
1722 if ( !is_array($terms) )
1723 $terms = array($terms);
1726 $old_tt_ids = wp_get_object_terms($object_id, $taxonomy, array('fields' => 'tt_ids', 'orderby' => 'none'));
1728 $old_tt_ids = array();
1731 $term_ids = array();
1733 foreach ( (array) $terms as $term) {
1734 if ( !strlen(trim($term)) )
1737 if ( !$term_info = term_exists($term, $taxonomy) ) {
1738 // Skip if a non-existent term ID is passed.
1739 if ( is_int($term) )
1741 $term_info = wp_insert_term($term, $taxonomy);
1743 if ( is_wp_error($term_info) )
1745 $term_ids[] = $term_info['term_id'];
1746 $tt_id = $term_info['term_taxonomy_id'];
1749 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 ) ) )
1751 do_action( 'add_term_relationship', $object_id, $tt_id );
1752 $wpdb->insert( $wpdb->term_relationships, array( 'object_id' => $object_id, 'term_taxonomy_id' => $tt_id ) );
1753 do_action( 'added_term_relationship', $object_id, $tt_id );
1756 wp_update_term_count($tt_ids, $taxonomy);
1759 $delete_terms = array_diff($old_tt_ids, $tt_ids);
1760 if ( $delete_terms ) {
1761 $in_delete_terms = "'" . implode("', '", $delete_terms) . "'";
1762 do_action( 'delete_term_relationships', $object_id, $delete_terms );
1763 $wpdb->query( $wpdb->prepare("DELETE FROM $wpdb->term_relationships WHERE object_id = %d AND term_taxonomy_id IN ($in_delete_terms)", $object_id) );
1764 do_action( 'deleted_term_relationships', $object_id, $delete_terms );
1765 wp_update_term_count($delete_terms, $taxonomy);
1769 $t = get_taxonomy($taxonomy);
1770 if ( ! $append && isset($t->sort) && $t->sort ) {
1773 $final_tt_ids = wp_get_object_terms($object_id, $taxonomy, array('fields' => 'tt_ids'));
1774 foreach ( $tt_ids as $tt_id )
1775 if ( in_array($tt_id, $final_tt_ids) )
1776 $values[] = $wpdb->prepare( "(%d, %d, %d)", $object_id, $tt_id, ++$term_order);
1778 $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)");
1781 do_action('set_object_terms', $object_id, $terms, $tt_ids, $taxonomy, $append, $old_tt_ids);
1786 * Will make slug unique, if it isn't already.
1788 * The $slug has to be unique global to every taxonomy, meaning that one
1789 * taxonomy term can't have a matching slug with another taxonomy term. Each
1790 * slug has to be globally unique for every taxonomy.
1792 * The way this works is that if the taxonomy that the term belongs to is
1793 * hierarchical and has a parent, it will append that parent to the $slug.
1795 * If that still doesn't return an unique slug, then it try to append a number
1796 * until it finds a number that is truely unique.
1798 * The only purpose for $term is for appending a parent, if one exists.
1800 * @package WordPress
1801 * @subpackage Taxonomy
1805 * @param string $slug The string that will be tried for a unique slug
1806 * @param object $term The term object that the $slug will belong too
1807 * @return string Will return a true unique slug.
1809 function wp_unique_term_slug($slug, $term) {
1812 if ( ! term_exists( $slug ) )
1815 // If the taxonomy supports hierarchy and the term has a parent, make the slug unique
1816 // by incorporating parent slugs.
1817 if ( is_taxonomy_hierarchical($term->taxonomy) && !empty($term->parent) ) {
1818 $the_parent = $term->parent;
1819 while ( ! empty($the_parent) ) {
1820 $parent_term = get_term($the_parent, $term->taxonomy);
1821 if ( is_wp_error($parent_term) || empty($parent_term) )
1823 $slug .= '-' . $parent_term->slug;
1824 if ( ! term_exists( $slug ) )
1827 if ( empty($parent_term->parent) )
1829 $the_parent = $parent_term->parent;
1833 // If we didn't get a unique slug, try appending a number to make it unique.
1834 if ( !empty($args['term_id']) )
1835 $query = $wpdb->prepare( "SELECT slug FROM $wpdb->terms WHERE slug = %s AND term_id != %d", $slug, $args['term_id'] );
1837 $query = $wpdb->prepare( "SELECT slug FROM $wpdb->terms WHERE slug = %s", $slug );
1839 if ( $wpdb->get_var( $query ) ) {
1842 $alt_slug = $slug . "-$num";
1844 $slug_check = $wpdb->get_var( $wpdb->prepare( "SELECT slug FROM $wpdb->terms WHERE slug = %s", $alt_slug ) );
1845 } while ( $slug_check );
1853 * Update term based on arguments provided.
1855 * The $args will indiscriminately override all values with the same field name.
1856 * Care must be taken to not override important information need to update or
1857 * update will fail (or perhaps create a new term, neither would be acceptable).
1859 * Defaults will set 'alias_of', 'description', 'parent', and 'slug' if not
1860 * defined in $args already.
1862 * 'alias_of' will create a term group, if it doesn't already exist, and update
1865 * If the 'slug' argument in $args is missing, then the 'name' in $args will be
1866 * used. It should also be noted that if you set 'slug' and it isn't unique then
1867 * a WP_Error will be passed back. If you don't pass any slug, then a unique one
1868 * will be created for you.
1870 * For what can be overrode in $args, check the term scheme can contain and stay
1871 * away from the term keys.
1873 * @package WordPress
1874 * @subpackage Taxonomy
1878 * @uses do_action() Will call both 'edit_term' and 'edit_$taxonomy' twice.
1879 * @uses apply_filters() Will call the 'term_id_filter' filter and pass the term
1880 * id and taxonomy id.
1882 * @param int $term_id The ID of the term
1883 * @param string $taxonomy The context in which to relate the term to the object.
1884 * @param array|string $args Overwrite term field values
1885 * @return array|WP_Error Returns Term ID and Taxonomy Term ID
1887 function wp_update_term( $term_id, $taxonomy, $args = array() ) {
1890 if ( ! taxonomy_exists($taxonomy) )
1891 return new WP_Error('invalid_taxonomy', __('Invalid taxonomy'));
1893 $term_id = (int) $term_id;
1895 // First, get all of the original args
1896 $term = get_term ($term_id, $taxonomy, ARRAY_A);
1898 if ( is_wp_error( $term ) )
1901 // Escape data pulled from DB.
1902 $term = add_magic_quotes($term);
1904 // Merge old and new args with new args overwriting old ones.
1905 $args = array_merge($term, $args);
1907 $defaults = array( 'alias_of' => '', 'description' => '', 'parent' => 0, 'slug' => '');
1908 $args = wp_parse_args($args, $defaults);
1909 $args = sanitize_term($args, $taxonomy, 'db');
1910 extract($args, EXTR_SKIP);
1912 // expected_slashed ($name)
1913 $name = stripslashes($name);
1914 $description = stripslashes($description);
1916 if ( '' == trim($name) )
1917 return new WP_Error('empty_term_name', __('A name is required for this term'));
1919 $empty_slug = false;
1920 if ( empty($slug) ) {
1922 $slug = sanitize_title($name);
1926 $alias = $wpdb->get_row( $wpdb->prepare( "SELECT term_id, term_group FROM $wpdb->terms WHERE slug = %s", $alias_of) );
1927 if ( $alias->term_group ) {
1928 // The alias we want is already in a group, so let's use that one.
1929 $term_group = $alias->term_group;
1931 // The alias isn't in a group, so let's create a new one and firstly add the alias term to it.
1932 $term_group = $wpdb->get_var("SELECT MAX(term_group) FROM $wpdb->terms") + 1;
1933 do_action( 'edit_terms', $alias->term_id );
1934 $wpdb->update( $wpdb->terms, compact('term_group'), array( 'term_id' => $alias->term_id ) );
1935 do_action( 'edited_terms', $alias->term_id );
1939 // Check for duplicate slug
1940 $id = $wpdb->get_var( $wpdb->prepare( "SELECT term_id FROM $wpdb->terms WHERE slug = %s", $slug ) );
1941 if ( $id && ($id != $term_id) ) {
1942 // If an empty slug was passed or the parent changed, reset the slug to something unique.
1944 if ( $empty_slug || ( $parent != $term['parent']) )
1945 $slug = wp_unique_term_slug($slug, (object) $args);
1947 return new WP_Error('duplicate_term_slug', sprintf(__('The slug “%s” is already in use by another term'), $slug));
1949 do_action( 'edit_terms', $term_id );
1950 $wpdb->update($wpdb->terms, compact( 'name', 'slug', 'term_group' ), compact( 'term_id' ) );
1951 if ( empty($slug) ) {
1952 $slug = sanitize_title($name, $term_id);
1953 $wpdb->update( $wpdb->terms, compact( 'slug' ), compact( 'term_id' ) );
1955 do_action( 'edited_terms', $term_id );
1957 $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) );
1958 do_action( 'edit_term_taxonomy', $tt_id, $taxonomy );
1959 $wpdb->update( $wpdb->term_taxonomy, compact( 'term_id', 'taxonomy', 'description', 'parent' ), array( 'term_taxonomy_id' => $tt_id ) );
1960 do_action( 'edited_term_taxonomy', $tt_id, $taxonomy );
1962 do_action("edit_term", $term_id, $tt_id, $taxonomy);
1963 do_action("edit_$taxonomy", $term_id, $tt_id);
1965 $term_id = apply_filters('term_id_filter', $term_id, $tt_id);
1967 clean_term_cache($term_id, $taxonomy);
1969 do_action("edited_term", $term_id, $tt_id, $taxonomy);
1970 do_action("edited_$taxonomy", $term_id, $tt_id);
1972 return array('term_id' => $term_id, 'term_taxonomy_id' => $tt_id);
1976 * Enable or disable term counting.
1980 * @param bool $defer Optional. Enable if true, disable if false.
1981 * @return bool Whether term counting is enabled or disabled.
1983 function wp_defer_term_counting($defer=null) {
1984 static $_defer = false;
1986 if ( is_bool($defer) ) {
1988 // flush any deferred counts
1990 wp_update_term_count( null, null, true );
1997 * Updates the amount of terms in taxonomy.
1999 * If there is a taxonomy callback applyed, then it will be called for updating
2002 * The default action is to count what the amount of terms have the relationship
2003 * of term ID. Once that is done, then update the database.
2005 * @package WordPress
2006 * @subpackage Taxonomy
2010 * @param int|array $terms The term_taxonomy_id of the terms
2011 * @param string $taxonomy The context of the term.
2012 * @return bool If no terms will return false, and if successful will return true.
2014 function wp_update_term_count( $terms, $taxonomy, $do_deferred=false ) {
2015 static $_deferred = array();
2017 if ( $do_deferred ) {
2018 foreach ( (array) array_keys($_deferred) as $tax ) {
2019 wp_update_term_count_now( $_deferred[$tax], $tax );
2020 unset( $_deferred[$tax] );
2024 if ( empty($terms) )
2027 if ( !is_array($terms) )
2028 $terms = array($terms);
2030 if ( wp_defer_term_counting() ) {
2031 if ( !isset($_deferred[$taxonomy]) )
2032 $_deferred[$taxonomy] = array();
2033 $_deferred[$taxonomy] = array_unique( array_merge($_deferred[$taxonomy], $terms) );
2037 return wp_update_term_count_now( $terms, $taxonomy );
2041 * Perform term count update immediately.
2045 * @param array $terms The term_taxonomy_id of terms to update.
2046 * @param string $taxonomy The context of the term.
2047 * @return bool Always true when complete.
2049 function wp_update_term_count_now( $terms, $taxonomy ) {
2052 $terms = array_map('intval', $terms);
2054 $taxonomy = get_taxonomy($taxonomy);
2055 if ( !empty($taxonomy->update_count_callback) ) {
2056 call_user_func($taxonomy->update_count_callback, $terms, $taxonomy);
2058 // Default count updater
2059 foreach ( (array) $terms as $term) {
2060 $count = $wpdb->get_var( $wpdb->prepare( "SELECT COUNT(*) FROM $wpdb->term_relationships WHERE term_taxonomy_id = %d", $term) );
2061 do_action( 'edit_term_taxonomy', $term, $taxonomy );
2062 $wpdb->update( $wpdb->term_taxonomy, compact( 'count' ), array( 'term_taxonomy_id' => $term ) );
2063 do_action( 'edited_term_taxonomy', $term, $taxonomy );
2068 clean_term_cache($terms, '', false);
2079 * Removes the taxonomy relationship to terms from the cache.
2081 * Will remove the entire taxonomy relationship containing term $object_id. The
2082 * term IDs have to exist within the taxonomy $object_type for the deletion to
2085 * @package WordPress
2086 * @subpackage Taxonomy
2089 * @see get_object_taxonomies() for more on $object_type
2090 * @uses do_action() Will call action hook named, 'clean_object_term_cache' after completion.
2091 * Passes, function params in same order.
2093 * @param int|array $object_ids Single or list of term object ID(s)
2094 * @param array|string $object_type The taxonomy object type
2096 function clean_object_term_cache($object_ids, $object_type) {
2097 if ( !is_array($object_ids) )
2098 $object_ids = array($object_ids);
2100 foreach ( $object_ids as $id )
2101 foreach ( get_object_taxonomies($object_type) as $taxonomy )
2102 wp_cache_delete($id, "{$taxonomy}_relationships");
2104 do_action('clean_object_term_cache', $object_ids, $object_type);
2109 * Will remove all of the term ids from the cache.
2111 * @package WordPress
2112 * @subpackage Taxonomy
2116 * @param int|array $ids Single or list of Term IDs
2117 * @param string $taxonomy Can be empty and will assume tt_ids, else will use for context.
2118 * @param bool $clean_taxonomy Whether to clean taxonomy wide caches (true), or just individual term object caches (false). Default is true.
2120 function clean_term_cache($ids, $taxonomy = '', $clean_taxonomy = true) {
2122 static $cleaned = array();
2124 if ( !is_array($ids) )
2127 $taxonomies = array();
2128 // If no taxonomy, assume tt_ids.
2129 if ( empty($taxonomy) ) {
2130 $tt_ids = array_map('intval', $ids);
2131 $tt_ids = implode(', ', $tt_ids);
2132 $terms = $wpdb->get_results("SELECT term_id, taxonomy FROM $wpdb->term_taxonomy WHERE term_taxonomy_id IN ($tt_ids)");
2134 foreach ( (array) $terms as $term ) {
2135 $taxonomies[] = $term->taxonomy;
2136 $ids[] = $term->term_id;
2137 wp_cache_delete($term->term_id, $term->taxonomy);
2139 $taxonomies = array_unique($taxonomies);
2141 $taxonomies = array($taxonomy);
2142 foreach ( $taxonomies as $taxonomy ) {
2143 foreach ( $ids as $id ) {
2144 wp_cache_delete($id, $taxonomy);
2149 foreach ( $taxonomies as $taxonomy ) {
2150 if ( isset($cleaned[$taxonomy]) )
2152 $cleaned[$taxonomy] = true;
2154 if ( $clean_taxonomy ) {
2155 wp_cache_delete('all_ids', $taxonomy);
2156 wp_cache_delete('get', $taxonomy);
2157 delete_option("{$taxonomy}_children");
2158 // Regenerate {$taxonomy}_children
2159 _get_term_hierarchy($taxonomy);
2162 do_action('clean_term_cache', $ids, $taxonomy);
2165 wp_cache_set('last_changed', time(), 'terms');
2170 * Retrieves the taxonomy relationship to the term object id.
2172 * @package WordPress
2173 * @subpackage Taxonomy
2176 * @uses wp_cache_get() Retrieves taxonomy relationship from cache
2178 * @param int|array $id Term object ID
2179 * @param string $taxonomy Taxonomy Name
2180 * @return bool|array Empty array if $terms found, but not $taxonomy. False if nothing is in cache for $taxonomy and $id.
2182 function &get_object_term_cache($id, $taxonomy) {
2183 $cache = wp_cache_get($id, "{$taxonomy}_relationships");
2189 * Updates the cache for Term ID(s).
2191 * Will only update the cache for terms not already cached.
2193 * The $object_ids expects that the ids be separated by commas, if it is a
2196 * It should be noted that update_object_term_cache() is very time extensive. It
2197 * is advised that the function is not called very often or at least not for a
2198 * lot of terms that exist in a lot of taxonomies. The amount of time increases
2199 * for each term and it also increases for each taxonomy the term belongs to.
2201 * @package WordPress
2202 * @subpackage Taxonomy
2204 * @uses wp_get_object_terms() Used to get terms from the database to update
2206 * @param string|array $object_ids Single or list of term object ID(s)
2207 * @param array|string $object_type The taxonomy object type
2208 * @return null|bool Null value is given with empty $object_ids. False if
2210 function update_object_term_cache($object_ids, $object_type) {
2211 if ( empty($object_ids) )
2214 if ( !is_array($object_ids) )
2215 $object_ids = explode(',', $object_ids);
2217 $object_ids = array_map('intval', $object_ids);
2219 $taxonomies = get_object_taxonomies($object_type);
2222 foreach ( (array) $object_ids as $id ) {
2223 foreach ( $taxonomies as $taxonomy ) {
2224 if ( false === wp_cache_get($id, "{$taxonomy}_relationships") ) {
2231 if ( empty( $ids ) )
2234 $terms = wp_get_object_terms($ids, $taxonomies, array('fields' => 'all_with_object_id'));
2236 $object_terms = array();
2237 foreach ( (array) $terms as $term )
2238 $object_terms[$term->object_id][$term->taxonomy][$term->term_id] = $term;
2240 foreach ( $ids as $id ) {
2241 foreach ( $taxonomies as $taxonomy ) {
2242 if ( ! isset($object_terms[$id][$taxonomy]) ) {
2243 if ( !isset($object_terms[$id]) )
2244 $object_terms[$id] = array();
2245 $object_terms[$id][$taxonomy] = array();
2250 foreach ( $object_terms as $id => $value ) {
2251 foreach ( $value as $taxonomy => $terms ) {
2252 wp_cache_set($id, $terms, "{$taxonomy}_relationships");
2259 * Updates Terms to Taxonomy in cache.
2261 * @package WordPress
2262 * @subpackage Taxonomy
2265 * @param array $terms List of Term objects to change
2266 * @param string $taxonomy Optional. Update Term to this taxonomy in cache
2268 function update_term_cache($terms, $taxonomy = '') {
2269 foreach ( (array) $terms as $term ) {
2270 $term_taxonomy = $taxonomy;
2271 if ( empty($term_taxonomy) )
2272 $term_taxonomy = $term->taxonomy;
2274 wp_cache_add($term->term_id, $term, $term_taxonomy);
2284 * Retrieves children of taxonomy as Term IDs.
2286 * @package WordPress
2287 * @subpackage Taxonomy
2291 * @uses update_option() Stores all of the children in "$taxonomy_children"
2292 * option. That is the name of the taxonomy, immediately followed by '_children'.
2294 * @param string $taxonomy Taxonomy Name
2295 * @return array Empty if $taxonomy isn't hierarchical or returns children as Term IDs.
2297 function _get_term_hierarchy($taxonomy) {
2298 if ( !is_taxonomy_hierarchical($taxonomy) )
2300 $children = get_option("{$taxonomy}_children");
2302 if ( is_array($children) )
2304 $children = array();
2305 $terms = get_terms($taxonomy, array('get' => 'all', 'orderby' => 'id', 'fields' => 'id=>parent'));
2306 foreach ( $terms as $term_id => $parent ) {
2308 $children[$parent][] = $term_id;
2310 update_option("{$taxonomy}_children", $children);
2317 * Get the subset of $terms that are descendants of $term_id.
2319 * If $terms is an array of objects, then _get_term_children returns an array of objects.
2320 * If $terms is an array of IDs, then _get_term_children returns an array of IDs.
2322 * @package WordPress
2323 * @subpackage Taxonomy
2327 * @param int $term_id The ancestor term: all returned terms should be descendants of $term_id.
2328 * @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.
2329 * @param string $taxonomy The taxonomy which determines the hierarchy of the terms.
2330 * @return array The subset of $terms that are descendants of $term_id.
2332 function &_get_term_children($term_id, $terms, $taxonomy) {
2333 $empty_array = array();
2334 if ( empty($terms) )
2335 return $empty_array;
2337 $term_list = array();
2338 $has_children = _get_term_hierarchy($taxonomy);
2340 if ( ( 0 != $term_id ) && ! isset($has_children[$term_id]) )
2341 return $empty_array;
2343 foreach ( (array) $terms as $term ) {
2345 if ( !is_object($term) ) {
2346 $term = get_term($term, $taxonomy);
2347 if ( is_wp_error( $term ) )
2352 if ( $term->term_id == $term_id )
2355 if ( $term->parent == $term_id ) {
2357 $term_list[] = $term->term_id;
2359 $term_list[] = $term;
2361 if ( !isset($has_children[$term->term_id]) )
2364 if ( $children = _get_term_children($term->term_id, $terms, $taxonomy) )
2365 $term_list = array_merge($term_list, $children);
2374 * Add count of children to parent count.
2376 * Recalculates term counts by including items from child terms. Assumes all
2377 * relevant children are already in the $terms argument.
2379 * @package WordPress
2380 * @subpackage Taxonomy
2385 * @param array $terms List of Term IDs
2386 * @param string $taxonomy Term Context
2387 * @return null Will break from function if conditions are not met.
2389 function _pad_term_counts(&$terms, $taxonomy) {
2392 // This function only works for hierarchical taxonomies like post categories.
2393 if ( !is_taxonomy_hierarchical( $taxonomy ) )
2396 $term_hier = _get_term_hierarchy($taxonomy);
2398 if ( empty($term_hier) )
2401 $term_items = array();
2403 foreach ( (array) $terms as $key => $term ) {
2404 $terms_by_id[$term->term_id] = & $terms[$key];
2405 $term_ids[$term->term_taxonomy_id] = $term->term_id;
2408 // Get the object and term ids and stick them in a lookup table
2409 $tax_obj = get_taxonomy($taxonomy);
2410 $object_types = esc_sql($tax_obj->object_type);
2411 $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'");
2412 foreach ( $results as $row ) {
2413 $id = $term_ids[$row->term_taxonomy_id];
2414 $term_items[$id][$row->object_id] = isset($term_items[$id][$row->object_id]) ? ++$term_items[$id][$row->object_id] : 1;
2417 // Touch every ancestor's lookup row for each post in each term
2418 foreach ( $term_ids as $term_id ) {
2420 while ( $parent = $terms_by_id[$child]->parent ) {
2421 if ( !empty($term_items[$term_id]) )
2422 foreach ( $term_items[$term_id] as $item_id => $touches ) {
2423 $term_items[$parent][$item_id] = isset($term_items[$parent][$item_id]) ? ++$term_items[$parent][$item_id]: 1;
2429 // Transfer the touched cells
2430 foreach ( (array) $term_items as $id => $items )
2431 if ( isset($terms_by_id[$id]) )
2432 $terms_by_id[$id]->count = count($items);
2436 // Default callbacks
2440 * Will update term count based on object types of the current taxonomy.
2442 * Private function for the default callback for post_tag and category
2445 * @package WordPress
2446 * @subpackage Taxonomy
2451 * @param array $terms List of Term taxonomy IDs
2452 * @param object $taxonomy Current taxonomy object of terms
2454 function _update_post_term_count( $terms, $taxonomy ) {
2457 $object_types = is_array($taxonomy->object_type) ? $taxonomy->object_type : array($taxonomy->object_type);
2458 $object_types = esc_sql($object_types);
2460 foreach ( (array) $terms as $term ) {
2461 $count = $wpdb->get_var( $wpdb->prepare( "SELECT COUNT(*) FROM $wpdb->term_relationships, $wpdb->posts WHERE $wpdb->posts.ID = $wpdb->term_relationships.object_id AND post_status = 'publish' AND post_type IN ('" . implode("', '", $object_types) . "') AND term_taxonomy_id = %d", $term ) );
2462 do_action( 'edit_term_taxonomy', $term, $taxonomy );
2463 $wpdb->update( $wpdb->term_taxonomy, compact( 'count' ), array( 'term_taxonomy_id' => $term ) );
2464 do_action( 'edited_term_taxonomy', $term, $taxonomy );
2470 * Generates a permalink for a taxonomy term archive.
2474 * @param object|int|string $term
2475 * @param string $taxonomy
2476 * @return string HTML link to taxonomy term archive
2478 function get_term_link( $term, $taxonomy ) {
2481 if ( !is_object($term) ) {
2482 if ( is_int($term) ) {
2483 $term = &get_term($term, $taxonomy);
2485 $term = &get_term_by('slug', $term, $taxonomy);
2489 if ( !is_object($term) )
2490 $term = new WP_Error('invalid_term', __('Empty Term'));
2492 if ( is_wp_error( $term ) )
2495 // use legacy functions for core taxonomies until they are fully plugged in
2496 if ( $taxonomy == 'category' )
2497 return get_category_link((int) $term->term_id);
2498 if ( $taxonomy == 'post_tag' )
2499 return get_tag_link((int) $term->term_id);
2501 $termlink = $wp_rewrite->get_extra_permastruct($taxonomy);
2503 $slug = $term->slug;
2505 if ( empty($termlink) ) {
2506 $t = get_taxonomy($taxonomy);
2507 if ( $t->query_var )
2508 $termlink = "?$t->query_var=$slug";
2510 $termlink = "?taxonomy=$taxonomy&term=$slug";
2511 $termlink = home_url($termlink);
2513 $termlink = str_replace("%$taxonomy%", $slug, $termlink);
2514 $termlink = home_url( user_trailingslashit($termlink, 'category') );
2516 return apply_filters('term_link', $termlink, $term, $taxonomy);
2520 * Display the taxonomies of a post with available options.
2522 * This function can be used within the loop to display the taxonomies for a
2523 * post without specifying the Post ID. You can also use it outside the Loop to
2524 * display the taxonomies for a specific post.
2526 * The available defaults are:
2527 * 'post' : default is 0. The post ID to get taxonomies of.
2528 * 'before' : default is empty string. Display before taxonomies list.
2529 * 'sep' : default is empty string. Separate every taxonomy with value in this.
2530 * 'after' : default is empty string. Display this after the taxonomies list.
2533 * @uses get_the_taxonomies()
2535 * @param array $args Override the defaults.
2537 function the_taxonomies($args = array()) {
2545 $r = wp_parse_args( $args, $defaults );
2546 extract( $r, EXTR_SKIP );
2548 echo $before . join($sep, get_the_taxonomies($post)) . $after;
2552 * Retrieve all taxonomies associated with a post.
2554 * This function can be used within the loop. It will also return an array of
2555 * the taxonomies with links to the taxonomy and name.
2559 * @param int $post Optional. Post ID or will use Global Post ID (in loop).
2562 function get_the_taxonomies($post = 0) {
2563 if ( is_int($post) )
2564 $post =& get_post($post);
2565 elseif ( !is_object($post) )
2566 $post =& $GLOBALS['post'];
2568 $taxonomies = array();
2573 $template = apply_filters('taxonomy_template', '%s: %l.');
2575 foreach ( get_object_taxonomies($post) as $taxonomy ) {
2576 $t = (array) get_taxonomy($taxonomy);
2577 if ( empty($t['label']) )
2578 $t['label'] = $taxonomy;
2579 if ( empty($t['args']) )
2580 $t['args'] = array();
2581 if ( empty($t['template']) )
2582 $t['template'] = $template;
2584 $terms = get_object_term_cache($post->ID, $taxonomy);
2585 if ( empty($terms) )
2586 $terms = wp_get_object_terms($post->ID, $taxonomy, $t['args']);
2590 foreach ( $terms as $term )
2591 $links[] = "<a href='" . esc_attr(get_term_link($term, $taxonomy)) . "'>$term->name</a>";
2594 $taxonomies[$taxonomy] = wp_sprintf($t['template'], $t['label'], $links, $terms);
2600 * Retrieve all taxonomies of a post with just the names.
2603 * @uses get_object_taxonomies()
2605 * @param int $post Optional. Post ID
2608 function get_post_taxonomies($post = 0) {
2609 $post =& get_post($post);
2611 return get_object_taxonomies($post);
2615 * Determine if the given object is associated with any of the given terms.
2617 * The given terms are checked against the object's terms' term_ids, names and slugs.
2618 * Terms given as integers will only be checked against the object's terms' term_ids.
2619 * If no terms are given, determines if object is associated with any terms in the given taxonomy.
2622 * @uses get_object_term_cache()
2623 * @uses wp_get_object_terms()
2625 * @param int $object_id. ID of the object (post ID, link ID, ...)
2626 * @param string $taxonomy. Single taxonomy name
2627 * @param int|string|array $terms Optional. Term term_id, name, slug or array of said
2628 * @return bool|WP_Error. WP_Error on input error.
2630 function is_object_in_term( $object_id, $taxonomy, $terms = null ) {
2631 if ( !$object_id = (int) $object_id )
2632 return new WP_Error( 'invalid_object', __( 'Invalid object ID' ) );
2634 $object_terms = get_object_term_cache( $object_id, $taxonomy );
2635 if ( empty( $object_terms ) )
2636 $object_terms = wp_get_object_terms( $object_id, $taxonomy );
2638 if ( is_wp_error( $object_terms ) )
2639 return $object_terms;
2640 if ( empty( $object_terms ) )
2642 if ( empty( $terms ) )
2643 return ( !empty( $object_terms ) );
2645 $terms = (array) $terms;
2647 if ( $ints = array_filter( $terms, 'is_int' ) )
2648 $strs = array_diff( $terms, $ints );
2652 foreach ( $object_terms as $object_term ) {
2653 if ( $ints && in_array( $object_term->term_id, $ints ) ) return true; // If int, check against term_id
2655 if ( in_array( $object_term->term_id, $strs ) ) return true;
2656 if ( in_array( $object_term->name, $strs ) ) return true;
2657 if ( in_array( $object_term->slug, $strs ) ) return true;
2665 * Determine if the given object type is associated with the given taxonomy.
2668 * @uses get_object_taxonomies()
2670 * @param string $object_type Object type string
2671 * @param string $taxonomy. Single taxonomy name
2672 * @return bool True if object is associated with the taxonomy, otherwise false.
2674 function is_object_in_taxonomy($object_type, $taxonomy) {
2675 $taxonomies = get_object_taxonomies($object_type);
2677 if ( empty($taxonomies) )
2680 if ( in_array($taxonomy, $taxonomies) )