9 // Taxonomy Registration
13 * Default Taxonomy Objects
15 * @global array $wp_taxonomies
17 $wp_taxonomies = array();
18 $wp_taxonomies['category'] = (object) array('name' => 'category', 'object_type' => 'post', 'hierarchical' => true, 'update_count_callback' => '_update_post_term_count');
19 $wp_taxonomies['post_tag'] = (object) array('name' => 'post_tag', 'object_type' => 'post', 'hierarchical' => false, 'update_count_callback' => '_update_post_term_count');
20 $wp_taxonomies['link_category'] = (object) array('name' => 'link_category', 'object_type' => 'link', 'hierarchical' => false);
23 * get_object_taxonomies() - Return all of the taxonomy names that are of $object_type
25 * It appears that this function can be used to find all of the names inside of
26 * $wp_taxonomies global variable.
28 * <code><?php $taxonomies = get_object_taxonomies('post'); ?></code>
29 * Should result in <code>Array('category', 'post_tag')</code>
32 * @subpackage Taxonomy
35 * @uses $wp_taxonomies
37 * @param array|string|object $object Name of the type of taxonomy object, or an object (row from posts)
38 * @return array The names of all taxonomy of $object_type.
40 function get_object_taxonomies($object) {
41 global $wp_taxonomies;
43 if ( is_object($object) ) {
44 if ( $object->post_type == 'attachment' )
45 return get_attachment_taxonomies($object);
46 $object = $object->post_type;
49 $object = (array) $object;
51 $taxonomies = array();
52 foreach ( $wp_taxonomies as $taxonomy ) {
53 if ( array_intersect($object, (array) $taxonomy->object_type) )
54 $taxonomies[] = $taxonomy->name;
61 * get_taxonomy() - Returns the taxonomy object of $taxonomy.
63 * The get_taxonomy function will first check that the parameter string given
64 * is a taxonomy object and if it is, it will return it.
67 * @subpackage Taxonomy
70 * @uses $wp_taxonomies
71 * @uses is_taxonomy() Checks whether taxonomy exists
73 * @param string $taxonomy Name of taxonomy object to return
74 * @return object|bool The Taxonomy Object or false if $taxonomy doesn't exist
76 function get_taxonomy( $taxonomy ) {
77 global $wp_taxonomies;
79 if ( ! is_taxonomy($taxonomy) )
82 return $wp_taxonomies[$taxonomy];
86 * is_taxonomy() - Checks that the taxonomy name exists
89 * @subpackage Taxonomy
92 * @uses $wp_taxonomies
94 * @param string $taxonomy Name of taxonomy object
95 * @return bool Whether the taxonomy exists or not.
97 function is_taxonomy( $taxonomy ) {
98 global $wp_taxonomies;
100 return isset($wp_taxonomies[$taxonomy]);
104 * is_taxonomy_hierarchical() - Whether the taxonomy object is hierarchical
106 * Checks to make sure that the taxonomy is an object first. Then Gets the object, and finally
107 * returns the hierarchical value in the object.
109 * A false return value might also mean that the taxonomy does not exist.
112 * @subpackage Taxonomy
115 * @uses is_taxonomy() Checks whether taxonomy exists
116 * @uses get_taxonomy() Used to get the taxonomy object
118 * @param string $taxonomy Name of taxonomy object
119 * @return bool Whether the taxonomy is hierarchical
121 function is_taxonomy_hierarchical($taxonomy) {
122 if ( ! is_taxonomy($taxonomy) )
125 $taxonomy = get_taxonomy($taxonomy);
126 return $taxonomy->hierarchical;
130 * register_taxonomy() - Create or modify a taxonomy object. Do not use before init.
132 * A simple function for creating or modifying a taxonomy object based on the parameters given.
133 * The function will accept an array (third optional parameter), along with strings for the
134 * taxonomy name and another string for the object type.
136 * Nothing is returned, so expect error maybe or use is_taxonomy() to check whether taxonomy exists.
138 * Optional $args contents:
139 * hierarachical - has some defined purpose at other parts of the API and is a boolean value.
140 * update_count_callback - works much like a hook, in that it will be called when the count is updated.
141 * rewrite - false to prevent rewrite, or array('slug'=>$slug) to customize permastruct; default will use $taxonomy as slug
142 * query_var - false to prevent queries, or string to customize query var (?$query_var=$term); default will use $taxonomy as query var
145 * @subpackage Taxonomy
147 * @uses $wp_taxonomies Inserts new taxonomy object into the list
148 * @uses $wp_rewrite Adds rewrite tags and permastructs
149 * @uses $wp Adds query vars
151 * @param string $taxonomy Name of taxonomy object
152 * @param array|string $object_type Name of the object type for the taxonomy object.
153 * @param array|string $args See above description for the two keys values.
155 function register_taxonomy( $taxonomy, $object_type, $args = array() ) {
156 global $wp_taxonomies, $wp_rewrite, $wp;
158 $defaults = array('hierarchical' => false, 'update_count_callback' => '', 'rewrite' => true, 'query_var' => true);
159 $args = wp_parse_args($args, $defaults);
161 if ( false !== $args['query_var'] && !empty($wp) ) {
162 if ( empty($args['query_var']) )
163 $args['query_var'] = $taxonomy;
164 $args['query_var'] = sanitize_title_with_dashes($args['query_var']);
165 $wp->add_query_var($args['query_var']);
168 if ( false !== $args['rewrite'] && !empty($wp_rewrite) ) {
169 if ( !is_array($args['rewrite']) )
170 $args['rewrite'] = array();
171 if ( !isset($args['rewrite']['slug']) )
172 $args['rewrite']['slug'] = sanitize_title_with_dashes($taxonomy);
173 $wp_rewrite->add_rewrite_tag("%$taxonomy%", '([^/]+)', $args['query_var'] ? "{$args['query_var']}=" : "taxonomy=$taxonomy&term=$term");
174 $wp_rewrite->add_permastruct($taxonomy, "{$args['rewrite']['slug']}/%$taxonomy%");
177 $args['name'] = $taxonomy;
178 $args['object_type'] = $object_type;
179 $wp_taxonomies[$taxonomy] = (object) $args;
187 * get_objects_in_term() - Return object_ids of valid taxonomy and term
189 * The strings of $taxonomies must exist before this function will continue. On failure of finding
190 * a valid taxonomy, it will return an WP_Error class, kind of like Exceptions in PHP 5, except you
191 * can't catch them. Even so, you can still test for the WP_Error class and get the error message.
193 * The $terms aren't checked the same as $taxonomies, but still need to exist for $object_ids to
196 * It is possible to change the order that object_ids is returned by either using PHP sort family
197 * functions or using the database by using $args with either ASC or DESC array. The value should
198 * be in the key named 'order'.
201 * @subpackage Taxonomy
205 * @uses wp_parse_args() Creates an array from string $args.
207 * @param string|array $terms String of term or array of string values of terms that will be used
208 * @param string|array $taxonomies String of taxonomy name or Array of string values of taxonomy names
209 * @param array|string $args Change the order of the object_ids, either ASC or DESC
210 * @return WP_Error|array If the taxonomy does not exist, then WP_Error will be returned. On success
211 * the array can be empty meaning that there are no $object_ids found or it will return the $object_ids found.
213 function get_objects_in_term( $terms, $taxonomies, $args = array() ) {
216 if ( !is_array( $terms) )
217 $terms = array($terms);
219 if ( !is_array($taxonomies) )
220 $taxonomies = array($taxonomies);
222 foreach ( $taxonomies as $taxonomy ) {
223 if ( ! is_taxonomy($taxonomy) )
224 return new WP_Error('invalid_taxonomy', __('Invalid Taxonomy'));
227 $defaults = array('order' => 'ASC');
228 $args = wp_parse_args( $args, $defaults );
229 extract($args, EXTR_SKIP);
231 $order = ( 'desc' == strtolower($order) ) ? 'DESC' : 'ASC';
233 $terms = array_map('intval', $terms);
235 $taxonomies = "'" . implode("', '", $taxonomies) . "'";
236 $terms = "'" . implode("', '", $terms) . "'";
238 $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 ($terms) ORDER BY tr.object_id $order");
247 * get_term() - Get all Term data from database by Term ID.
249 * The usage of the get_term function is to apply filters to a term object.
250 * It is possible to get a term object from the database before applying the
253 * $term ID must be part of $taxonomy, to get from the database. Failure, might be
254 * able to be captured by the hooks. Failure would be the same value as $wpdb returns for the
257 * There are two hooks, one is specifically for each term, named 'get_term', and the second is
258 * for the taxonomy name, 'term_$taxonomy'. Both hooks gets the term object, and the taxonomy
259 * name as parameters. Both hooks are expected to return a Term object.
261 * 'get_term' hook - Takes two parameters the term Object and the taxonomy name. Must return
262 * term object. Used in get_term() as a catch-all filter for every $term.
264 * 'get_$taxonomy' hook - Takes two parameters the term Object and the taxonomy name. Must return
265 * term object. $taxonomy will be the taxonomy name, so for example, if 'category', it would be
266 * 'get_category' as the filter name. Useful for custom taxonomies or plugging into default taxonomies.
269 * @subpackage Taxonomy
273 * @uses sanitize_term() Cleanses the term based on $filter context before returning.
274 * @see sanitize_term_field() The $context param lists the available values for get_term_by() $filter param.
276 * @param int|object $term If integer, will get from database. If object will apply filters and return $term.
277 * @param string $taxonomy Taxonomy name that $term is part of.
278 * @param string $output Constant OBJECT, ARRAY_A, or ARRAY_N
279 * @param string $filter Optional, default is raw or no WordPress defined filter will applied.
280 * @return mixed|null|WP_Error Term Row from database. Will return null if $term is empty. If taxonomy does not
281 * exist then WP_Error will be returned.
283 function &get_term($term, $taxonomy, $output = OBJECT, $filter = 'raw') {
289 if ( ! is_taxonomy($taxonomy) )
290 return new WP_Error('invalid_taxonomy', __('Invalid Taxonomy'));
292 if ( is_object($term) ) {
293 wp_cache_add($term->term_id, $term, $taxonomy);
297 if ( ! $_term = wp_cache_get($term, $taxonomy) ) {
298 $_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) );
299 wp_cache_add($term, $_term, $taxonomy);
303 $_term = apply_filters('get_term', $_term, $taxonomy);
304 $_term = apply_filters("get_$taxonomy", $_term, $taxonomy);
305 $_term = sanitize_term($_term, $taxonomy, $filter);
307 if ( $output == OBJECT ) {
309 } elseif ( $output == ARRAY_A ) {
310 return get_object_vars($_term);
311 } elseif ( $output == ARRAY_N ) {
312 return array_values(get_object_vars($_term));
319 * get_term_by() - Get all Term data from database by Term field and data.
321 * Warning: $value is not escaped for 'name' $field. You must do it yourself, if required.
323 * The default $field is 'id', therefore it is possible to also use null for field, but not
324 * recommended that you do so.
326 * If $value does not exist, the return value will be false. If $taxonomy exists and $field
327 * and $value combinations exist, the Term will be returned.
330 * @subpackage Taxonomy
334 * @uses sanitize_term() Cleanses the term based on $filter context before returning.
335 * @see sanitize_term_field() The $context param lists the available values for get_term_by() $filter param.
337 * @param string $field Either 'slug', 'name', or 'id'
338 * @param string|int $value Search for this term value
339 * @param string $taxonomy Taxonomy Name
340 * @param string $output Constant OBJECT, ARRAY_A, or ARRAY_N
341 * @param string $filter Optional, default is raw or no WordPress defined filter will applied.
342 * @return mixed Term Row from database. Will return false if $taxonomy does not exist or $term was not found.
344 function get_term_by($field, $value, $taxonomy, $output = OBJECT, $filter = 'raw') {
347 if ( ! is_taxonomy($taxonomy) )
350 if ( 'slug' == $field ) {
352 $value = sanitize_title($value);
355 } else if ( 'name' == $field ) {
356 // Assume already escaped
359 $field = 't.term_id';
360 $value = (int) $value;
363 $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) );
367 wp_cache_add($term->term_id, $term, $taxonomy);
369 $term = sanitize_term($term, $taxonomy, $filter);
371 if ( $output == OBJECT ) {
373 } elseif ( $output == ARRAY_A ) {
374 return get_object_vars($term);
375 } elseif ( $output == ARRAY_N ) {
376 return array_values(get_object_vars($term));
383 * get_term_children() - Merge all term children into a single array.
385 * This recursive function will merge all of the children of $term into
386 * the same array. Only useful for taxonomies which are hierarchical.
388 * Will return an empty array if $term does not exist in $taxonomy.
391 * @subpackage Taxonomy
395 * @uses _get_term_hierarchy()
396 * @uses get_term_children() Used to get the children of both $taxonomy and the parent $term
398 * @param string $term Name of Term to get children
399 * @param string $taxonomy Taxonomy Name
400 * @return array|WP_Error List of Term Objects. WP_Error returned if $taxonomy does not exist
402 function get_term_children( $term, $taxonomy ) {
403 if ( ! is_taxonomy($taxonomy) )
404 return new WP_Error('invalid_taxonomy', __('Invalid Taxonomy'));
406 $terms = _get_term_hierarchy($taxonomy);
408 if ( ! isset($terms[$term]) )
411 $children = $terms[$term];
413 foreach ( $terms[$term] as $child ) {
414 if ( isset($terms[$child]) )
415 $children = array_merge($children, get_term_children($child, $taxonomy));
422 * get_term_field() - Get sanitized Term field
424 * Does checks for $term, based on the $taxonomy. The function is for
425 * contextual reasons and for simplicity of usage. See sanitize_term_field() for
429 * @subpackage Taxonomy
432 * @uses sanitize_term_field() Passes the return value in sanitize_term_field on success.
434 * @param string $field Term field to fetch
435 * @param int $term Term ID
436 * @param string $taxonomy Taxonomy Name
437 * @param string $context Optional, default is display. Look at sanitize_term_field() for available options.
438 * @return mixed Will return an empty string if $term is not an object or if $field is not set in $term.
440 function get_term_field( $field, $term, $taxonomy, $context = 'display' ) {
442 $term = get_term( $term, $taxonomy );
443 if ( is_wp_error($term) )
446 if ( !is_object($term) )
449 if ( !isset($term->$field) )
452 return sanitize_term_field($field, $term->$field, $term->term_id, $taxonomy, $context);
456 * get_term_to_edit() - Sanitizes Term for editing
458 * Return value is sanitize_term() and usage is for sanitizing the term
459 * for editing. Function is for contextual and simplicity.
462 * @subpackage Taxonomy
465 * @uses sanitize_term() Passes the return value on success
467 * @param int|object $id Term ID or Object
468 * @param string $taxonomy Taxonomy Name
469 * @return mixed|null|WP_Error Will return empty string if $term is not an object.
471 function get_term_to_edit( $id, $taxonomy ) {
472 $term = get_term( $id, $taxonomy );
474 if ( is_wp_error($term) )
477 if ( !is_object($term) )
480 return sanitize_term($term, $taxonomy, 'edit');
484 * get_terms() - Retrieve the terms in taxonomy or list of taxonomies.
486 * You can fully inject any customizations to the query before it is sent, as well as control
487 * the output with a filter.
489 * The 'get_terms' filter will be called when the cache has the term and will pass the found
490 * term along with the array of $taxonomies and array of $args. This filter is also called
491 * before the array of terms is passed and will pass the array of terms, along with the $taxonomies
494 * The 'list_terms_exclusions' filter passes the compiled exclusions along with the $args.
496 * The list that $args can contain, which will overwrite the defaults.
497 * orderby - Default is 'name'. Can be name, count, or nothing (will use term_id).
498 * order - Default is ASC. Can use DESC.
499 * hide_empty - Default is true. Will not return empty $terms.
500 * fields - Default is all.
501 * slug - Any terms that has this value. Default is empty string.
502 * hierarchical - Whether to return hierarchical taxonomy. Default is true.
503 * name__like - Default is empty string.
505 * The argument 'pad_counts' will count all of the children along with the $terms.
507 * The 'get' argument allows for overwriting 'hide_empty' and 'child_of', which can be done by
508 * setting the value to 'all', instead of its default empty string value.
510 * The 'child_of' argument will be used if you use multiple taxonomy or the first $taxonomy
511 * isn't hierarchical or 'parent' isn't used. The default is 0, which will be translated to
512 * a false value. If 'child_of' is set, then 'child_of' value will be tested against
513 * $taxonomy to see if 'child_of' is contained within. Will return an empty array if test
516 * If 'parent' is set, then it will be used to test against the first taxonomy. Much like
517 * 'child_of'. Will return an empty array if the test fails.
520 * @subpackage Taxonomy
524 * @uses wp_parse_args() Merges the defaults with those defined by $args and allows for strings.
527 * @param string|array Taxonomy name or list of Taxonomy names
528 * @param string|array $args The values of what to search for when returning terms
529 * @return array|WP_Error List of Term Objects and their children. Will return WP_Error, if any of $taxonomies do not exist.
531 function &get_terms($taxonomies, $args = '') {
533 $empty_array = array();
535 $single_taxonomy = false;
536 if ( !is_array($taxonomies) ) {
537 $single_taxonomy = true;
538 $taxonomies = array($taxonomies);
541 foreach ( $taxonomies as $taxonomy ) {
542 if ( ! is_taxonomy($taxonomy) )
543 return new WP_Error('invalid_taxonomy', __('Invalid Taxonomy'));
546 $in_taxonomies = "'" . implode("', '", $taxonomies) . "'";
548 $defaults = array('orderby' => 'name', 'order' => 'ASC',
549 'hide_empty' => true, 'exclude' => '', 'include' => '',
550 'number' => '', 'fields' => 'all', 'slug' => '', 'parent' => '',
551 'hierarchical' => true, 'child_of' => 0, 'get' => '', 'name__like' => '',
552 'pad_counts' => false, 'offset' => '', 'search' => '');
553 $args = wp_parse_args( $args, $defaults );
554 $args['number'] = absint( $args['number'] );
555 $args['offset'] = absint( $args['offset'] );
556 if ( !$single_taxonomy || !is_taxonomy_hierarchical($taxonomies[0]) ||
557 '' != $args['parent'] ) {
558 $args['child_of'] = 0;
559 $args['hierarchical'] = false;
560 $args['pad_counts'] = false;
563 if ( 'all' == $args['get'] ) {
564 $args['child_of'] = 0;
565 $args['hide_empty'] = 0;
566 $args['hierarchical'] = false;
567 $args['pad_counts'] = false;
569 extract($args, EXTR_SKIP);
572 $hierarchy = _get_term_hierarchy($taxonomies[0]);
573 if ( !isset($hierarchy[$child_of]) )
578 $hierarchy = _get_term_hierarchy($taxonomies[0]);
579 if ( !isset($hierarchy[$parent]) )
583 // $args can be whatever, only use the args defined in defaults to compute the key
584 $key = md5( serialize( compact(array_keys($defaults)) ) . serialize( $taxonomies ) );
586 if ( $cache = wp_cache_get( 'get_terms', 'terms' ) ) {
587 if ( isset( $cache[ $key ] ) )
588 return apply_filters('get_terms', $cache[$key], $taxonomies, $args);
591 if ( 'count' == $orderby )
592 $orderby = 'tt.count';
593 else if ( 'name' == $orderby )
595 else if ( 'slug' == $orderby )
597 else if ( 'term_group' == $orderby )
598 $orderby = 't.term_group';
600 $orderby = 't.term_id';
604 if ( !empty($include) ) {
606 $interms = preg_split('/[\s,]+/',$include);
607 if ( count($interms) ) {
608 foreach ( $interms as $interm ) {
609 if (empty($inclusions))
610 $inclusions = ' AND ( t.term_id = ' . intval($interm) . ' ';
612 $inclusions .= ' OR t.term_id = ' . intval($interm) . ' ';
617 if ( !empty($inclusions) )
619 $where .= $inclusions;
622 if ( !empty($exclude) ) {
623 $exterms = preg_split('/[\s,]+/',$exclude);
624 if ( count($exterms) ) {
625 foreach ( $exterms as $exterm ) {
626 if (empty($exclusions))
627 $exclusions = ' AND ( t.term_id <> ' . intval($exterm) . ' ';
629 $exclusions .= ' AND t.term_id <> ' . intval($exterm) . ' ';
634 if ( !empty($exclusions) )
636 $exclusions = apply_filters('list_terms_exclusions', $exclusions, $args );
637 $where .= $exclusions;
639 if ( !empty($slug) ) {
640 $slug = sanitize_title($slug);
641 $where .= " AND t.slug = '$slug'";
644 if ( !empty($name__like) )
645 $where .= " AND t.name LIKE '{$name__like}%'";
647 if ( '' != $parent ) {
648 $parent = (int) $parent;
649 $where .= " AND tt.parent = '$parent'";
652 if ( $hide_empty && !$hierarchical )
653 $where .= ' AND tt.count > 0';
655 if ( !empty($number) ) {
657 $number = 'LIMIT ' . $offset . ',' . $number;
659 $number = 'LIMIT ' . $number;
664 if ( !empty($search) ) {
665 $search = like_escape($search);
666 $where .= " AND (t.name LIKE '%$search%')";
670 if ( 'all' == $fields )
671 $select_this = 't.*, tt.*';
672 else if ( 'ids' == $fields )
673 $select_this = 't.term_id';
674 else if ( 'names' == $fields )
675 $select_this = 't.name';
677 $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 ORDER BY $orderby $order $number";
679 if ( 'all' == $fields ) {
680 $terms = $wpdb->get_results($query);
681 update_term_cache($terms);
682 } else if ( ('ids' == $fields) || ('names' == $fields) ) {
683 $terms = $wpdb->get_col($query);
686 if ( empty($terms) ) {
687 $cache[ $key ] = array();
688 wp_cache_set( 'get_terms', $cache, 'terms' );
689 return apply_filters('get_terms', array(), $taxonomies, $args);
692 if ( $child_of || $hierarchical ) {
693 $children = _get_term_hierarchy($taxonomies[0]);
694 if ( ! empty($children) )
695 $terms = & _get_term_children($child_of, $terms, $taxonomies[0]);
698 // Update term counts to include children.
700 _pad_term_counts($terms, $taxonomies[0]);
702 // Make sure we show empty categories that have children.
703 if ( $hierarchical && $hide_empty ) {
704 foreach ( $terms as $k => $term ) {
705 if ( ! $term->count ) {
706 $children = _get_term_children($term->term_id, $terms, $taxonomies[0]);
707 foreach ( $children as $child )
711 // It really is empty
718 $cache[ $key ] = $terms;
719 wp_cache_set( 'get_terms', $cache, 'terms' );
721 $terms = apply_filters('get_terms', $terms, $taxonomies, $args);
726 * is_term() - Check if Term exists
728 * Returns the index of a defined term, or 0 (false) if the term doesn't exist.
731 * @subpackage Taxonomy
736 * @param int|string $term The term to check
737 * @param string $taxonomy The taxonomy name to use
738 * @return mixed Get the term id or Term Object, if exists.
740 function is_term($term, $taxonomy = '') {
743 if ( is_int($term) ) {
746 $where = $wpdb->prepare( "t.term_id = %d", $term );
748 if ( '' === $term = sanitize_title($term) )
750 $where = $wpdb->prepare( "t.slug = %s", $term );
753 if ( !empty($taxonomy) )
754 return $wpdb->get_row("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 = '$taxonomy'", ARRAY_A);
756 return $wpdb->get_var("SELECT term_id FROM $wpdb->terms as t WHERE $where");
760 * sanitize_term() - Sanitize Term all fields
762 * Relys on sanitize_term_field() to sanitize the term. The difference
763 * is that this function will sanitize <strong>all</strong> fields. The context
764 * is based on sanitize_term_field().
766 * The $term is expected to be either an array or an object.
769 * @subpackage Taxonomy
772 * @uses sanitize_term_field Used to sanitize all fields in a term
774 * @param array|object $term The term to check
775 * @param string $taxonomy The taxonomy name to use
776 * @param string $context Default is 'display'.
777 * @return array|object Term with all fields sanitized
779 function sanitize_term($term, $taxonomy, $context = 'display') {
781 if ( 'raw' == $context )
784 $fields = array('term_id', 'name', 'description', 'slug', 'count', 'parent', 'term_group');
787 if ( is_object($term) )
790 foreach ( $fields as $field ) {
792 $term->$field = sanitize_term_field($field, $term->$field, $term->term_id, $taxonomy, $context);
794 $term[$field] = sanitize_term_field($field, $term[$field], $term['term_id'], $taxonomy, $context);
801 * sanitize_term_field() - Cleanse the field value in the term based on the context
803 * Passing a term field value through the function should be assumed to have cleansed
804 * the value for whatever context the term field is going to be used.
806 * If no context or an unsupported context is given, then default filters will be applied.
808 * There are enough filters for each context to support a custom filtering without creating
809 * your own filter function. Simply create a function that hooks into the filter you need.
812 * @subpackage Taxonomy
817 * @param string $field Term field to sanitize
818 * @param string $value Search for this term value
819 * @param int $term_id Term ID
820 * @param string $taxonomy Taxonomy Name
821 * @param string $context Either edit, db, display, attribute, or js.
822 * @return mixed sanitized field
824 function sanitize_term_field($field, $value, $term_id, $taxonomy, $context) {
825 if ( 'parent' == $field || 'term_id' == $field || 'count' == $field || 'term_group' == $field ) {
826 $value = (int) $value;
831 if ( 'raw' == $context )
834 if ( 'edit' == $context ) {
835 $value = apply_filters("edit_term_$field", $value, $term_id, $taxonomy);
836 $value = apply_filters("edit_${taxonomy}_$field", $value, $term_id);
837 if ( 'description' == $field )
838 $value = format_to_edit($value);
840 $value = attribute_escape($value);
841 } else if ( 'db' == $context ) {
842 $value = apply_filters("pre_term_$field", $value, $taxonomy);
843 $value = apply_filters("pre_${taxonomy}_$field", $value);
844 // Back compat filters
845 if ( 'slug' == $field )
846 $value = apply_filters('pre_category_nicename', $value);
848 } else if ( 'rss' == $context ) {
849 $value = apply_filters("term_${field}_rss", $value, $taxonomy);
850 $value = apply_filters("${taxonomy}_${field}_rss", $value);
852 // Use display filters by default.
853 $value = apply_filters("term_$field", $value, $term_id, $taxonomy, $context);
854 $value = apply_filters("${taxonomy}_$field", $value, $term_id, $context);
857 if ( 'attribute' == $context )
858 $value = attribute_escape($value);
859 else if ( 'js' == $context )
860 $value = js_escape($value);
866 * wp_count_terms() - Count how many terms are in Taxonomy
868 * Default $args is 'ignore_empty' which can be <code>'ignore_empty=true'</code> or
869 * <code>array('ignore_empty' => true);</code>.
872 * @subpackage Taxonomy
876 * @uses wp_parse_args() Turns strings into arrays and merges defaults into an array.
878 * @param string $taxonomy Taxonomy name
879 * @param array|string $args Overwrite defaults
880 * @return int How many terms are in $taxonomy
882 function wp_count_terms( $taxonomy, $args = array() ) {
885 $defaults = array('ignore_empty' => false);
886 $args = wp_parse_args($args, $defaults);
887 extract($args, EXTR_SKIP);
891 $where = 'AND count > 0';
893 $taxonomy = $wpdb->escape( $taxonomy );
894 return $wpdb->get_var("SELECT COUNT(*) FROM $wpdb->term_taxonomy WHERE taxonomy = '$taxonomy' $where");
898 * wp_delete_object_term_relationships() - Will unlink the term from the taxonomy
900 * Will remove the term's relationship to the taxonomy, not the term or taxonomy itself.
901 * The term and taxonomy will still exist. Will require the term's object ID to perform
905 * @subpackage Taxonomy
909 * @param int $object_id The term Object Id that refers to the term
910 * @param string|array $taxonomy List of Taxonomy Names or single Taxonomy name.
912 function wp_delete_object_term_relationships( $object_id, $taxonomies ) {
915 $object_id = (int) $object_id;
917 if ( !is_array($taxonomies) )
918 $taxonomies = array($taxonomies);
920 foreach ( $taxonomies as $taxonomy ) {
921 $terms = wp_get_object_terms($object_id, $taxonomy, 'fields=tt_ids');
922 $in_terms = "'" . implode("', '", $terms) . "'";
923 $wpdb->query("DELETE FROM $wpdb->term_relationships WHERE object_id = '$object_id' AND term_taxonomy_id IN ($in_terms)");
924 wp_update_term_count($terms, $taxonomy);
929 * wp_delete_term() - Removes a term from the database.
931 * If the term is a parent of other terms, then the children will be updated
932 * to that term's parent.
934 * The $args 'default' will only override the terms found, if there is only one
935 * term found. Any other and the found terms are used.
938 * @subpackage Taxonomy
942 * @uses do_action() Calls both 'delete_term' and 'delete_$taxonomy' action hooks,
943 * passing term object, term id. 'delete_term' gets an additional parameter with
944 * the $taxonomy parameter.
946 * @param int $term Term ID
947 * @param string $taxonomy Taxonomy Name
948 * @param array|string $args Optional. Change 'default' term id and override found term ids.
949 * @return bool|WP_Error Returns false if not term; true if completes delete action.
951 function wp_delete_term( $term, $taxonomy, $args = array() ) {
956 if ( ! $ids = is_term($term, $taxonomy) )
958 if ( is_wp_error( $ids ) )
961 $tt_id = $ids['term_taxonomy_id'];
964 $args = wp_parse_args($args, $defaults);
965 extract($args, EXTR_SKIP);
967 if ( isset($default) ) {
968 $default = (int) $default;
969 if ( ! is_term($default, $taxonomy) )
973 // Update children to point to new parent
974 if ( is_taxonomy_hierarchical($taxonomy) ) {
975 $term_obj = get_term($term, $taxonomy);
976 if ( is_wp_error( $term_obj ) )
978 $parent = $term_obj->parent;
980 $wpdb->update( $wpdb->term_taxonomy, compact( 'parent' ), array( 'parent' => $term_obj->term_id) + compact( 'taxonomy' ) );
983 $objects = $wpdb->get_col( $wpdb->prepare( "SELECT object_id FROM $wpdb->term_relationships WHERE term_taxonomy_id = %d", $tt_id ) );
985 foreach ( (array) $objects as $object ) {
986 $terms = wp_get_object_terms($object, $taxonomy, 'fields=ids');
987 if ( 1 == count($terms) && isset($default) )
988 $terms = array($default);
990 $terms = array_diff($terms, array($term));
991 $terms = array_map('intval', $terms);
992 wp_set_object_terms($object, $terms, $taxonomy);
995 $wpdb->query( $wpdb->prepare( "DELETE FROM $wpdb->term_taxonomy WHERE term_taxonomy_id = %d", $tt_id ) );
997 // Delete the term if no taxonomies use it.
998 if ( !$wpdb->get_var( $wpdb->prepare( "SELECT COUNT(*) FROM $wpdb->term_taxonomy WHERE term_id = %d", $term) ) )
999 $wpdb->query( $wpdb->prepare( "DELETE FROM $wpdb->terms WHERE term_id = %d", $term) );
1001 clean_term_cache($term, $taxonomy);
1003 do_action('delete_term', $term, $tt_id, $taxonomy);
1004 do_action("delete_$taxonomy", $term, $tt_id);
1010 * wp_get_object_terms() - Retrieves the terms associated with the given object(s), in the supplied taxonomies.
1012 * The following information has to do the $args parameter and for what can be contained in the string
1013 * or array of that parameter, if it exists.
1015 * The first argument is called, 'orderby' and has the default value of 'name'. The other value that is
1016 * supported is 'count'.
1018 * The second argument is called, 'order' and has the default value of 'ASC'. The only other value that
1019 * will be acceptable is 'DESC'.
1021 * The final argument supported is called, 'fields' and has the default value of 'all'. There are
1022 * multiple other options that can be used instead. Supported values are as follows: 'all', 'ids',
1023 * 'names', and finally 'all_with_object_id'.
1025 * The fields argument also decides what will be returned. If 'all' or 'all_with_object_id' is choosen or
1026 * the default kept intact, then all matching terms objects will be returned. If either 'ids' or 'names'
1027 * is used, then an array of all matching term ids or term names will be returned respectively.
1029 * @package WordPress
1030 * @subpackage Taxonomy
1034 * @param int|array $object_id The id of the object(s) to retrieve.
1035 * @param string|array $taxonomies The taxonomies to retrieve terms from.
1036 * @param array|string $args Change what is returned
1037 * @return array|WP_Error The requested term data or empty array if no terms found. WP_Error if $taxonomy does not exist.
1039 function wp_get_object_terms($object_ids, $taxonomies, $args = array()) {
1042 if ( !is_array($taxonomies) )
1043 $taxonomies = array($taxonomies);
1045 foreach ( $taxonomies as $taxonomy ) {
1046 if ( ! is_taxonomy($taxonomy) )
1047 return new WP_Error('invalid_taxonomy', __('Invalid Taxonomy'));
1050 if ( !is_array($object_ids) )
1051 $object_ids = array($object_ids);
1052 $object_ids = array_map('intval', $object_ids);
1054 $defaults = array('orderby' => 'name', 'order' => 'ASC', 'fields' => 'all');
1055 $args = wp_parse_args( $args, $defaults );
1058 if ( count($taxonomies) > 1 ) {
1059 foreach ( $taxonomies as $index => $taxonomy ) {
1060 $t = get_taxonomy($taxonomy);
1061 if ( is_array($t->args) && $args != array_merge($args, $t->args) ) {
1062 unset($taxonomies[$index]);
1063 $terms = array_merge($terms, wp_get_object_terms($object_ids, $taxonomy, array_merge($args, $t->args)));
1067 $t = get_taxonomy($taxonomies[0]);
1068 if ( is_array($t->args) )
1069 $args = array_merge($args, $t->args);
1072 extract($args, EXTR_SKIP);
1074 if ( 'count' == $orderby )
1075 $orderby = 'tt.count';
1076 else if ( 'name' == $orderby )
1077 $orderby = 't.name';
1078 else if ( 'slug' == $orderby )
1079 $orderby = 't.slug';
1080 else if ( 'term_group' == $orderby )
1081 $orderby = 't.term_group';
1082 else if ( 'term_order' == $orderby )
1083 $orderby = 'tr.term_order';
1085 $orderby = 't.term_id';
1087 $taxonomies = "'" . implode("', '", $taxonomies) . "'";
1088 $object_ids = implode(', ', $object_ids);
1091 if ( 'all' == $fields )
1092 $select_this = 't.*, tt.*';
1093 else if ( 'ids' == $fields )
1094 $select_this = 't.term_id';
1095 else if ( 'names' == $fields )
1096 $select_this = 't.name';
1097 else if ( 'all_with_object_id' == $fields )
1098 $select_this = 't.*, tt.*, tr.object_id';
1100 $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) ORDER BY $orderby $order";
1102 if ( 'all' == $fields || 'all_with_object_id' == $fields ) {
1103 $terms = array_merge($terms, $wpdb->get_results($query));
1104 update_term_cache($terms);
1105 } else if ( 'ids' == $fields || 'names' == $fields ) {
1106 $terms = array_merge($terms, $wpdb->get_col($query));
1107 } else if ( 'tt_ids' == $fields ) {
1108 $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) ORDER BY tr.term_taxonomy_id $order");
1118 * wp_insert_term() - Adds a new term to the database. Optionally marks it as an alias of an existing term.
1120 * Error handling is assigned for the nonexistance of the $taxonomy and $term parameters before inserting.
1121 * If both the term id and taxonomy exist previously, then an array will be returned that contains the term
1122 * id and the contents of what is returned. The keys of the array are 'term_id' and 'term_taxonomy_id' containing
1125 * It is assumed that the term does not yet exist or the above will apply. The term will be first added to the term
1126 * table and then related to the taxonomy if everything is well. If everything is correct, then several actions
1127 * will be run prior to a filter and then several actions will be run after the filter is run.
1129 * The arguments decide how the term is handled based on the $args parameter. The following
1130 * is a list of the available overrides and the defaults.
1132 * 'alias_of'. There is no default, but if added, expected is the slug that the term will be an alias of.
1133 * Expected to be a string.
1135 * 'description'. There is no default. If exists, will be added to the database along with the term. Expected
1138 * 'parent'. Expected to be numeric and default is 0 (zero). Will assign value of 'parent' to the term.
1140 * 'slug'. Expected to be a string. There is no default.
1142 * If 'slug' argument exists then the slug will be checked to see if it is not a valid term. If that check
1143 * succeeds (it is not a valid term), then it is added and the term id is given. If it fails, then a check
1144 * is made to whether the taxonomy is hierarchical and the parent argument is not empty. If the second check
1145 * succeeds, the term will be inserted and the term id will be given.
1147 * @package WordPress
1148 * @subpackage Taxonomy
1152 * @uses do_action() Calls 'create_term' hook with the term id and taxonomy id as parameters.
1153 * @uses do_action() Calls 'create_$taxonomy' hook with term id and taxonomy id as parameters.
1154 * @uses apply_filters() Calls 'term_id_filter' hook with term id and taxonomy id as parameters.
1155 * @uses do_action() Calls 'created_term' hook with the term id and taxonomy id as parameters.
1156 * @uses do_action() Calls 'created_$taxonomy' hook with term id and taxonomy id as parameters.
1158 * @param int|string $term The term to add or update.
1159 * @param string $taxonomy The taxonomy to which to add the term
1160 * @param array|string $args Change the values of the inserted term
1161 * @return array|WP_Error The Term ID and Term Taxonomy ID
1163 function wp_insert_term( $term, $taxonomy, $args = array() ) {
1166 if ( ! is_taxonomy($taxonomy) )
1167 return new WP_Error('invalid_taxonomy', __('Invalid taxonomy'));
1169 if ( is_int($term) && 0 == $term )
1170 return new WP_Error('invalid_term_id', __('Invalid term ID'));
1172 $defaults = array( 'alias_of' => '', 'description' => '', 'parent' => 0, 'slug' => '');
1173 $args = wp_parse_args($args, $defaults);
1174 $args['name'] = $term;
1175 $args['taxonomy'] = $taxonomy;
1176 $args = sanitize_term($args, $taxonomy, 'db');
1177 extract($args, EXTR_SKIP);
1179 // expected_slashed ($name)
1180 $name = stripslashes($name);
1181 $description = stripslashes($description);
1184 $slug = sanitize_title($name);
1188 $alias = $wpdb->get_row( $wpdb->prepare( "SELECT term_id, term_group FROM $wpdb->terms WHERE slug = %s", $alias_of) );
1189 if ( $alias->term_group ) {
1190 // The alias we want is already in a group, so let's use that one.
1191 $term_group = $alias->term_group;
1193 // The alias isn't in a group, so let's create a new one and firstly add the alias term to it.
1194 $term_group = $wpdb->get_var("SELECT MAX(term_group) FROM $wpdb->terms") + 1;
1195 $wpdb->query( $wpdb->prepare( "UPDATE $wpdb->terms SET term_group = %d WHERE term_id = %d", $term_group, $alias->term_id ) );
1199 if ( ! $term_id = is_term($slug) ) {
1200 if ( false === $wpdb->insert( $wpdb->terms, compact( 'name', 'slug', 'term_group' ) ) )
1201 return new WP_Error('db_insert_error', __('Could not insert term into the database'), $wpdb->last_error);
1202 $term_id = (int) $wpdb->insert_id;
1203 } else if ( is_taxonomy_hierarchical($taxonomy) && !empty($parent) ) {
1204 // If the taxonomy supports hierarchy and the term has a parent, make the slug unique
1205 // by incorporating parent slugs.
1206 $slug = wp_unique_term_slug($slug, (object) $args);
1207 if ( false === $wpdb->insert( $wpdb->terms, compact( 'name', 'slug', 'term_group' ) ) )
1208 return new WP_Error('db_insert_error', __('Could not insert term into the database'), $wpdb->last_error);
1209 $term_id = (int) $wpdb->insert_id;
1212 if ( empty($slug) ) {
1213 $slug = sanitize_title($slug, $term_id);
1214 $wpdb->update( $wpdb->terms, compact( 'slug' ), compact( 'term_id' ) );
1217 $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 ) );
1219 if ( !empty($tt_id) )
1220 return array('term_id' => $term_id, 'term_taxonomy_id' => $tt_id);
1222 $wpdb->insert( $wpdb->term_taxonomy, compact( 'term_id', 'taxonomy', 'description', 'parent') + array( 'count' => 0 ) );
1223 $tt_id = (int) $wpdb->insert_id;
1225 do_action("create_term", $term_id, $tt_id);
1226 do_action("create_$taxonomy", $term_id, $tt_id);
1228 $term_id = apply_filters('term_id_filter', $term_id, $tt_id);
1230 clean_term_cache($term_id, $taxonomy);
1232 do_action("created_term", $term_id, $tt_id);
1233 do_action("created_$taxonomy", $term_id, $tt_id);
1235 return array('term_id' => $term_id, 'term_taxonomy_id' => $tt_id);
1239 * wp_set_object_terms() - Create Term and Taxonomy Relationships
1241 * Relates an object (post, link etc) to a term and taxonomy type. Creates the term and taxonomy
1242 * relationship if it doesn't already exist. Creates a term if it doesn't exist (using the slug).
1244 * A relationship means that the term is grouped in or belongs to the taxonomy. A term has no
1245 * meaning until it is given context by defining which taxonomy it exists under.
1247 * @package WordPress
1248 * @subpackage Taxonomy
1252 * @param int $object_id The object to relate to.
1253 * @param array|int|string $term The slug or id of the term.
1254 * @param array|string $taxonomy The context in which to relate the term to the object.
1255 * @param bool $append If false will delete difference of terms.
1256 * @return array|WP_Error Affected Term IDs
1258 function wp_set_object_terms($object_id, $terms, $taxonomy, $append = false) {
1261 $object_id = (int) $object_id;
1263 if ( ! is_taxonomy($taxonomy) )
1264 return new WP_Error('invalid_taxonomy', __('Invalid Taxonomy'));
1266 if ( !is_array($terms) )
1267 $terms = array($terms);
1270 $old_terms = wp_get_object_terms($object_id, $taxonomy, 'fields=tt_ids');
1273 $term_ids = array();
1275 foreach ($terms as $term) {
1276 if ( !strlen(trim($term)) )
1279 if ( !$id = is_term($term, $taxonomy) )
1280 $id = wp_insert_term($term, $taxonomy);
1281 if ( is_wp_error($id) )
1283 $term_ids[] = $id['term_id'];
1284 $id = $id['term_taxonomy_id'];
1287 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, $id ) ) )
1289 $wpdb->insert( $wpdb->term_relationships, array( 'object_id' => $object_id, 'term_taxonomy_id' => $id ) );
1292 wp_update_term_count($tt_ids, $taxonomy);
1295 $delete_terms = array_diff($old_terms, $tt_ids);
1296 if ( $delete_terms ) {
1297 $in_delete_terms = "'" . implode("', '", $delete_terms) . "'";
1298 $wpdb->query("DELETE FROM $wpdb->term_relationships WHERE object_id = '$object_id' AND term_taxonomy_id IN ($in_delete_terms)");
1299 wp_update_term_count($delete_terms, $taxonomy);
1303 $t = get_taxonomy($taxonomy);
1304 if ( ! $append && isset($t->sort) && $t->sort ) {
1307 $final_term_ids = wp_get_object_terms($object_id, $taxonomy, 'fields=tt_ids');
1308 foreach ( $term_ids as $term_id )
1309 if ( in_array($term_id, $final_term_ids) )
1310 $values[] = $wpdb->prepare( "(%d, %d, %d)", $object_id, $term_id, ++$term_order);
1312 $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)");
1319 * wp_unique_term_slug() - Will make slug unique, if it isn't already
1321 * The $slug has to be unique global to every taxonomy, meaning that one taxonomy
1322 * term can't have a matching slug with another taxonomy term. Each slug has to be
1323 * globally unique for every taxonomy.
1325 * The way this works is that if the taxonomy that the term belongs to is heirarchical
1326 * and has a parent, it will append that parent to the $slug.
1328 * If that still doesn't return an unique slug, then it try to append a number until
1329 * it finds a number that is truely unique.
1331 * The only purpose for $term is for appending a parent, if one exists.
1333 * @package WordPress
1334 * @subpackage Taxonomy
1338 * @param string $slug The string that will be tried for a unique slug
1339 * @param object $term The term object that the $slug will belong too
1340 * @return string Will return a true unique slug.
1342 function wp_unique_term_slug($slug, $term) {
1345 // If the taxonomy supports hierarchy and the term has a parent, make the slug unique
1346 // by incorporating parent slugs.
1347 if ( is_taxonomy_hierarchical($term->taxonomy) && !empty($term->parent) ) {
1348 $the_parent = $term->parent;
1349 while ( ! empty($the_parent) ) {
1350 $parent_term = get_term($the_parent, $term->taxonomy);
1351 if ( is_wp_error($parent_term) || empty($parent_term) )
1353 $slug .= '-' . $parent_term->slug;
1354 if ( empty($parent_term->parent) )
1356 $the_parent = $parent_term->parent;
1360 // If we didn't get a unique slug, try appending a number to make it unique.
1361 if ( !empty($args['term_id']) )
1362 $query = $wpdb->prepare( "SELECT slug FROM $wpdb->terms WHERE slug = %s AND term_id != %d", $slug, $args['term_id'] );
1364 $query = $wpdb->prepare( "SELECT slug FROM $wpdb->terms WHERE slug = %s", $slug );
1366 if ( $wpdb->get_var( $query ) ) {
1369 $alt_slug = $slug . "-$num";
1371 $slug_check = $wpdb->get_var( $wpdb->prepare( "SELECT slug FROM $wpdb->terms WHERE slug = %s", $alt_slug ) );
1372 } while ( $slug_check );
1380 * wp_update_term() - Update term based on arguments provided
1382 * The $args will indiscriminately override all values with the same field name. Care
1383 * must be taken to not override important information need to update or update will
1384 * fail (or perhaps create a new term, neither would be acceptable).
1386 * Defaults will set 'alias_of', 'description', 'parent', and 'slug' if not defined
1389 * 'alias_of' will create a term group, if it doesn't already exist, and update it for
1392 * If the 'slug' argument in $args is missing, then the 'name' in $args will be used.
1393 * It should also be noted that if you set 'slug' and it isn't unique then a WP_Error
1394 * will be passed back. If you don't pass any slug, then a unique one will be created
1397 * For what can be overrode in $args, check the term scheme can contain and stay away
1398 * from the term keys.
1400 * @package WordPress
1401 * @subpackage Taxonomy
1405 * @uses do_action() Will call both 'edit_term' and 'edit_$taxonomy' twice.
1406 * @uses apply_filters() Will call the 'term_id_filter' filter and pass the term id and
1409 * @param int $term The ID of the term
1410 * @param string $taxonomy The context in which to relate the term to the object.
1411 * @param array|string $args Overwrite term field values
1412 * @return array|WP_Error Returns Term ID and Taxonomy Term ID
1414 function wp_update_term( $term, $taxonomy, $args = array() ) {
1417 if ( ! is_taxonomy($taxonomy) )
1418 return new WP_Error('invalid_taxonomy', __('Invalid taxonomy'));
1420 $term_id = (int) $term;
1422 // First, get all of the original args
1423 $term = get_term ($term_id, $taxonomy, ARRAY_A);
1425 // Escape data pulled from DB.
1426 $term = add_magic_quotes($term);
1428 // Merge old and new args with new args overwriting old ones.
1429 $args = array_merge($term, $args);
1431 $defaults = array( 'alias_of' => '', 'description' => '', 'parent' => 0, 'slug' => '');
1432 $args = wp_parse_args($args, $defaults);
1433 $args = sanitize_term($args, $taxonomy, 'db');
1434 extract($args, EXTR_SKIP);
1436 // expected_slashed ($name)
1437 $name = stripslashes($name);
1438 $description = stripslashes($description);
1440 $empty_slug = false;
1441 if ( empty($slug) ) {
1443 $slug = sanitize_title($name);
1447 $alias = $wpdb->get_row( $wpdb->prepare( "SELECT term_id, term_group FROM $wpdb->terms WHERE slug = %s", $alias_of) );
1448 if ( $alias->term_group ) {
1449 // The alias we want is already in a group, so let's use that one.
1450 $term_group = $alias->term_group;
1452 // The alias isn't in a group, so let's create a new one and firstly add the alias term to it.
1453 $term_group = $wpdb->get_var("SELECT MAX(term_group) FROM $wpdb->terms") + 1;
1454 $wpdb->update( $wpdb->terms, compact('term_group'), array( 'term_id' => $alias->term_id ) );
1458 // Check for duplicate slug
1459 $id = $wpdb->get_var( $wpdb->prepare( "SELECT term_id FROM $wpdb->terms WHERE slug = %s", $slug ) );
1460 if ( $id && ($id != $term_id) ) {
1461 // If an empty slug was passed or the parent changed, reset the slug to something unique.
1463 if ( $empty_slug || ( $parent != $term->parent) )
1464 $slug = wp_unique_term_slug($slug, (object) $args);
1466 return new WP_Error('duplicate_term_slug', sprintf(__('The slug "%s" is already in use by another term'), $slug));
1469 $wpdb->update($wpdb->terms, compact( 'name', 'slug', 'term_group' ), compact( 'term_id' ) );
1471 if ( empty($slug) ) {
1472 $slug = sanitize_title($name, $term_id);
1473 $wpdb->update( $wpdb->terms, compact( 'slug' ), compact( 'term_id' ) );
1476 $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) );
1478 $wpdb->update( $wpdb->term_taxonomy, compact( 'term_id', 'taxonomy', 'description', 'parent' ), array( 'term_taxonomy_id' => $tt_id ) );
1480 do_action("edit_term", $term_id, $tt_id);
1481 do_action("edit_$taxonomy", $term_id, $tt_id);
1483 $term_id = apply_filters('term_id_filter', $term_id, $tt_id);
1485 clean_term_cache($term_id, $taxonomy);
1487 do_action("edited_term", $term_id, $tt_id);
1488 do_action("edited_$taxonomy", $term_id, $tt_id);
1490 return array('term_id' => $term_id, 'term_taxonomy_id' => $tt_id);
1493 // enable or disable term count deferring
1494 // if no value is supplied, the current value of the defer setting is returned
1495 function wp_defer_term_counting($defer=NULL) {
1496 static $_defer = false;
1498 if ( is_bool($defer) ) {
1500 // flush any deferred counts
1502 wp_update_term_count( NULL, NULL, true );
1509 * wp_update_term_count() - Updates the amount of terms in taxonomy
1511 * If there is a taxonomy callback applyed, then it will be called for updating the count.
1513 * The default action is to count what the amount of terms have the relationship of term ID.
1514 * Once that is done, then update the database.
1516 * @package WordPress
1517 * @subpackage Taxonomy
1521 * @param int|array $terms The ID of the terms
1522 * @param string $taxonomy The context of the term.
1523 * @return bool If no terms will return false, and if successful will return true.
1525 function wp_update_term_count( $terms, $taxonomy, $do_deferred=false ) {
1526 static $_deferred = array();
1528 if ( $do_deferred ) {
1529 foreach ( array_keys($_deferred) as $tax ) {
1530 wp_update_term_count_now( $_deferred[$tax], $tax );
1531 unset( $_deferred[$tax] );
1535 if ( empty($terms) )
1538 if ( !is_array($terms) )
1539 $terms = array($terms);
1541 if ( wp_defer_term_counting() ) {
1542 if ( !isset($_deferred[$taxonomy]) )
1543 $_deferred[$taxonomy] = array();
1544 $_deferred[$taxonomy] = array_unique( array_merge($_deferred[$taxonomy], $terms) );
1548 return wp_update_term_count_now( $terms, $taxonomy );
1551 function wp_update_term_count_now( $terms, $taxonomy ) {
1554 $terms = array_map('intval', $terms);
1556 $taxonomy = get_taxonomy($taxonomy);
1557 if ( !empty($taxonomy->update_count_callback) ) {
1558 call_user_func($taxonomy->update_count_callback, $terms);
1560 // Default count updater
1561 foreach ($terms as $term) {
1562 $count = $wpdb->get_var( $wpdb->prepare( "SELECT COUNT(*) FROM $wpdb->term_relationships WHERE term_taxonomy_id = %d", $term) );
1563 $wpdb->update( $wpdb->term_taxonomy, compact( 'count' ), array( 'term_taxonomy_id' => $term ) );
1568 clean_term_cache($terms);
1578 * clean_object_term_cache() - Removes the taxonomy relationship to terms from the cache.
1580 * Will remove the entire taxonomy relationship containing term $object_id. The term IDs
1581 * have to exist within the taxonomy $object_type for the deletion to take place.
1583 * @package WordPress
1584 * @subpackage Taxonomy
1587 * @see get_object_taxonomies() for more on $object_type
1588 * @uses do_action() Will call action hook named, 'clean_object_term_cache' after completion.
1589 * Passes, function params in same order.
1591 * @param int|array $object_ids Single or list of term object ID(s)
1592 * @param array|string $object_type The taxonomy object type
1594 function clean_object_term_cache($object_ids, $object_type) {
1595 if ( !is_array($object_ids) )
1596 $object_ids = array($object_ids);
1598 foreach ( $object_ids as $id )
1599 foreach ( get_object_taxonomies($object_type) as $taxonomy )
1600 wp_cache_delete($id, "{$taxonomy}_relationships");
1602 do_action('clean_object_term_cache', $object_ids, $object_type);
1606 * clean_term_cache() - Will remove all of the term ids from the cache
1608 * @package WordPress
1609 * @subpackage Taxonomy
1613 * @param int|array $ids Single or list of Term IDs
1614 * @param string $taxonomy Can be empty and will assume tt_ids, else will use for context.
1616 function clean_term_cache($ids, $taxonomy = '') {
1619 if ( !is_array($ids) )
1622 $taxonomies = array();
1623 // If no taxonomy, assume tt_ids.
1624 if ( empty($taxonomy) ) {
1625 $tt_ids = implode(', ', $ids);
1626 $terms = $wpdb->get_results("SELECT term_id, taxonomy FROM $wpdb->term_taxonomy WHERE term_taxonomy_id IN ($tt_ids)");
1627 foreach ( (array) $terms as $term ) {
1628 $taxonomies[] = $term->taxonomy;
1629 wp_cache_delete($term->term_id, $term->taxonomy);
1631 $taxonomies = array_unique($taxonomies);
1633 foreach ( $ids as $id ) {
1634 wp_cache_delete($id, $taxonomy);
1636 $taxonomies = array($taxonomy);
1639 foreach ( $taxonomies as $taxonomy ) {
1640 wp_cache_delete('all_ids', $taxonomy);
1641 wp_cache_delete('get', $taxonomy);
1642 delete_option("{$taxonomy}_children");
1645 wp_cache_delete('get_terms', 'terms');
1647 do_action('clean_term_cache', $ids, $taxonomy);
1651 * get_object_term_cache() - Retrieves the taxonomy relationship to the term object id.
1653 * @package WordPress
1654 * @subpackage Taxonomy
1657 * @uses wp_cache_get() Retrieves taxonomy relationship from cache
1659 * @param int|array $id Term object ID
1660 * @param string $taxonomy Taxonomy Name
1661 * @return bool|array Empty array if $terms found, but not $taxonomy. False if nothing is in cache for $taxonomy and $id.
1663 function &get_object_term_cache($id, $taxonomy) {
1664 $cache = wp_cache_get($id, "{$taxonomy}_relationships");
1669 * update_object_term_cache() - Updates the cache for Term ID(s)
1671 * Will only update the cache for terms not already cached.
1673 * The $object_ids expects that the ids be separated by commas, if it is
1676 * It should be noted that update_object_term_cache() is very time extensive.
1677 * It is advised that the function is not called very often or at least not
1678 * for a lot of terms that exist in a lot of taxonomies. The amount of time
1679 * increases for each term and it also increases for each taxonomy the term
1682 * @package WordPress
1683 * @subpackage Taxonomy
1685 * @uses wp_get_object_terms() Used to get terms from the database to update
1687 * @param string|array $object_ids Single or list of term object ID(s)
1688 * @param array|string $object_type The taxonomy object type
1689 * @return null|bool Null value is given with empty $object_ids. False if
1691 function update_object_term_cache($object_ids, $object_type) {
1692 if ( empty($object_ids) )
1695 if ( !is_array($object_ids) )
1696 $object_ids = explode(',', $object_ids);
1698 $object_ids = array_map('intval', $object_ids);
1700 $taxonomies = get_object_taxonomies($object_type);
1703 foreach ( (array) $object_ids as $id ) {
1704 foreach ( $taxonomies as $taxonomy ) {
1705 if ( false === wp_cache_get($id, "{$taxonomy}_relationships") ) {
1712 if ( empty( $ids ) )
1715 $terms = wp_get_object_terms($ids, $taxonomies, 'fields=all_with_object_id');
1717 $object_terms = array();
1718 foreach ( (array) $terms as $term )
1719 $object_terms[$term->object_id][$term->taxonomy][$term->term_id] = $term;
1721 foreach ( $ids as $id ) {
1722 foreach ( $taxonomies as $taxonomy ) {
1723 if ( ! isset($object_terms[$id][$taxonomy]) ) {
1724 if ( !isset($object_terms[$id]) )
1725 $object_terms[$id] = array();
1726 $object_terms[$id][$taxonomy] = array();
1731 foreach ( $object_terms as $id => $value ) {
1732 foreach ( $value as $taxonomy => $terms ) {
1733 wp_cache_set($id, $terms, "{$taxonomy}_relationships");
1739 * update_term_cache() - Updates Terms to Taxonomy in cache.
1741 * @package WordPress
1742 * @subpackage Taxonomy
1745 * @param array $terms List of Term objects to change
1746 * @param string $taxonomy Optional. Update Term to this taxonomy in cache
1748 function update_term_cache($terms, $taxonomy = '') {
1749 foreach ( $terms as $term ) {
1750 $term_taxonomy = $taxonomy;
1751 if ( empty($term_taxonomy) )
1752 $term_taxonomy = $term->taxonomy;
1754 wp_cache_add($term->term_id, $term, $term_taxonomy);
1763 * _get_term_hierarchy() - Retrieves children of taxonomy
1765 * @package WordPress
1766 * @subpackage Taxonomy
1770 * @uses update_option() Stores all of the children in "$taxonomy_children" option.
1771 * That is the name of the taxonomy, immediately followed by '_children'.
1773 * @param string $taxonomy Taxonomy Name
1774 * @return array Empty if $taxonomy isn't hierarachical or returns children.
1776 function _get_term_hierarchy($taxonomy) {
1777 if ( !is_taxonomy_hierarchical($taxonomy) )
1779 $children = get_option("{$taxonomy}_children");
1780 if ( is_array($children) )
1783 $children = array();
1784 $terms = get_terms($taxonomy, 'get=all');
1785 foreach ( $terms as $term ) {
1786 if ( $term->parent > 0 )
1787 $children[$term->parent][] = $term->term_id;
1789 update_option("{$taxonomy}_children", $children);
1795 * _get_term_children() - Get array of child terms
1797 * If $terms is an array of objects, then objects will returned from the function.
1798 * If $terms is an array of IDs, then an array of ids of children will be returned.
1800 * @package WordPress
1801 * @subpackage Taxonomy
1805 * @param int $term_id Look for this Term ID in $terms
1806 * @param array $terms List of Term IDs
1807 * @param string $taxonomy Term Context
1808 * @return array Empty if $terms is empty else returns full list of child terms.
1810 function &_get_term_children($term_id, $terms, $taxonomy) {
1811 $empty_array = array();
1812 if ( empty($terms) )
1813 return $empty_array;
1815 $term_list = array();
1816 $has_children = _get_term_hierarchy($taxonomy);
1818 if ( ( 0 != $term_id ) && ! isset($has_children[$term_id]) )
1819 return $empty_array;
1821 foreach ( $terms as $term ) {
1823 if ( !is_object($term) ) {
1824 $term = get_term($term, $taxonomy);
1825 if ( is_wp_error( $term ) )
1830 if ( $term->term_id == $term_id )
1833 if ( $term->parent == $term_id ) {
1835 $term_list[] = $term->term_id;
1837 $term_list[] = $term;
1839 if ( !isset($has_children[$term->term_id]) )
1842 if ( $children = _get_term_children($term->term_id, $terms, $taxonomy) )
1843 $term_list = array_merge($term_list, $children);
1851 * _pad_term_counts() - Add count of children to parent count
1853 * Recalculates term counts by including items from child terms.
1854 * Assumes all relevant children are already in the $terms argument
1856 * @package WordPress
1857 * @subpackage Taxonomy
1862 * @param array $terms List of Term IDs
1863 * @param string $taxonomy Term Context
1864 * @return null Will break from function if conditions are not met.
1866 function _pad_term_counts(&$terms, $taxonomy) {
1869 // This function only works for post categories.
1870 if ( 'category' != $taxonomy )
1873 $term_hier = _get_term_hierarchy($taxonomy);
1875 if ( empty($term_hier) )
1878 $term_items = array();
1880 foreach ( $terms as $key => $term ) {
1881 $terms_by_id[$term->term_id] = & $terms[$key];
1882 $term_ids[$term->term_taxonomy_id] = $term->term_id;
1885 // Get the object and term ids and stick them in a lookup table
1886 $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 (".join(',', array_keys($term_ids)).") AND post_type = 'post' AND post_status = 'publish'");
1887 foreach ( $results as $row ) {
1888 $id = $term_ids[$row->term_taxonomy_id];
1889 ++$term_items[$id][$row->object_id];
1892 // Touch every ancestor's lookup row for each post in each term
1893 foreach ( $term_ids as $term_id ) {
1895 while ( $parent = $terms_by_id[$child]->parent ) {
1896 if ( !empty($term_items[$term_id]) )
1897 foreach ( $term_items[$term_id] as $item_id => $touches )
1898 ++$term_items[$parent][$item_id];
1903 // Transfer the touched cells
1904 foreach ( (array) $term_items as $id => $items )
1905 if ( isset($terms_by_id[$id]) )
1906 $terms_by_id[$id]->count = count($items);
1910 // Default callbacks
1914 * _update_post_term_count() - Will update term count based on posts
1916 * Private function for the default callback for post_tag and category taxonomies.
1918 * @package WordPress
1919 * @subpackage Taxonomy
1924 * @param array $terms List of Term IDs
1926 function _update_post_term_count( $terms ) {
1929 foreach ( $terms as $term ) {
1930 $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 = 'post' AND term_taxonomy_id = %d", $term ) );
1931 $wpdb->update( $wpdb->term_taxonomy, compact( 'count' ), array( 'term_taxonomy_id' => $term ) );
1936 * get_term_link() - Generates a permalink for a taxonomy term archive
1938 * @param object|int|string $term
1939 * @param string $taxonomy
1940 * @return string HTML link to taxonomy term archive
1942 function get_term_link( $term, $taxonomy ) {
1945 // use legacy functions for core taxonomies until they are fully plugged in
1946 if ( $taxonomy == 'category' )
1947 return get_category_link($term);
1948 if ( $taxonomy == 'post_tag' )
1949 return get_tag_link($term);
1951 $termlink = $wp_rewrite->get_extra_permastruct($taxonomy);
1953 if ( !is_object($term) ) {
1954 if ( is_int($term) ) {
1955 $term = &get_term($term, $taxonomy);
1957 $term = &get_term_by('slug', $term, $taxonomy);
1960 if ( is_wp_error( $term ) )
1963 $slug = $term->slug;
1965 if ( empty($termlink) ) {
1966 $file = get_option('home') . '/';
1967 $t = get_taxonomy($taxonomy);
1968 if ( $t->query_var )
1969 $termlink = "$file?$t->query_var=$slug";
1971 $termlink = "$file?taxonomy=$taxonomy&term=$slug";
1973 $termlink = str_replace("%$taxonomy%", $slug, $termlink);
1974 $termlink = get_option('home') . user_trailingslashit($termlink, 'category');
1976 return apply_filters('term_link', $termlink, $term, $taxonomy);
1979 function the_taxonomies($args = array()) {
1987 $r = wp_parse_args( $args, $defaults );
1988 extract( $r, EXTR_SKIP );
1990 echo $before . join($sep, get_the_taxonomies($post)) . $after;
1993 function get_the_taxonomies($post = 0) {
1994 if ( is_int($post) )
1995 $post =& get_post($post);
1996 elseif ( !is_object($post) )
1997 $post =& $GLOBALS['post'];
1999 $taxonomies = array();
2004 $template = apply_filters('taxonomy_template', '%s: %l.');
2006 foreach ( get_object_taxonomies($post) as $taxonomy ) {
2007 $t = (array) get_taxonomy($taxonomy);
2008 if ( empty($t['label']) )
2009 $t['label'] = $taxonomy;
2010 if ( empty($t['args']) )
2011 $t['args'] = array();
2012 if ( empty($t['template']) )
2013 $t['template'] = $template;
2015 $terms = get_object_term_cache($post->ID, $taxonomy);
2016 if ( empty($terms) )
2017 $terms = wp_get_object_terms($post->ID, $taxonomy, $t['args']);
2021 foreach ( $terms as $term )
2022 $links[] = "<a href='" . attribute_escape(get_term_link($term, $taxonomy)) . "'>$term->name</a>";
2025 $taxonomies[$taxonomy] = wp_sprintf($t['template'], $t['label'], $links, $terms);
2030 function get_post_taxonomies($post = 0) {
2031 $post =& get_post($post);
2033 return get_object_taxonomies($post);