11 // Taxonomy Registration
15 * Creates the initial taxonomies when 'init' action is fired.
17 function create_initial_taxonomies() {
20 register_taxonomy( 'category', 'post', array(
21 'hierarchical' => true,
22 'update_count_callback' => '_update_post_term_count',
23 'query_var' => 'category_name',
24 'rewrite' => did_action( 'init' ) ? array(
25 'hierarchical' => true,
26 'slug' => get_option('category_base') ? get_option('category_base') : 'category',
27 'with_front' => ( get_option('category_base') && ! $wp_rewrite->using_index_permalinks() ) ? false : true ) : false,
33 register_taxonomy( 'post_tag', 'post', array(
34 'hierarchical' => false,
35 'update_count_callback' => '_update_post_term_count',
37 'rewrite' => did_action( 'init' ) ? array(
38 'slug' => get_option('tag_base') ? get_option('tag_base') : 'tag',
39 'with_front' => ( get_option('category_base') && ! $wp_rewrite->using_index_permalinks() ) ? false : true ) : false,
45 register_taxonomy( 'nav_menu', 'nav_menu_item', array(
47 'hierarchical' => false,
49 'name' => __( 'Navigation Menus' ),
50 'singular_name' => __( 'Navigation Menu' ),
56 'show_in_nav_menus' => false,
59 register_taxonomy( 'link_category', 'link', array(
60 'hierarchical' => false,
62 'name' => __( 'Link Categories' ),
63 'singular_name' => __( 'Link Category' ),
64 'search_items' => __( 'Search Link Categories' ),
65 'popular_items' => null,
66 'all_items' => __( 'All Link Categories' ),
67 'edit_item' => __( 'Edit Link Category' ),
68 'update_item' => __( 'Update Link Category' ),
69 'add_new_item' => __( 'Add New Link Category' ),
70 'new_item_name' => __( 'New Link Category Name' ),
71 'separate_items_with_commas' => null,
72 'add_or_remove_items' => null,
73 'choose_from_most_used' => null,
83 if ( did_action( 'init' ) ) {
84 $rewrite = apply_filters( 'post_format_rewrite_base', 'type' );
85 $rewrite = $rewrite ? array( 'slug' => $rewrite ) : false;
88 register_taxonomy( 'post_format', 'post', array(
90 'hierarchical' => false,
92 'name' => _x( 'Format', 'post format' ),
93 'singular_name' => _x( 'Format', 'post format' ),
96 'rewrite' => $rewrite,
99 'show_in_nav_menus' => false,
102 add_action( 'init', 'create_initial_taxonomies', 0 ); // highest priority
105 * Get a list of registered taxonomy objects.
108 * @subpackage Taxonomy
110 * @uses $wp_taxonomies
111 * @see register_taxonomy
113 * @param array $args An array of key => value arguments to match against the taxonomy objects.
114 * @param string $output The type of output to return, either taxonomy 'names' or 'objects'. 'names' is the default.
115 * @param string $operator The logical operation to perform. 'or' means only one element
116 * from the array needs to match; 'and' means all elements must match. The default is 'and'.
117 * @return array A list of taxonomy names or objects
119 function get_taxonomies( $args = array(), $output = 'names', $operator = 'and' ) {
120 global $wp_taxonomies;
122 $field = ('names' == $output) ? 'name' : false;
124 return wp_filter_object_list($wp_taxonomies, $args, $operator, $field);
129 * Return all of the taxonomy names that are of $object_type.
131 * It appears that this function can be used to find all of the names inside of
132 * $wp_taxonomies global variable.
134 * <code><?php $taxonomies = get_object_taxonomies('post'); ?></code> Should
135 * result in <code>Array('category', 'post_tag')</code>
138 * @subpackage Taxonomy
141 * @uses $wp_taxonomies
143 * @param array|string|object $object Name of the type of taxonomy object, or an object (row from posts)
144 * @param string $output The type of output to return, either taxonomy 'names' or 'objects'. 'names' is the default.
145 * @return array The names of all taxonomy of $object_type.
147 function get_object_taxonomies($object, $output = 'names') {
148 global $wp_taxonomies;
150 if ( is_object($object) ) {
151 if ( $object->post_type == 'attachment' )
152 return get_attachment_taxonomies($object);
153 $object = $object->post_type;
156 $object = (array) $object;
158 $taxonomies = array();
159 foreach ( (array) $wp_taxonomies as $tax_name => $tax_obj ) {
160 if ( array_intersect($object, (array) $tax_obj->object_type) ) {
161 if ( 'names' == $output )
162 $taxonomies[] = $tax_name;
164 $taxonomies[ $tax_name ] = $tax_obj;
172 * Retrieves the taxonomy object of $taxonomy.
174 * The get_taxonomy function will first check that the parameter string given
175 * is a taxonomy object and if it is, it will return it.
178 * @subpackage Taxonomy
181 * @uses $wp_taxonomies
182 * @uses taxonomy_exists() Checks whether taxonomy exists
184 * @param string $taxonomy Name of taxonomy object to return
185 * @return object|bool The Taxonomy Object or false if $taxonomy doesn't exist
187 function get_taxonomy( $taxonomy ) {
188 global $wp_taxonomies;
190 if ( ! taxonomy_exists( $taxonomy ) )
193 return $wp_taxonomies[$taxonomy];
197 * Checks that the taxonomy name exists.
199 * Formerly is_taxonomy(), introduced in 2.3.0.
202 * @subpackage Taxonomy
205 * @uses $wp_taxonomies
207 * @param string $taxonomy Name of taxonomy object
208 * @return bool Whether the taxonomy exists.
210 function taxonomy_exists( $taxonomy ) {
211 global $wp_taxonomies;
213 return isset( $wp_taxonomies[$taxonomy] );
217 * Whether the taxonomy object is hierarchical.
219 * Checks to make sure that the taxonomy is an object first. Then Gets the
220 * object, and finally returns the hierarchical value in the object.
222 * A false return value might also mean that the taxonomy does not exist.
225 * @subpackage Taxonomy
228 * @uses taxonomy_exists() Checks whether taxonomy exists
229 * @uses get_taxonomy() Used to get the taxonomy object
231 * @param string $taxonomy Name of taxonomy object
232 * @return bool Whether the taxonomy is hierarchical
234 function is_taxonomy_hierarchical($taxonomy) {
235 if ( ! taxonomy_exists($taxonomy) )
238 $taxonomy = get_taxonomy($taxonomy);
239 return $taxonomy->hierarchical;
243 * Create or modify a taxonomy object. Do not use before init.
245 * A simple function for creating or modifying a taxonomy object based on the
246 * parameters given. The function will accept an array (third optional
247 * parameter), along with strings for the taxonomy name and another string for
250 * Nothing is returned, so expect error maybe or use taxonomy_exists() to check
251 * whether taxonomy exists.
253 * Optional $args contents:
255 * label - Name of the taxonomy shown in the menu. Usually plural. If not set, labels['name'] will be used.
257 * hierarchical - has some defined purpose at other parts of the API and is a
260 * update_count_callback - works much like a hook, in that it will be called
261 * when the count is updated.
263 * rewrite - false to prevent rewrite, or array('slug'=>$slug) to customize
264 * permastruct; default will use $taxonomy as slug.
266 * query_var - false to prevent queries, or string to customize query var
267 * (?$query_var=$term); default will use $taxonomy as query var.
269 * public - If the taxonomy should be publically queryable; //@TODO not implemented.
272 * show_ui - If the WordPress UI admin tags UI should apply to this taxonomy;
273 * defaults to public.
275 * show_in_nav_menus - true makes this taxonomy available for selection in navigation menus.
276 * Defaults to public.
278 * show_tagcloud - false to prevent the taxonomy being listed in the Tag Cloud Widget;
279 * defaults to show_ui which defalts to public.
281 * labels - An array of labels for this taxonomy. You can see accepted values in {@link get_taxonomy_labels()}. By default tag labels are used for non-hierarchical types and category labels for hierarchical ones.
284 * @subpackage Taxonomy
286 * @uses $wp_taxonomies Inserts new taxonomy object into the list
287 * @uses $wp_rewrite Adds rewrite tags and permastructs
288 * @uses $wp Adds query vars
290 * @param string $taxonomy Name of taxonomy object
291 * @param array|string $object_type Name of the object type for the taxonomy object.
292 * @param array|string $args See above description for the two keys values.
294 function register_taxonomy( $taxonomy, $object_type, $args = array() ) {
295 global $wp_taxonomies, $wp_rewrite, $wp;
297 if ( ! is_array($wp_taxonomies) )
298 $wp_taxonomies = array();
300 $defaults = array( 'hierarchical' => false,
301 'update_count_callback' => '',
303 'query_var' => $taxonomy,
306 'show_tagcloud' => null,
309 'capabilities' => array(),
310 'show_in_nav_menus' => null,
312 $args = wp_parse_args($args, $defaults);
314 if ( false !== $args['query_var'] && !empty($wp) ) {
315 if ( true === $args['query_var'] )
316 $args['query_var'] = $taxonomy;
317 $args['query_var'] = sanitize_title_with_dashes($args['query_var']);
318 $wp->add_query_var($args['query_var']);
321 if ( false !== $args['rewrite'] && '' != get_option('permalink_structure') ) {
322 $args['rewrite'] = wp_parse_args($args['rewrite'], array(
323 'slug' => sanitize_title_with_dashes($taxonomy),
324 'with_front' => true,
325 'hierarchical' => false
328 if ( $args['hierarchical'] && $args['rewrite']['hierarchical'] )
333 $wp_rewrite->add_rewrite_tag("%$taxonomy%", $tag, $args['query_var'] ? "{$args['query_var']}=" : "taxonomy=$taxonomy&term=");
334 $wp_rewrite->add_permastruct($taxonomy, "{$args['rewrite']['slug']}/%$taxonomy%", $args['rewrite']['with_front']);
337 if ( is_null($args['show_ui']) )
338 $args['show_ui'] = $args['public'];
340 // Whether to show this type in nav-menus.php. Defaults to the setting for public.
341 if ( null === $args['show_in_nav_menus'] )
342 $args['show_in_nav_menus'] = $args['public'];
344 if ( is_null($args['show_tagcloud']) )
345 $args['show_tagcloud'] = $args['show_ui'];
347 $default_caps = array(
348 'manage_terms' => 'manage_categories',
349 'edit_terms' => 'manage_categories',
350 'delete_terms' => 'manage_categories',
351 'assign_terms' => 'edit_posts',
353 $args['cap'] = (object) array_merge( $default_caps, $args['capabilities'] );
354 unset( $args['capabilities'] );
356 $args['name'] = $taxonomy;
357 $args['object_type'] = (array) $object_type;
359 $args['labels'] = get_taxonomy_labels( (object) $args );
360 $args['label'] = $args['labels']->name;
362 $wp_taxonomies[$taxonomy] = (object) $args;
364 // register callback handling for metabox
365 add_filter('wp_ajax_add-' . $taxonomy, '_wp_ajax_add_hierarchical_term');
369 * Builds an object with all taxonomy labels out of a taxonomy object
371 * Accepted keys of the label array in the taxonomy object:
372 * - name - general name for the taxonomy, usually plural. The same as and overriden by $tax->label. Default is Post Tags/Categories
373 * - singular_name - name for one object of this taxonomy. Default is Post Tag/Category
374 * - search_items - Default is Search Tags/Search Categories
375 * - popular_items - This string isn't used on hierarchical taxonomies. Default is Popular Tags
376 * - all_items - Default is All Tags/All Categories
377 * - parent_item - This string isn't used on non-hierarchical taxonomies. In hierarchical ones the default is Parent Category
378 * - parent_item_colon - The same as <code>parent_item</code>, but with colon <code>:</code> in the end
379 * - edit_item - Default is Edit Tag/Edit Category
380 * - update_item - Default is Update Tag/Update Category
381 * - add_new_item - Default is Add New Tag/Add New Category
382 * - new_item_name - Default is New Tag Name/New Category Name
383 * - separate_items_with_commas - This string isn't used on hierarchical taxonomies. Default is "Separate tags with commas," used in the meta box.
384 * - add_or_remove_items - This string isn't used on hierarchical taxonomies. Default is "Add or remove tags," used in the meta box when JavaScript is disabled.
385 * - choose_from_most_used - This string isn't used on hierarchical taxonomies. Default is "Choose from the most used tags," used in the meta box.
387 * Above, the first default value is for non-hierarchical taxonomies (like tags) and the second one is for hierarchical taxonomies (like categories.)
390 * @param object $tax Taxonomy object
391 * @return object object with all the labels as member variables
394 function get_taxonomy_labels( $tax ) {
395 if ( isset( $tax->helps ) && empty( $tax->labels['separate_items_with_commas'] ) )
396 $tax->labels['separate_items_with_commas'] = $tax->helps;
398 $nohier_vs_hier_defaults = array(
399 'name' => array( _x( 'Post Tags', 'taxonomy general name' ), _x( 'Categories', 'taxonomy general name' ) ),
400 'singular_name' => array( _x( 'Post Tag', 'taxonomy singular name' ), _x( 'Category', 'taxonomy singular name' ) ),
401 'search_items' => array( __( 'Search Tags' ), __( 'Search Categories' ) ),
402 'popular_items' => array( __( 'Popular Tags' ), null ),
403 'all_items' => array( __( 'All Tags' ), __( 'All Categories' ) ),
404 'parent_item' => array( null, __( 'Parent Category' ) ),
405 'parent_item_colon' => array( null, __( 'Parent Category:' ) ),
406 'edit_item' => array( __( 'Edit Tag' ), __( 'Edit Category' ) ),
407 'update_item' => array( __( 'Update Tag' ), __( 'Update Category' ) ),
408 'add_new_item' => array( __( 'Add New Tag' ), __( 'Add New Category' ) ),
409 'new_item_name' => array( __( 'New Tag Name' ), __( 'New Category Name' ) ),
410 'separate_items_with_commas' => array( __( 'Separate tags with commas' ), null ),
411 'add_or_remove_items' => array( __( 'Add or remove tags' ), null ),
412 'choose_from_most_used' => array( __( 'Choose from the most used tags' ), null ),
414 $nohier_vs_hier_defaults['menu_name'] = $nohier_vs_hier_defaults['name'];
416 return _get_custom_object_labels( $tax, $nohier_vs_hier_defaults );
420 * Add an already registered taxonomy to an object type.
423 * @subpackage Taxonomy
425 * @uses $wp_taxonomies Modifies taxonomy object
427 * @param string $taxonomy Name of taxonomy object
428 * @param array|string $object_type Name of the object type
429 * @return bool True if successful, false if not
431 function register_taxonomy_for_object_type( $taxonomy, $object_type) {
432 global $wp_taxonomies;
434 if ( !isset($wp_taxonomies[$taxonomy]) )
437 if ( ! get_post_type_object($object_type) )
440 $wp_taxonomies[$taxonomy]->object_type[] = $object_type;
450 * Retrieve object_ids of valid taxonomy and term.
452 * The strings of $taxonomies must exist before this function will continue. On
453 * failure of finding a valid taxonomy, it will return an WP_Error class, kind
454 * of like Exceptions in PHP 5, except you can't catch them. Even so, you can
455 * still test for the WP_Error class and get the error message.
457 * The $terms aren't checked the same as $taxonomies, but still need to exist
458 * for $object_ids to be returned.
460 * It is possible to change the order that object_ids is returned by either
461 * using PHP sort family functions or using the database by using $args with
462 * either ASC or DESC array. The value should be in the key named 'order'.
465 * @subpackage Taxonomy
469 * @uses wp_parse_args() Creates an array from string $args.
471 * @param int|array $term_ids Term id or array of term ids of terms that will be used
472 * @param string|array $taxonomies String of taxonomy name or Array of string values of taxonomy names
473 * @param array|string $args Change the order of the object_ids, either ASC or DESC
474 * @return WP_Error|array If the taxonomy does not exist, then WP_Error will be returned. On success
475 * the array can be empty meaning that there are no $object_ids found or it will return the $object_ids found.
477 function get_objects_in_term( $term_ids, $taxonomies, $args = array() ) {
480 if ( ! is_array( $term_ids ) )
481 $term_ids = array( $term_ids );
483 if ( ! is_array( $taxonomies ) )
484 $taxonomies = array( $taxonomies );
486 foreach ( (array) $taxonomies as $taxonomy ) {
487 if ( ! taxonomy_exists( $taxonomy ) )
488 return new WP_Error( 'invalid_taxonomy', __( 'Invalid Taxonomy' ) );
491 $defaults = array( 'order' => 'ASC' );
492 $args = wp_parse_args( $args, $defaults );
493 extract( $args, EXTR_SKIP );
495 $order = ( 'desc' == strtolower( $order ) ) ? 'DESC' : 'ASC';
497 $term_ids = array_map('intval', $term_ids );
499 $taxonomies = "'" . implode( "', '", $taxonomies ) . "'";
500 $term_ids = "'" . implode( "', '", $term_ids ) . "'";
502 $object_ids = $wpdb->get_col("SELECT tr.object_id FROM $wpdb->term_relationships AS tr INNER JOIN $wpdb->term_taxonomy AS tt ON tr.term_taxonomy_id = tt.term_taxonomy_id WHERE tt.taxonomy IN ($taxonomies) AND tt.term_id IN ($term_ids) ORDER BY tr.object_id $order");
511 * Given a taxonomy query, generates SQL to be appended to a main query.
517 * @param array $tax_query A compact tax query
518 * @param string $primary_table
519 * @param string $primary_id_column
522 function get_tax_sql( $tax_query, $primary_table, $primary_id_column ) {
523 $tax_query_obj = new WP_Tax_Query( $tax_query );
524 return $tax_query_obj->get_sql( $primary_table, $primary_id_column );
528 * Container class for a multiple taxonomy query.
535 * List of taxonomy queries. A single taxonomy query is an associative array:
536 * - 'taxonomy' string The taxonomy being queried
537 * - 'terms' string|array The list of terms
538 * - 'field' string (optional) Which term field is being used.
539 * Possible values: 'term_id', 'slug' or 'name'
541 * - 'operator' string (optional)
542 * Possible values: 'IN' and 'NOT IN'.
544 * - 'include_children' bool (optional) Whether to include child terms.
551 var $queries = array();
554 * The relation between the queries. Can be one of 'AND' or 'OR'.
563 * PHP4 type constructor.
565 * Parses a compact tax query and sets defaults.
570 * @param array $tax_query A compact tax query:
572 * 'relation' => 'OR',
574 * 'taxonomy' => 'tax1',
575 * 'terms' => array( 'term1', 'term2' ),
579 * 'taxonomy' => 'tax2',
580 * 'terms' => array( 'term-a', 'term-b' ),
585 * @return WP_Tax_Query
587 function WP_Tax_Query( $tax_query ) {
588 if ( isset( $tax_query['relation'] ) && strtoupper( $tax_query['relation'] ) == 'OR' ) {
589 $this->relation = 'OR';
591 $this->relation = 'AND';
597 'include_children' => true,
598 'field' => 'term_id',
602 foreach ( $tax_query as $query ) {
603 if ( ! is_array( $query ) )
606 $query = array_merge( $defaults, $query );
608 $query['terms'] = (array) $query['terms'];
610 $this->queries[] = $query;
615 * Generates SQL clauses to be appended to a main query.
620 * @param string $primary_table
621 * @param string $primary_id_column
624 function get_sql( $primary_table, $primary_id_column ) {
631 foreach ( $this->queries as $query ) {
634 if ( ! taxonomy_exists( $taxonomy ) )
635 return array( 'join' => '', 'where' => ' AND 0 = 1');
637 $terms = array_unique( (array) $terms );
639 if ( empty( $terms ) )
642 if ( is_taxonomy_hierarchical( $taxonomy ) && $include_children ) {
643 $this->_transform_terms( $terms, $taxonomy, $field, 'term_id' );
646 foreach ( $terms as $term ) {
647 $children = array_merge( $children, get_term_children( $term, $taxonomy ) );
652 $this->_transform_terms( $terms, $taxonomy, 'term_id', 'term_taxonomy_id' );
655 $this->_transform_terms( $terms, $taxonomy, $field, 'term_taxonomy_id' );
658 if ( 'IN' == $operator ) {
660 if ( empty( $terms ) ) {
661 if ( 'OR' == $this->relation )
664 return array( 'join' => '', 'where' => ' AND 0 = 1' );
667 $terms = implode( ',', $terms );
669 $alias = $i ? 'tt' . $i : $wpdb->term_relationships;
671 $join .= " INNER JOIN $wpdb->term_relationships";
672 $join .= $i ? " AS $alias" : '';
673 $join .= " ON ($primary_table.$primary_id_column = $alias.object_id)";
675 $where[] = "$alias.term_taxonomy_id $operator ($terms)";
676 } elseif ( 'NOT IN' == $operator ) {
678 if ( empty( $terms ) )
681 $terms = implode( ',', $terms );
683 $where[] = "$primary_table.$primary_id_column NOT IN (
685 FROM $wpdb->term_relationships
686 WHERE term_taxonomy_id IN ($terms)
688 } elseif ( 'AND' == $operator ) {
690 if ( empty( $terms ) )
693 $num_terms = count( $terms );
695 $terms = implode( ',', $terms );
697 $where[] = "$primary_table.$primary_id_column IN (
699 FROM $wpdb->term_relationships
700 WHERE term_taxonomy_id IN ($terms)
701 GROUP BY object_id HAVING COUNT(object_id) = $num_terms
708 if ( !empty( $where ) )
709 $where = ' AND ( ' . implode( " $this->relation ", $where ) . ' )';
713 return compact( 'join', 'where' );
717 * Transforms a list of terms, from one field to another.
722 * @param array &$terms The list of terms
723 * @param string $taxonomy The taxonomy of the terms
724 * @param string $field The initial field
725 * @param string $resulting_field The resulting field
727 function _transform_terms( &$terms, $taxonomy, $field, $resulting_field ) {
730 if ( empty( $terms ) )
733 if ( $field == $resulting_field )
736 $resulting_field = esc_sql( $resulting_field );
741 $terms = "'" . implode( "','", array_map( 'sanitize_title_for_query', $terms ) ) . "'";
742 $terms = $wpdb->get_col( "
743 SELECT $wpdb->term_taxonomy.$resulting_field
744 FROM $wpdb->term_taxonomy
745 INNER JOIN $wpdb->terms USING (term_id)
746 WHERE taxonomy = '$taxonomy'
747 AND $wpdb->terms.$field IN ($terms)
752 $terms = implode( ',', array_map( 'intval', $terms ) );
753 $terms = $wpdb->get_col( "
754 SELECT $resulting_field
755 FROM $wpdb->term_taxonomy
756 WHERE taxonomy = '$taxonomy'
757 AND term_id IN ($terms)
764 * Get all Term data from database by Term ID.
766 * The usage of the get_term function is to apply filters to a term object. It
767 * is possible to get a term object from the database before applying the
770 * $term ID must be part of $taxonomy, to get from the database. Failure, might
771 * be able to be captured by the hooks. Failure would be the same value as $wpdb
772 * returns for the get_row method.
774 * There are two hooks, one is specifically for each term, named 'get_term', and
775 * the second is for the taxonomy name, 'term_$taxonomy'. Both hooks gets the
776 * term object, and the taxonomy name as parameters. Both hooks are expected to
777 * return a Term object.
779 * 'get_term' hook - Takes two parameters the term Object and the taxonomy name.
780 * Must return term object. Used in get_term() as a catch-all filter for every
783 * 'get_$taxonomy' hook - Takes two parameters the term Object and the taxonomy
784 * name. Must return term object. $taxonomy will be the taxonomy name, so for
785 * example, if 'category', it would be 'get_category' as the filter name. Useful
786 * for custom taxonomies or plugging into default taxonomies.
789 * @subpackage Taxonomy
793 * @uses sanitize_term() Cleanses the term based on $filter context before returning.
794 * @see sanitize_term_field() The $context param lists the available values for get_term_by() $filter param.
796 * @param int|object $term If integer, will get from database. If object will apply filters and return $term.
797 * @param string $taxonomy Taxonomy name that $term is part of.
798 * @param string $output Constant OBJECT, ARRAY_A, or ARRAY_N
799 * @param string $filter Optional, default is raw or no WordPress defined filter will applied.
800 * @return mixed|null|WP_Error Term Row from database. Will return null if $term is empty. If taxonomy does not
801 * exist then WP_Error will be returned.
803 function &get_term($term, $taxonomy, $output = OBJECT, $filter = 'raw') {
807 if ( empty($term) ) {
808 $error = new WP_Error('invalid_term', __('Empty Term'));
812 if ( ! taxonomy_exists($taxonomy) ) {
813 $error = new WP_Error('invalid_taxonomy', __('Invalid Taxonomy'));
817 if ( is_object($term) && empty($term->filter) ) {
818 wp_cache_add($term->term_id, $term, $taxonomy);
821 if ( is_object($term) )
822 $term = $term->term_id;
824 if ( ! $_term = wp_cache_get($term, $taxonomy) ) {
825 $_term = $wpdb->get_row( $wpdb->prepare( "SELECT t.*, tt.* FROM $wpdb->terms AS t INNER JOIN $wpdb->term_taxonomy AS tt ON t.term_id = tt.term_id WHERE tt.taxonomy = %s AND t.term_id = %s LIMIT 1", $taxonomy, $term) );
828 wp_cache_add($term, $_term, $taxonomy);
832 $_term = apply_filters('get_term', $_term, $taxonomy);
833 $_term = apply_filters("get_$taxonomy", $_term, $taxonomy);
834 $_term = sanitize_term($_term, $taxonomy, $filter);
836 if ( $output == OBJECT ) {
838 } elseif ( $output == ARRAY_A ) {
839 $__term = get_object_vars($_term);
841 } elseif ( $output == ARRAY_N ) {
842 $__term = array_values(get_object_vars($_term));
850 * Get all Term data from database by Term field and data.
852 * Warning: $value is not escaped for 'name' $field. You must do it yourself, if
855 * The default $field is 'id', therefore it is possible to also use null for
856 * field, but not recommended that you do so.
858 * If $value does not exist, the return value will be false. If $taxonomy exists
859 * and $field and $value combinations exist, the Term will be returned.
862 * @subpackage Taxonomy
866 * @uses sanitize_term() Cleanses the term based on $filter context before returning.
867 * @see sanitize_term_field() The $context param lists the available values for get_term_by() $filter param.
869 * @param string $field Either 'slug', 'name', or 'id'
870 * @param string|int $value Search for this term value
871 * @param string $taxonomy Taxonomy Name
872 * @param string $output Constant OBJECT, ARRAY_A, or ARRAY_N
873 * @param string $filter Optional, default is raw or no WordPress defined filter will applied.
874 * @return mixed Term Row from database. Will return false if $taxonomy does not exist or $term was not found.
876 function get_term_by($field, $value, $taxonomy, $output = OBJECT, $filter = 'raw') {
879 if ( ! taxonomy_exists($taxonomy) )
882 if ( 'slug' == $field ) {
884 $value = sanitize_title($value);
887 } else if ( 'name' == $field ) {
888 // Assume already escaped
889 $value = stripslashes($value);
892 $term = get_term( (int) $value, $taxonomy, $output, $filter);
893 if ( is_wp_error( $term ) )
898 $term = $wpdb->get_row( $wpdb->prepare( "SELECT t.*, tt.* FROM $wpdb->terms AS t INNER JOIN $wpdb->term_taxonomy AS tt ON t.term_id = tt.term_id WHERE tt.taxonomy = %s AND $field = %s LIMIT 1", $taxonomy, $value) );
902 wp_cache_add($term->term_id, $term, $taxonomy);
904 $term = apply_filters('get_term', $term, $taxonomy);
905 $term = apply_filters("get_$taxonomy", $term, $taxonomy);
906 $term = sanitize_term($term, $taxonomy, $filter);
908 if ( $output == OBJECT ) {
910 } elseif ( $output == ARRAY_A ) {
911 return get_object_vars($term);
912 } elseif ( $output == ARRAY_N ) {
913 return array_values(get_object_vars($term));
920 * Merge all term children into a single array of their IDs.
922 * This recursive function will merge all of the children of $term into the same
923 * array of term IDs. Only useful for taxonomies which are hierarchical.
925 * Will return an empty array if $term does not exist in $taxonomy.
928 * @subpackage Taxonomy
932 * @uses _get_term_hierarchy()
933 * @uses get_term_children() Used to get the children of both $taxonomy and the parent $term
935 * @param string $term_id ID of Term to get children
936 * @param string $taxonomy Taxonomy Name
937 * @return array|WP_Error List of Term Objects. WP_Error returned if $taxonomy does not exist
939 function get_term_children( $term_id, $taxonomy ) {
940 if ( ! taxonomy_exists($taxonomy) )
941 return new WP_Error('invalid_taxonomy', __('Invalid Taxonomy'));
943 $term_id = intval( $term_id );
945 $terms = _get_term_hierarchy($taxonomy);
947 if ( ! isset($terms[$term_id]) )
950 $children = $terms[$term_id];
952 foreach ( (array) $terms[$term_id] as $child ) {
953 if ( isset($terms[$child]) )
954 $children = array_merge($children, get_term_children($child, $taxonomy));
961 * Get sanitized Term field.
963 * Does checks for $term, based on the $taxonomy. The function is for contextual
964 * reasons and for simplicity of usage. See sanitize_term_field() for more
968 * @subpackage Taxonomy
971 * @uses sanitize_term_field() Passes the return value in sanitize_term_field on success.
973 * @param string $field Term field to fetch
974 * @param int $term Term ID
975 * @param string $taxonomy Taxonomy Name
976 * @param string $context Optional, default is display. Look at sanitize_term_field() for available options.
977 * @return mixed Will return an empty string if $term is not an object or if $field is not set in $term.
979 function get_term_field( $field, $term, $taxonomy, $context = 'display' ) {
981 $term = get_term( $term, $taxonomy );
982 if ( is_wp_error($term) )
985 if ( !is_object($term) )
988 if ( !isset($term->$field) )
991 return sanitize_term_field($field, $term->$field, $term->term_id, $taxonomy, $context);
995 * Sanitizes Term for editing.
997 * Return value is sanitize_term() and usage is for sanitizing the term for
998 * editing. Function is for contextual and simplicity.
1000 * @package WordPress
1001 * @subpackage Taxonomy
1004 * @uses sanitize_term() Passes the return value on success
1006 * @param int|object $id Term ID or Object
1007 * @param string $taxonomy Taxonomy Name
1008 * @return mixed|null|WP_Error Will return empty string if $term is not an object.
1010 function get_term_to_edit( $id, $taxonomy ) {
1011 $term = get_term( $id, $taxonomy );
1013 if ( is_wp_error($term) )
1016 if ( !is_object($term) )
1019 return sanitize_term($term, $taxonomy, 'edit');
1023 * Retrieve the terms in a given taxonomy or list of taxonomies.
1025 * You can fully inject any customizations to the query before it is sent, as
1026 * well as control the output with a filter.
1028 * The 'get_terms' filter will be called when the cache has the term and will
1029 * pass the found term along with the array of $taxonomies and array of $args.
1030 * This filter is also called before the array of terms is passed and will pass
1031 * the array of terms, along with the $taxonomies and $args.
1033 * The 'list_terms_exclusions' filter passes the compiled exclusions along with
1036 * The 'get_terms_orderby' filter passes the ORDER BY clause for the query
1037 * along with the $args array.
1039 * The 'get_terms_fields' filter passes the fields for the SELECT query
1040 * along with the $args array.
1042 * The list of arguments that $args can contain, which will overwrite the defaults:
1044 * orderby - Default is 'name'. Can be name, count, term_group, slug or nothing
1045 * (will use term_id), Passing a custom value other than these will cause it to
1046 * order based on the custom value.
1048 * order - Default is ASC. Can use DESC.
1050 * hide_empty - Default is true. Will not return empty terms, which means
1051 * terms whose count is 0 according to the given taxonomy.
1053 * exclude - Default is an empty array. An array, comma- or space-delimited string
1054 * of term ids to exclude from the return array. If 'include' is non-empty,
1055 * 'exclude' is ignored.
1057 * exclude_tree - Default is an empty array. An array, comma- or space-delimited
1058 * string of term ids to exclude from the return array, along with all of their
1059 * descendant terms according to the primary taxonomy. If 'include' is non-empty,
1060 * 'exclude_tree' is ignored.
1062 * include - Default is an empty array. An array, comma- or space-delimited string
1063 * of term ids to include in the return array.
1065 * number - The maximum number of terms to return. Default is to return them all.
1067 * offset - The number by which to offset the terms query.
1069 * fields - Default is 'all', which returns an array of term objects.
1070 * If 'fields' is 'ids' or 'names', returns an array of
1071 * integers or strings, respectively.
1073 * slug - Returns terms whose "slug" matches this value. Default is empty string.
1075 * hierarchical - Whether to include terms that have non-empty descendants
1076 * (even if 'hide_empty' is set to true).
1078 * search - Returned terms' names will contain the value of 'search',
1079 * case-insensitive. Default is an empty string.
1081 * name__like - Returned terms' names will begin with the value of 'name__like',
1082 * case-insensitive. Default is empty string.
1084 * The argument 'pad_counts', if set to true will include the quantity of a term's
1085 * children in the quantity of each term's "count" object variable.
1087 * The 'get' argument, if set to 'all' instead of its default empty string,
1088 * returns terms regardless of ancestry or whether the terms are empty.
1090 * The 'child_of' argument, when used, should be set to the integer of a term ID. Its default
1091 * is 0. If set to a non-zero value, all returned terms will be descendants
1092 * of that term according to the given taxonomy. Hence 'child_of' is set to 0
1093 * if more than one taxonomy is passed in $taxonomies, because multiple taxonomies
1094 * make term ancestry ambiguous.
1096 * The 'parent' argument, when used, should be set to the integer of a term ID. Its default is
1097 * the empty string '', which has a different meaning from the integer 0.
1098 * If set to an integer value, all returned terms will have as an immediate
1099 * ancestor the term whose ID is specified by that integer according to the given taxonomy.
1100 * The 'parent' argument is different from 'child_of' in that a term X is considered a 'parent'
1101 * of term Y only if term X is the father of term Y, not its grandfather or great-grandfather, etc.
1103 * @package WordPress
1104 * @subpackage Taxonomy
1108 * @uses wp_parse_args() Merges the defaults with those defined by $args and allows for strings.
1110 * @param string|array $taxonomies Taxonomy name or list of Taxonomy names
1111 * @param string|array $args The values of what to search for when returning terms
1112 * @return array|WP_Error List of Term Objects and their children. Will return WP_Error, if any of $taxonomies do not exist.
1114 function &get_terms($taxonomies, $args = '') {
1116 $empty_array = array();
1118 $single_taxonomy = false;
1119 if ( !is_array($taxonomies) ) {
1120 $single_taxonomy = true;
1121 $taxonomies = array($taxonomies);
1124 foreach ( $taxonomies as $taxonomy ) {
1125 if ( ! taxonomy_exists($taxonomy) ) {
1126 $error = & new WP_Error('invalid_taxonomy', __('Invalid Taxonomy'));
1131 $defaults = array('orderby' => 'name', 'order' => 'ASC',
1132 'hide_empty' => true, 'exclude' => array(), 'exclude_tree' => array(), 'include' => array(),
1133 'number' => '', 'fields' => 'all', 'slug' => '', 'parent' => '',
1134 'hierarchical' => true, 'child_of' => 0, 'get' => '', 'name__like' => '',
1135 'pad_counts' => false, 'offset' => '', 'search' => '');
1136 $args = wp_parse_args( $args, $defaults );
1137 $args['number'] = absint( $args['number'] );
1138 $args['offset'] = absint( $args['offset'] );
1139 if ( !$single_taxonomy || !is_taxonomy_hierarchical($taxonomies[0]) ||
1140 '' !== $args['parent'] ) {
1141 $args['child_of'] = 0;
1142 $args['hierarchical'] = false;
1143 $args['pad_counts'] = false;
1146 if ( 'all' == $args['get'] ) {
1147 $args['child_of'] = 0;
1148 $args['hide_empty'] = 0;
1149 $args['hierarchical'] = false;
1150 $args['pad_counts'] = false;
1153 $args = apply_filters( 'get_terms_args', $args, $taxonomies );
1155 extract($args, EXTR_SKIP);
1158 $hierarchy = _get_term_hierarchy($taxonomies[0]);
1159 if ( !isset($hierarchy[$child_of]) )
1160 return $empty_array;
1164 $hierarchy = _get_term_hierarchy($taxonomies[0]);
1165 if ( !isset($hierarchy[$parent]) )
1166 return $empty_array;
1169 // $args can be whatever, only use the args defined in defaults to compute the key
1170 $filter_key = ( has_filter('list_terms_exclusions') ) ? serialize($GLOBALS['wp_filter']['list_terms_exclusions']) : '';
1171 $key = md5( serialize( compact(array_keys($defaults)) ) . serialize( $taxonomies ) . $filter_key );
1172 $last_changed = wp_cache_get('last_changed', 'terms');
1173 if ( !$last_changed ) {
1174 $last_changed = time();
1175 wp_cache_set('last_changed', $last_changed, 'terms');
1177 $cache_key = "get_terms:$key:$last_changed";
1178 $cache = wp_cache_get( $cache_key, 'terms' );
1179 if ( false !== $cache ) {
1180 $cache = apply_filters('get_terms', $cache, $taxonomies, $args);
1184 $_orderby = strtolower($orderby);
1185 if ( 'count' == $_orderby )
1186 $orderby = 'tt.count';
1187 else if ( 'name' == $_orderby )
1188 $orderby = 't.name';
1189 else if ( 'slug' == $_orderby )
1190 $orderby = 't.slug';
1191 else if ( 'term_group' == $_orderby )
1192 $orderby = 't.term_group';
1193 else if ( 'none' == $_orderby )
1195 elseif ( empty($_orderby) || 'id' == $_orderby )
1196 $orderby = 't.term_id';
1198 $orderby = 't.name';
1200 $orderby = apply_filters( 'get_terms_orderby', $orderby, $args );
1202 if ( !empty($orderby) )
1203 $orderby = "ORDER BY $orderby";
1207 $order = strtoupper( $order );
1208 if ( '' !== $order && !in_array( $order, array( 'ASC', 'DESC' ) ) )
1211 $where = "tt.taxonomy IN ('" . implode("', '", $taxonomies) . "')";
1213 if ( !empty($include) ) {
1216 $interms = wp_parse_id_list($include);
1217 foreach ( $interms as $interm ) {
1218 if ( empty($inclusions) )
1219 $inclusions = ' AND ( t.term_id = ' . intval($interm) . ' ';
1221 $inclusions .= ' OR t.term_id = ' . intval($interm) . ' ';
1225 if ( !empty($inclusions) )
1227 $where .= $inclusions;
1230 if ( !empty( $exclude_tree ) ) {
1231 $excluded_trunks = wp_parse_id_list($exclude_tree);
1232 foreach ( $excluded_trunks as $extrunk ) {
1233 $excluded_children = (array) get_terms($taxonomies[0], array('child_of' => intval($extrunk), 'fields' => 'ids', 'hide_empty' => 0));
1234 $excluded_children[] = $extrunk;
1235 foreach( $excluded_children as $exterm ) {
1236 if ( empty($exclusions) )
1237 $exclusions = ' AND ( t.term_id <> ' . intval($exterm) . ' ';
1239 $exclusions .= ' AND t.term_id <> ' . intval($exterm) . ' ';
1244 if ( !empty($exclude) ) {
1245 $exterms = wp_parse_id_list($exclude);
1246 foreach ( $exterms as $exterm ) {
1247 if ( empty($exclusions) )
1248 $exclusions = ' AND ( t.term_id <> ' . intval($exterm) . ' ';
1250 $exclusions .= ' AND t.term_id <> ' . intval($exterm) . ' ';
1254 if ( !empty($exclusions) )
1256 $exclusions = apply_filters('list_terms_exclusions', $exclusions, $args );
1257 $where .= $exclusions;
1259 if ( !empty($slug) ) {
1260 $slug = sanitize_title($slug);
1261 $where .= " AND t.slug = '$slug'";
1264 if ( !empty($name__like) ) {
1265 $name__like = like_escape( $name__like );
1266 $where .= $wpdb->prepare( " AND t.name LIKE %s", $name__like . '%' );
1269 if ( '' !== $parent ) {
1270 $parent = (int) $parent;
1271 $where .= " AND tt.parent = '$parent'";
1274 if ( $hide_empty && !$hierarchical )
1275 $where .= ' AND tt.count > 0';
1277 // don't limit the query results when we have to descend the family tree
1278 if ( ! empty($number) && ! $hierarchical && empty( $child_of ) && '' === $parent ) {
1280 $limits = 'LIMIT ' . $offset . ',' . $number;
1282 $limits = 'LIMIT ' . $number;
1287 if ( !empty($search) ) {
1288 $search = like_escape($search);
1289 $where .= $wpdb->prepare( " AND (t.name LIKE %s)", '%' . $search . '%');
1293 switch ( $fields ) {
1295 $selects = array('t.*', 'tt.*');
1299 $selects = array('t.term_id', 'tt.parent', 'tt.count');
1302 $selects = array('t.term_id', 'tt.parent', 'tt.count', 't.name');
1307 $selects = array('COUNT(*)');
1312 $fields = implode(', ', apply_filters( 'get_terms_fields', $selects, $args ));
1314 $join = "INNER JOIN $wpdb->term_taxonomy AS tt ON t.term_id = tt.term_id";
1316 $pieces = array( 'fields', 'join', 'where', 'orderby', 'order', 'limits' );
1317 $clauses = apply_filters( 'terms_clauses', compact( $pieces ), $taxonomies, $args );
1318 foreach ( $pieces as $piece )
1319 $$piece = isset( $clauses[ $piece ] ) ? $clauses[ $piece ] : '';
1321 $query = "SELECT $fields FROM $wpdb->terms AS t $join WHERE $where $orderby $order $limits";
1325 if ( 'count' == $fields ) {
1326 $term_count = $wpdb->get_var($query);
1330 $terms = $wpdb->get_results($query);
1331 if ( 'all' == $fields ) {
1332 update_term_cache($terms);
1335 if ( empty($terms) ) {
1336 wp_cache_add( $cache_key, array(), 'terms', 86400 ); // one day
1337 $terms = apply_filters('get_terms', array(), $taxonomies, $args);
1342 $children = _get_term_hierarchy($taxonomies[0]);
1343 if ( ! empty($children) )
1344 $terms = & _get_term_children($child_of, $terms, $taxonomies[0]);
1347 // Update term counts to include children.
1348 if ( $pad_counts && 'all' == $fields )
1349 _pad_term_counts($terms, $taxonomies[0]);
1351 // Make sure we show empty categories that have children.
1352 if ( $hierarchical && $hide_empty && is_array($terms) ) {
1353 foreach ( $terms as $k => $term ) {
1354 if ( ! $term->count ) {
1355 $children = _get_term_children($term->term_id, $terms, $taxonomies[0]);
1356 if ( is_array($children) )
1357 foreach ( $children as $child )
1358 if ( $child->count )
1361 // It really is empty
1369 if ( 'id=>parent' == $fields ) {
1370 while ( $term = array_shift($terms) )
1371 $_terms[$term->term_id] = $term->parent;
1373 } elseif ( 'ids' == $fields ) {
1374 while ( $term = array_shift($terms) )
1375 $_terms[] = $term->term_id;
1377 } elseif ( 'names' == $fields ) {
1378 while ( $term = array_shift($terms) )
1379 $_terms[] = $term->name;
1383 if ( 0 < $number && intval(@count($terms)) > $number ) {
1384 $terms = array_slice($terms, $offset, $number);
1387 wp_cache_add( $cache_key, $terms, 'terms', 86400 ); // one day
1389 $terms = apply_filters('get_terms', $terms, $taxonomies, $args);
1394 * Check if Term exists.
1396 * Returns the index of a defined term, or 0 (false) if the term doesn't exist.
1398 * Formerly is_term(), introduced in 2.3.0.
1400 * @package WordPress
1401 * @subpackage Taxonomy
1406 * @param int|string $term The term to check
1407 * @param string $taxonomy The taxonomy name to use
1408 * @param int $parent ID of parent term under which to confine the exists search.
1409 * @return mixed Get the term id or Term Object, if exists.
1411 function term_exists($term, $taxonomy = '', $parent = 0) {
1414 $select = "SELECT term_id FROM $wpdb->terms as t WHERE ";
1415 $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 ";
1417 if ( is_int($term) ) {
1420 $where = 't.term_id = %d';
1421 if ( !empty($taxonomy) )
1422 return $wpdb->get_row( $wpdb->prepare( $tax_select . $where . " AND tt.taxonomy = %s", $term, $taxonomy ), ARRAY_A );
1424 return $wpdb->get_var( $wpdb->prepare( $select . $where, $term ) );
1427 $term = trim( stripslashes( $term ) );
1429 if ( '' === $slug = sanitize_title($term) )
1432 $where = 't.slug = %s';
1433 $else_where = 't.name = %s';
1434 $where_fields = array($slug);
1435 $else_where_fields = array($term);
1436 if ( !empty($taxonomy) ) {
1437 $parent = (int) $parent;
1438 if ( $parent > 0 ) {
1439 $where_fields[] = $parent;
1440 $else_where_fields[] = $parent;
1441 $where .= ' AND tt.parent = %d';
1442 $else_where .= ' AND tt.parent = %d';
1445 $where_fields[] = $taxonomy;
1446 $else_where_fields[] = $taxonomy;
1448 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) )
1451 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);
1454 if ( $result = $wpdb->get_var( $wpdb->prepare("SELECT term_id FROM $wpdb->terms as t WHERE $where", $where_fields) ) )
1457 return $wpdb->get_var( $wpdb->prepare("SELECT term_id FROM $wpdb->terms as t WHERE $else_where", $else_where_fields) );
1461 * Sanitize Term all fields.
1463 * Relys on sanitize_term_field() to sanitize the term. The difference is that
1464 * this function will sanitize <strong>all</strong> fields. The context is based
1465 * on sanitize_term_field().
1467 * The $term is expected to be either an array or an object.
1469 * @package WordPress
1470 * @subpackage Taxonomy
1473 * @uses sanitize_term_field Used to sanitize all fields in a term
1475 * @param array|object $term The term to check
1476 * @param string $taxonomy The taxonomy name to use
1477 * @param string $context Default is 'display'.
1478 * @return array|object Term with all fields sanitized
1480 function sanitize_term($term, $taxonomy, $context = 'display') {
1482 if ( 'raw' == $context )
1485 $fields = array('term_id', 'name', 'description', 'slug', 'count', 'parent', 'term_group');
1488 if ( is_object($term) )
1491 $term_id = $do_object ? $term->term_id : (isset($term['term_id']) ? $term['term_id'] : 0);
1493 foreach ( (array) $fields as $field ) {
1495 if ( isset($term->$field) )
1496 $term->$field = sanitize_term_field($field, $term->$field, $term_id, $taxonomy, $context);
1498 if ( isset($term[$field]) )
1499 $term[$field] = sanitize_term_field($field, $term[$field], $term_id, $taxonomy, $context);
1504 $term->filter = $context;
1506 $term['filter'] = $context;
1512 * Cleanse the field value in the term based on the context.
1514 * Passing a term field value through the function should be assumed to have
1515 * cleansed the value for whatever context the term field is going to be used.
1517 * If no context or an unsupported context is given, then default filters will
1520 * There are enough filters for each context to support a custom filtering
1521 * without creating your own filter function. Simply create a function that
1522 * hooks into the filter you need.
1524 * @package WordPress
1525 * @subpackage Taxonomy
1530 * @param string $field Term field to sanitize
1531 * @param string $value Search for this term value
1532 * @param int $term_id Term ID
1533 * @param string $taxonomy Taxonomy Name
1534 * @param string $context Either edit, db, display, attribute, or js.
1535 * @return mixed sanitized field
1537 function sanitize_term_field($field, $value, $term_id, $taxonomy, $context) {
1538 if ( 'parent' == $field || 'term_id' == $field || 'count' == $field || 'term_group' == $field ) {
1539 $value = (int) $value;
1544 if ( 'raw' == $context )
1547 if ( 'edit' == $context ) {
1548 $value = apply_filters("edit_term_{$field}", $value, $term_id, $taxonomy);
1549 $value = apply_filters("edit_{$taxonomy}_{$field}", $value, $term_id);
1550 if ( 'description' == $field )
1551 $value = esc_html($value); // textarea_escaped
1553 $value = esc_attr($value);
1554 } else if ( 'db' == $context ) {
1555 $value = apply_filters("pre_term_{$field}", $value, $taxonomy);
1556 $value = apply_filters("pre_{$taxonomy}_{$field}", $value);
1557 // Back compat filters
1558 if ( 'slug' == $field )
1559 $value = apply_filters('pre_category_nicename', $value);
1561 } else if ( 'rss' == $context ) {
1562 $value = apply_filters("term_{$field}_rss", $value, $taxonomy);
1563 $value = apply_filters("{$taxonomy}_{$field}_rss", $value);
1565 // Use display filters by default.
1566 $value = apply_filters("term_{$field}", $value, $term_id, $taxonomy, $context);
1567 $value = apply_filters("{$taxonomy}_{$field}", $value, $term_id, $context);
1570 if ( 'attribute' == $context )
1571 $value = esc_attr($value);
1572 else if ( 'js' == $context )
1573 $value = esc_js($value);
1579 * Count how many terms are in Taxonomy.
1581 * Default $args is 'hide_empty' which can be 'hide_empty=true' or array('hide_empty' => true).
1583 * @package WordPress
1584 * @subpackage Taxonomy
1588 * @uses wp_parse_args() Turns strings into arrays and merges defaults into an array.
1590 * @param string $taxonomy Taxonomy name
1591 * @param array|string $args Overwrite defaults. See get_terms()
1592 * @return int How many terms are in $taxonomy
1594 function wp_count_terms( $taxonomy, $args = array() ) {
1595 $defaults = array('hide_empty' => false);
1596 $args = wp_parse_args($args, $defaults);
1598 // backwards compatibility
1599 if ( isset($args['ignore_empty']) ) {
1600 $args['hide_empty'] = $args['ignore_empty'];
1601 unset($args['ignore_empty']);
1604 $args['fields'] = 'count';
1606 return get_terms($taxonomy, $args);
1610 * Will unlink the object from the taxonomy or taxonomies.
1612 * Will remove all relationships between the object and any terms in
1613 * a particular taxonomy or taxonomies. Does not remove the term or
1616 * @package WordPress
1617 * @subpackage Taxonomy
1621 * @param int $object_id The term Object Id that refers to the term
1622 * @param string|array $taxonomies List of Taxonomy Names or single Taxonomy name.
1624 function wp_delete_object_term_relationships( $object_id, $taxonomies ) {
1627 $object_id = (int) $object_id;
1629 if ( !is_array($taxonomies) )
1630 $taxonomies = array($taxonomies);
1632 foreach ( (array) $taxonomies as $taxonomy ) {
1633 $tt_ids = wp_get_object_terms($object_id, $taxonomy, array('fields' => 'tt_ids'));
1634 $in_tt_ids = "'" . implode("', '", $tt_ids) . "'";
1635 do_action( 'delete_term_relationships', $object_id, $tt_ids );
1636 $wpdb->query( $wpdb->prepare("DELETE FROM $wpdb->term_relationships WHERE object_id = %d AND term_taxonomy_id IN ($in_tt_ids)", $object_id) );
1637 do_action( 'deleted_term_relationships', $object_id, $tt_ids );
1638 wp_update_term_count($tt_ids, $taxonomy);
1643 * Removes a term from the database.
1645 * If the term is a parent of other terms, then the children will be updated to
1646 * that term's parent.
1648 * The $args 'default' will only override the terms found, if there is only one
1649 * term found. Any other and the found terms are used.
1651 * The $args 'force_default' will force the term supplied as default to be
1652 * assigned even if the object was not going to be termless
1653 * @package WordPress
1654 * @subpackage Taxonomy
1658 * @uses do_action() Calls both 'delete_term' and 'delete_$taxonomy' action
1659 * hooks, passing term object, term id. 'delete_term' gets an additional
1660 * parameter with the $taxonomy parameter.
1662 * @param int $term Term ID
1663 * @param string $taxonomy Taxonomy Name
1664 * @param array|string $args Optional. Change 'default' term id and override found term ids.
1665 * @return bool|WP_Error Returns false if not term; true if completes delete action.
1667 function wp_delete_term( $term, $taxonomy, $args = array() ) {
1670 $term = (int) $term;
1672 if ( ! $ids = term_exists($term, $taxonomy) )
1674 if ( is_wp_error( $ids ) )
1677 $tt_id = $ids['term_taxonomy_id'];
1679 $defaults = array();
1681 if ( 'category' == $taxonomy ) {
1682 $defaults['default'] = get_option( 'default_category' );
1683 if ( $defaults['default'] == $term )
1684 return 0; // Don't delete the default category
1687 $args = wp_parse_args($args, $defaults);
1688 extract($args, EXTR_SKIP);
1690 if ( isset( $default ) ) {
1691 $default = (int) $default;
1692 if ( ! term_exists($default, $taxonomy) )
1696 // Update children to point to new parent
1697 if ( is_taxonomy_hierarchical($taxonomy) ) {
1698 $term_obj = get_term($term, $taxonomy);
1699 if ( is_wp_error( $term_obj ) )
1701 $parent = $term_obj->parent;
1703 $edit_tt_ids = $wpdb->get_col( "SELECT `term_taxonomy_id` FROM $wpdb->term_taxonomy WHERE `parent` = " . (int)$term_obj->term_id );
1704 do_action( 'edit_term_taxonomies', $edit_tt_ids );
1705 $wpdb->update( $wpdb->term_taxonomy, compact( 'parent' ), array( 'parent' => $term_obj->term_id) + compact( 'taxonomy' ) );
1706 do_action( 'edited_term_taxonomies', $edit_tt_ids );
1709 $objects = $wpdb->get_col( $wpdb->prepare( "SELECT object_id FROM $wpdb->term_relationships WHERE term_taxonomy_id = %d", $tt_id ) );
1711 foreach ( (array) $objects as $object ) {
1712 $terms = wp_get_object_terms($object, $taxonomy, array('fields' => 'ids', 'orderby' => 'none'));
1713 if ( 1 == count($terms) && isset($default) ) {
1714 $terms = array($default);
1716 $terms = array_diff($terms, array($term));
1717 if (isset($default) && isset($force_default) && $force_default)
1718 $terms = array_merge($terms, array($default));
1720 $terms = array_map('intval', $terms);
1721 wp_set_object_terms($object, $terms, $taxonomy);
1724 // Clean the relationship caches for all object types using this term
1725 $tax_object = get_taxonomy( $taxonomy );
1726 foreach ( $tax_object->object_type as $object_type )
1727 clean_object_term_cache( $objects, $object_type );
1729 do_action( 'delete_term_taxonomy', $tt_id );
1730 $wpdb->query( $wpdb->prepare( "DELETE FROM $wpdb->term_taxonomy WHERE term_taxonomy_id = %d", $tt_id ) );
1731 do_action( 'deleted_term_taxonomy', $tt_id );
1733 // Delete the term if no taxonomies use it.
1734 if ( !$wpdb->get_var( $wpdb->prepare( "SELECT COUNT(*) FROM $wpdb->term_taxonomy WHERE term_id = %d", $term) ) )
1735 $wpdb->query( $wpdb->prepare( "DELETE FROM $wpdb->terms WHERE term_id = %d", $term) );
1737 clean_term_cache($term, $taxonomy);
1739 do_action('delete_term', $term, $tt_id, $taxonomy);
1740 do_action("delete_$taxonomy", $term, $tt_id);
1746 * Deletes one existing category.
1749 * @uses wp_delete_term()
1751 * @param int $cat_ID
1752 * @return mixed Returns true if completes delete action; false if term doesnt exist;
1753 * Zero on attempted deletion of default Category; WP_Error object is also a possibility.
1755 function wp_delete_category( $cat_ID ) {
1756 return wp_delete_term( $cat_ID, 'category' );
1760 * Retrieves the terms associated with the given object(s), in the supplied taxonomies.
1762 * The following information has to do the $args parameter and for what can be
1763 * contained in the string or array of that parameter, if it exists.
1765 * The first argument is called, 'orderby' and has the default value of 'name'.
1766 * The other value that is supported is 'count'.
1768 * The second argument is called, 'order' and has the default value of 'ASC'.
1769 * The only other value that will be acceptable is 'DESC'.
1771 * The final argument supported is called, 'fields' and has the default value of
1772 * 'all'. There are multiple other options that can be used instead. Supported
1773 * values are as follows: 'all', 'ids', 'names', and finally
1774 * 'all_with_object_id'.
1776 * The fields argument also decides what will be returned. If 'all' or
1777 * 'all_with_object_id' is choosen or the default kept intact, then all matching
1778 * terms objects will be returned. If either 'ids' or 'names' is used, then an
1779 * array of all matching term ids or term names will be returned respectively.
1781 * @package WordPress
1782 * @subpackage Taxonomy
1786 * @param int|array $object_ids The ID(s) of the object(s) to retrieve.
1787 * @param string|array $taxonomies The taxonomies to retrieve terms from.
1788 * @param array|string $args Change what is returned
1789 * @return array|WP_Error The requested term data or empty array if no terms found. WP_Error if $taxonomy does not exist.
1791 function wp_get_object_terms($object_ids, $taxonomies, $args = array()) {
1794 if ( !is_array($taxonomies) )
1795 $taxonomies = array($taxonomies);
1797 foreach ( (array) $taxonomies as $taxonomy ) {
1798 if ( ! taxonomy_exists($taxonomy) )
1799 return new WP_Error('invalid_taxonomy', __('Invalid Taxonomy'));
1802 if ( !is_array($object_ids) )
1803 $object_ids = array($object_ids);
1804 $object_ids = array_map('intval', $object_ids);
1806 $defaults = array('orderby' => 'name', 'order' => 'ASC', 'fields' => 'all');
1807 $args = wp_parse_args( $args, $defaults );
1810 if ( count($taxonomies) > 1 ) {
1811 foreach ( $taxonomies as $index => $taxonomy ) {
1812 $t = get_taxonomy($taxonomy);
1813 if ( isset($t->args) && is_array($t->args) && $args != array_merge($args, $t->args) ) {
1814 unset($taxonomies[$index]);
1815 $terms = array_merge($terms, wp_get_object_terms($object_ids, $taxonomy, array_merge($args, $t->args)));
1819 $t = get_taxonomy($taxonomies[0]);
1820 if ( isset($t->args) && is_array($t->args) )
1821 $args = array_merge($args, $t->args);
1824 extract($args, EXTR_SKIP);
1826 if ( 'count' == $orderby )
1827 $orderby = 'tt.count';
1828 else if ( 'name' == $orderby )
1829 $orderby = 't.name';
1830 else if ( 'slug' == $orderby )
1831 $orderby = 't.slug';
1832 else if ( 'term_group' == $orderby )
1833 $orderby = 't.term_group';
1834 else if ( 'term_order' == $orderby )
1835 $orderby = 'tr.term_order';
1836 else if ( 'none' == $orderby ) {
1840 $orderby = 't.term_id';
1843 // tt_ids queries can only be none or tr.term_taxonomy_id
1844 if ( ('tt_ids' == $fields) && !empty($orderby) )
1845 $orderby = 'tr.term_taxonomy_id';
1847 if ( !empty($orderby) )
1848 $orderby = "ORDER BY $orderby";
1850 $taxonomies = "'" . implode("', '", $taxonomies) . "'";
1851 $object_ids = implode(', ', $object_ids);
1854 if ( 'all' == $fields )
1855 $select_this = 't.*, tt.*';
1856 else if ( 'ids' == $fields )
1857 $select_this = 't.term_id';
1858 else if ( 'names' == $fields )
1859 $select_this = 't.name';
1860 else if ( 'all_with_object_id' == $fields )
1861 $select_this = 't.*, tt.*, tr.object_id';
1863 $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";
1865 if ( 'all' == $fields || 'all_with_object_id' == $fields ) {
1866 $terms = array_merge($terms, $wpdb->get_results($query));
1867 update_term_cache($terms);
1868 } else if ( 'ids' == $fields || 'names' == $fields ) {
1869 $terms = array_merge($terms, $wpdb->get_col($query));
1870 } else if ( 'tt_ids' == $fields ) {
1871 $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");
1877 return apply_filters('wp_get_object_terms', $terms, $object_ids, $taxonomies, $args);
1881 * Adds a new term to the database. Optionally marks it as an alias of an existing term.
1883 * Error handling is assigned for the nonexistance of the $taxonomy and $term
1884 * parameters before inserting. If both the term id and taxonomy exist
1885 * previously, then an array will be returned that contains the term id and the
1886 * contents of what is returned. The keys of the array are 'term_id' and
1887 * 'term_taxonomy_id' containing numeric values.
1889 * It is assumed that the term does not yet exist or the above will apply. The
1890 * term will be first added to the term table and then related to the taxonomy
1891 * if everything is well. If everything is correct, then several actions will be
1892 * run prior to a filter and then several actions will be run after the filter
1895 * The arguments decide how the term is handled based on the $args parameter.
1896 * The following is a list of the available overrides and the defaults.
1898 * 'alias_of'. There is no default, but if added, expected is the slug that the
1899 * term will be an alias of. Expected to be a string.
1901 * 'description'. There is no default. If exists, will be added to the database
1902 * along with the term. Expected to be a string.
1904 * 'parent'. Expected to be numeric and default is 0 (zero). Will assign value
1905 * of 'parent' to the term.
1907 * 'slug'. Expected to be a string. There is no default.
1909 * If 'slug' argument exists then the slug will be checked to see if it is not
1910 * a valid term. If that check succeeds (it is not a valid term), then it is
1911 * added and the term id is given. If it fails, then a check is made to whether
1912 * the taxonomy is hierarchical and the parent argument is not empty. If the
1913 * second check succeeds, the term will be inserted and the term id will be
1916 * @package WordPress
1917 * @subpackage Taxonomy
1921 * @uses apply_filters() Calls 'pre_insert_term' hook with term and taxonomy as parameters.
1922 * @uses do_action() Calls 'create_term' hook with the term id and taxonomy id as parameters.
1923 * @uses do_action() Calls 'create_$taxonomy' hook with term id and taxonomy id as parameters.
1924 * @uses apply_filters() Calls 'term_id_filter' hook with term id and taxonomy id as parameters.
1925 * @uses do_action() Calls 'created_term' hook with the term id and taxonomy id as parameters.
1926 * @uses do_action() Calls 'created_$taxonomy' hook with term id and taxonomy id as parameters.
1928 * @param string $term The term to add or update.
1929 * @param string $taxonomy The taxonomy to which to add the term
1930 * @param array|string $args Change the values of the inserted term
1931 * @return array|WP_Error The Term ID and Term Taxonomy ID
1933 function wp_insert_term( $term, $taxonomy, $args = array() ) {
1936 if ( ! taxonomy_exists($taxonomy) )
1937 return new WP_Error('invalid_taxonomy', __('Invalid taxonomy'));
1939 $term = apply_filters( 'pre_insert_term', $term, $taxonomy );
1940 if ( is_wp_error( $term ) )
1943 if ( is_int($term) && 0 == $term )
1944 return new WP_Error('invalid_term_id', __('Invalid term ID'));
1946 if ( '' == trim($term) )
1947 return new WP_Error('empty_term_name', __('A name is required for this term'));
1949 $defaults = array( 'alias_of' => '', 'description' => '', 'parent' => 0, 'slug' => '');
1950 $args = wp_parse_args($args, $defaults);
1951 $args['name'] = $term;
1952 $args['taxonomy'] = $taxonomy;
1953 $args = sanitize_term($args, $taxonomy, 'db');
1954 extract($args, EXTR_SKIP);
1956 // expected_slashed ($name)
1957 $name = stripslashes($name);
1958 $description = stripslashes($description);
1961 $slug = sanitize_title($name);
1965 $alias = $wpdb->get_row( $wpdb->prepare( "SELECT term_id, term_group FROM $wpdb->terms WHERE slug = %s", $alias_of) );
1966 if ( $alias->term_group ) {
1967 // The alias we want is already in a group, so let's use that one.
1968 $term_group = $alias->term_group;
1970 // The alias isn't in a group, so let's create a new one and firstly add the alias term to it.
1971 $term_group = $wpdb->get_var("SELECT MAX(term_group) FROM $wpdb->terms") + 1;
1972 do_action( 'edit_terms', $alias->term_id );
1973 $wpdb->update($wpdb->terms, compact('term_group'), array('term_id' => $alias->term_id) );
1974 do_action( 'edited_terms', $alias->term_id );
1978 if ( $term_id = term_exists($slug) ) {
1979 $existing_term = $wpdb->get_row( $wpdb->prepare( "SELECT name FROM $wpdb->terms WHERE term_id = %d", $term_id), ARRAY_A );
1980 // We've got an existing term in the same taxonomy, which matches the name of the new term:
1981 if ( is_taxonomy_hierarchical($taxonomy) && $existing_term['name'] == $name && $exists = term_exists( (int) $term_id, $taxonomy ) ) {
1982 // Hierarchical, and it matches an existing term, Do not allow same "name" in the same level.
1983 $siblings = get_terms($taxonomy, array('fields' => 'names', 'get' => 'all', 'parent' => (int)$parent) );
1984 if ( in_array($name, $siblings) ) {
1985 return new WP_Error('term_exists', __('A term with the name provided already exists with this parent.'), $exists['term_id']);
1987 $slug = wp_unique_term_slug($slug, (object) $args);
1988 if ( false === $wpdb->insert( $wpdb->terms, compact( 'name', 'slug', 'term_group' ) ) )
1989 return new WP_Error('db_insert_error', __('Could not insert term into the database'), $wpdb->last_error);
1990 $term_id = (int) $wpdb->insert_id;
1992 } elseif ( $existing_term['name'] != $name ) {
1993 // We've got an existing term, with a different name, Create the new term.
1994 $slug = wp_unique_term_slug($slug, (object) $args);
1995 if ( false === $wpdb->insert( $wpdb->terms, compact( 'name', 'slug', 'term_group' ) ) )
1996 return new WP_Error('db_insert_error', __('Could not insert term into the database'), $wpdb->last_error);
1997 $term_id = (int) $wpdb->insert_id;
1998 } elseif ( $exists = term_exists( (int) $term_id, $taxonomy ) ) {
1999 // Same name, same slug.
2000 return new WP_Error('term_exists', __('A term with the name provided already exists.'), $exists['term_id']);
2003 // This term does not exist at all in the database, Create it.
2004 $slug = wp_unique_term_slug($slug, (object) $args);
2005 if ( false === $wpdb->insert( $wpdb->terms, compact( 'name', 'slug', 'term_group' ) ) )
2006 return new WP_Error('db_insert_error', __('Could not insert term into the database'), $wpdb->last_error);
2007 $term_id = (int) $wpdb->insert_id;
2010 // Seems unreachable, However, Is used in the case that a term name is provided, which sanitizes to an empty string.
2011 if ( empty($slug) ) {
2012 $slug = sanitize_title($slug, $term_id);
2013 do_action( 'edit_terms', $term_id );
2014 $wpdb->update( $wpdb->terms, compact( 'slug' ), compact( 'term_id' ) );
2015 do_action( 'edited_terms', $term_id );
2018 $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 ) );
2020 if ( !empty($tt_id) )
2021 return array('term_id' => $term_id, 'term_taxonomy_id' => $tt_id);
2023 $wpdb->insert( $wpdb->term_taxonomy, compact( 'term_id', 'taxonomy', 'description', 'parent') + array( 'count' => 0 ) );
2024 $tt_id = (int) $wpdb->insert_id;
2026 do_action("create_term", $term_id, $tt_id, $taxonomy);
2027 do_action("create_$taxonomy", $term_id, $tt_id);
2029 $term_id = apply_filters('term_id_filter', $term_id, $tt_id);
2031 clean_term_cache($term_id, $taxonomy);
2033 do_action("created_term", $term_id, $tt_id, $taxonomy);
2034 do_action("created_$taxonomy", $term_id, $tt_id);
2036 return array('term_id' => $term_id, 'term_taxonomy_id' => $tt_id);
2040 * Create Term and Taxonomy Relationships.
2042 * Relates an object (post, link etc) to a term and taxonomy type. Creates the
2043 * term and taxonomy relationship if it doesn't already exist. Creates a term if
2044 * it doesn't exist (using the slug).
2046 * A relationship means that the term is grouped in or belongs to the taxonomy.
2047 * A term has no meaning until it is given context by defining which taxonomy it
2050 * @package WordPress
2051 * @subpackage Taxonomy
2055 * @param int $object_id The object to relate to.
2056 * @param array|int|string $terms The slug or id of the term, will replace all existing
2057 * related terms in this taxonomy.
2058 * @param array|string $taxonomy The context in which to relate the term to the object.
2059 * @param bool $append If false will delete difference of terms.
2060 * @return array|WP_Error Affected Term IDs
2062 function wp_set_object_terms($object_id, $terms, $taxonomy, $append = false) {
2065 $object_id = (int) $object_id;
2067 if ( ! taxonomy_exists($taxonomy) )
2068 return new WP_Error('invalid_taxonomy', __('Invalid Taxonomy'));
2070 if ( !is_array($terms) )
2071 $terms = array($terms);
2074 $old_tt_ids = wp_get_object_terms($object_id, $taxonomy, array('fields' => 'tt_ids', 'orderby' => 'none'));
2076 $old_tt_ids = array();
2079 $term_ids = array();
2081 foreach ( (array) $terms as $term) {
2082 if ( !strlen(trim($term)) )
2085 if ( !$term_info = term_exists($term, $taxonomy) ) {
2086 // Skip if a non-existent term ID is passed.
2087 if ( is_int($term) )
2089 $term_info = wp_insert_term($term, $taxonomy);
2091 if ( is_wp_error($term_info) )
2093 $term_ids[] = $term_info['term_id'];
2094 $tt_id = $term_info['term_taxonomy_id'];
2097 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 ) ) )
2099 do_action( 'add_term_relationship', $object_id, $tt_id );
2100 $wpdb->insert( $wpdb->term_relationships, array( 'object_id' => $object_id, 'term_taxonomy_id' => $tt_id ) );
2101 do_action( 'added_term_relationship', $object_id, $tt_id );
2104 wp_update_term_count($tt_ids, $taxonomy);
2107 $delete_terms = array_diff($old_tt_ids, $tt_ids);
2108 if ( $delete_terms ) {
2109 $in_delete_terms = "'" . implode("', '", $delete_terms) . "'";
2110 do_action( 'delete_term_relationships', $object_id, $delete_terms );
2111 $wpdb->query( $wpdb->prepare("DELETE FROM $wpdb->term_relationships WHERE object_id = %d AND term_taxonomy_id IN ($in_delete_terms)", $object_id) );
2112 do_action( 'deleted_term_relationships', $object_id, $delete_terms );
2113 wp_update_term_count($delete_terms, $taxonomy);
2117 $t = get_taxonomy($taxonomy);
2118 if ( ! $append && isset($t->sort) && $t->sort ) {
2121 $final_tt_ids = wp_get_object_terms($object_id, $taxonomy, array('fields' => 'tt_ids'));
2122 foreach ( $tt_ids as $tt_id )
2123 if ( in_array($tt_id, $final_tt_ids) )
2124 $values[] = $wpdb->prepare( "(%d, %d, %d)", $object_id, $tt_id, ++$term_order);
2126 $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)");
2129 do_action('set_object_terms', $object_id, $terms, $tt_ids, $taxonomy, $append, $old_tt_ids);
2134 * Will make slug unique, if it isn't already.
2136 * The $slug has to be unique global to every taxonomy, meaning that one
2137 * taxonomy term can't have a matching slug with another taxonomy term. Each
2138 * slug has to be globally unique for every taxonomy.
2140 * The way this works is that if the taxonomy that the term belongs to is
2141 * hierarchical and has a parent, it will append that parent to the $slug.
2143 * If that still doesn't return an unique slug, then it try to append a number
2144 * until it finds a number that is truely unique.
2146 * The only purpose for $term is for appending a parent, if one exists.
2148 * @package WordPress
2149 * @subpackage Taxonomy
2153 * @param string $slug The string that will be tried for a unique slug
2154 * @param object $term The term object that the $slug will belong too
2155 * @return string Will return a true unique slug.
2157 function wp_unique_term_slug($slug, $term) {
2160 if ( ! term_exists( $slug ) )
2163 // If the taxonomy supports hierarchy and the term has a parent, make the slug unique
2164 // by incorporating parent slugs.
2165 if ( is_taxonomy_hierarchical($term->taxonomy) && !empty($term->parent) ) {
2166 $the_parent = $term->parent;
2167 while ( ! empty($the_parent) ) {
2168 $parent_term = get_term($the_parent, $term->taxonomy);
2169 if ( is_wp_error($parent_term) || empty($parent_term) )
2171 $slug .= '-' . $parent_term->slug;
2172 if ( ! term_exists( $slug ) )
2175 if ( empty($parent_term->parent) )
2177 $the_parent = $parent_term->parent;
2181 // If we didn't get a unique slug, try appending a number to make it unique.
2182 if ( !empty($args['term_id']) )
2183 $query = $wpdb->prepare( "SELECT slug FROM $wpdb->terms WHERE slug = %s AND term_id != %d", $slug, $args['term_id'] );
2185 $query = $wpdb->prepare( "SELECT slug FROM $wpdb->terms WHERE slug = %s", $slug );
2187 if ( $wpdb->get_var( $query ) ) {
2190 $alt_slug = $slug . "-$num";
2192 $slug_check = $wpdb->get_var( $wpdb->prepare( "SELECT slug FROM $wpdb->terms WHERE slug = %s", $alt_slug ) );
2193 } while ( $slug_check );
2201 * Update term based on arguments provided.
2203 * The $args will indiscriminately override all values with the same field name.
2204 * Care must be taken to not override important information need to update or
2205 * update will fail (or perhaps create a new term, neither would be acceptable).
2207 * Defaults will set 'alias_of', 'description', 'parent', and 'slug' if not
2208 * defined in $args already.
2210 * 'alias_of' will create a term group, if it doesn't already exist, and update
2213 * If the 'slug' argument in $args is missing, then the 'name' in $args will be
2214 * used. It should also be noted that if you set 'slug' and it isn't unique then
2215 * a WP_Error will be passed back. If you don't pass any slug, then a unique one
2216 * will be created for you.
2218 * For what can be overrode in $args, check the term scheme can contain and stay
2219 * away from the term keys.
2221 * @package WordPress
2222 * @subpackage Taxonomy
2226 * @uses do_action() Will call both 'edit_term' and 'edit_$taxonomy' twice.
2227 * @uses apply_filters() Will call the 'term_id_filter' filter and pass the term
2228 * id and taxonomy id.
2230 * @param int $term_id The ID of the term
2231 * @param string $taxonomy The context in which to relate the term to the object.
2232 * @param array|string $args Overwrite term field values
2233 * @return array|WP_Error Returns Term ID and Taxonomy Term ID
2235 function wp_update_term( $term_id, $taxonomy, $args = array() ) {
2238 if ( ! taxonomy_exists($taxonomy) )
2239 return new WP_Error('invalid_taxonomy', __('Invalid taxonomy'));
2241 $term_id = (int) $term_id;
2243 // First, get all of the original args
2244 $term = get_term ($term_id, $taxonomy, ARRAY_A);
2246 if ( is_wp_error( $term ) )
2249 // Escape data pulled from DB.
2250 $term = add_magic_quotes($term);
2252 // Merge old and new args with new args overwriting old ones.
2253 $args = array_merge($term, $args);
2255 $defaults = array( 'alias_of' => '', 'description' => '', 'parent' => 0, 'slug' => '');
2256 $args = wp_parse_args($args, $defaults);
2257 $args = sanitize_term($args, $taxonomy, 'db');
2258 extract($args, EXTR_SKIP);
2260 // expected_slashed ($name)
2261 $name = stripslashes($name);
2262 $description = stripslashes($description);
2264 if ( '' == trim($name) )
2265 return new WP_Error('empty_term_name', __('A name is required for this term'));
2267 $empty_slug = false;
2268 if ( empty($slug) ) {
2270 $slug = sanitize_title($name);
2274 $alias = $wpdb->get_row( $wpdb->prepare( "SELECT term_id, term_group FROM $wpdb->terms WHERE slug = %s", $alias_of) );
2275 if ( $alias->term_group ) {
2276 // The alias we want is already in a group, so let's use that one.
2277 $term_group = $alias->term_group;
2279 // The alias isn't in a group, so let's create a new one and firstly add the alias term to it.
2280 $term_group = $wpdb->get_var("SELECT MAX(term_group) FROM $wpdb->terms") + 1;
2281 do_action( 'edit_terms', $alias->term_id );
2282 $wpdb->update( $wpdb->terms, compact('term_group'), array( 'term_id' => $alias->term_id ) );
2283 do_action( 'edited_terms', $alias->term_id );
2287 // Check $parent to see if it will cause a hierarchy loop
2288 $parent = apply_filters( 'wp_update_term_parent', $parent, $term_id, $taxonomy, compact( array_keys( $args ) ), $args );
2290 // Check for duplicate slug
2291 $id = $wpdb->get_var( $wpdb->prepare( "SELECT term_id FROM $wpdb->terms WHERE slug = %s", $slug ) );
2292 if ( $id && ($id != $term_id) ) {
2293 // If an empty slug was passed or the parent changed, reset the slug to something unique.
2295 if ( $empty_slug || ( $parent != $term['parent']) )
2296 $slug = wp_unique_term_slug($slug, (object) $args);
2298 return new WP_Error('duplicate_term_slug', sprintf(__('The slug “%s” is already in use by another term'), $slug));
2300 do_action( 'edit_terms', $term_id );
2301 $wpdb->update($wpdb->terms, compact( 'name', 'slug', 'term_group' ), compact( 'term_id' ) );
2302 if ( empty($slug) ) {
2303 $slug = sanitize_title($name, $term_id);
2304 $wpdb->update( $wpdb->terms, compact( 'slug' ), compact( 'term_id' ) );
2306 do_action( 'edited_terms', $term_id );
2308 $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) );
2309 do_action( 'edit_term_taxonomy', $tt_id, $taxonomy );
2310 $wpdb->update( $wpdb->term_taxonomy, compact( 'term_id', 'taxonomy', 'description', 'parent' ), array( 'term_taxonomy_id' => $tt_id ) );
2311 do_action( 'edited_term_taxonomy', $tt_id, $taxonomy );
2313 do_action("edit_term", $term_id, $tt_id, $taxonomy);
2314 do_action("edit_$taxonomy", $term_id, $tt_id);
2316 $term_id = apply_filters('term_id_filter', $term_id, $tt_id);
2318 clean_term_cache($term_id, $taxonomy);
2320 do_action("edited_term", $term_id, $tt_id, $taxonomy);
2321 do_action("edited_$taxonomy", $term_id, $tt_id);
2323 return array('term_id' => $term_id, 'term_taxonomy_id' => $tt_id);
2327 * Enable or disable term counting.
2331 * @param bool $defer Optional. Enable if true, disable if false.
2332 * @return bool Whether term counting is enabled or disabled.
2334 function wp_defer_term_counting($defer=null) {
2335 static $_defer = false;
2337 if ( is_bool($defer) ) {
2339 // flush any deferred counts
2341 wp_update_term_count( null, null, true );
2348 * Updates the amount of terms in taxonomy.
2350 * If there is a taxonomy callback applyed, then it will be called for updating
2353 * The default action is to count what the amount of terms have the relationship
2354 * of term ID. Once that is done, then update the database.
2356 * @package WordPress
2357 * @subpackage Taxonomy
2361 * @param int|array $terms The term_taxonomy_id of the terms
2362 * @param string $taxonomy The context of the term.
2363 * @return bool If no terms will return false, and if successful will return true.
2365 function wp_update_term_count( $terms, $taxonomy, $do_deferred=false ) {
2366 static $_deferred = array();
2368 if ( $do_deferred ) {
2369 foreach ( (array) array_keys($_deferred) as $tax ) {
2370 wp_update_term_count_now( $_deferred[$tax], $tax );
2371 unset( $_deferred[$tax] );
2375 if ( empty($terms) )
2378 if ( !is_array($terms) )
2379 $terms = array($terms);
2381 if ( wp_defer_term_counting() ) {
2382 if ( !isset($_deferred[$taxonomy]) )
2383 $_deferred[$taxonomy] = array();
2384 $_deferred[$taxonomy] = array_unique( array_merge($_deferred[$taxonomy], $terms) );
2388 return wp_update_term_count_now( $terms, $taxonomy );
2392 * Perform term count update immediately.
2396 * @param array $terms The term_taxonomy_id of terms to update.
2397 * @param string $taxonomy The context of the term.
2398 * @return bool Always true when complete.
2400 function wp_update_term_count_now( $terms, $taxonomy ) {
2403 $terms = array_map('intval', $terms);
2405 $taxonomy = get_taxonomy($taxonomy);
2406 if ( !empty($taxonomy->update_count_callback) ) {
2407 call_user_func($taxonomy->update_count_callback, $terms, $taxonomy);
2409 // Default count updater
2410 foreach ( (array) $terms as $term) {
2411 $count = $wpdb->get_var( $wpdb->prepare( "SELECT COUNT(*) FROM $wpdb->term_relationships WHERE term_taxonomy_id = %d", $term) );
2412 do_action( 'edit_term_taxonomy', $term, $taxonomy );
2413 $wpdb->update( $wpdb->term_taxonomy, compact( 'count' ), array( 'term_taxonomy_id' => $term ) );
2414 do_action( 'edited_term_taxonomy', $term, $taxonomy );
2419 clean_term_cache($terms, '', false);
2430 * Removes the taxonomy relationship to terms from the cache.
2432 * Will remove the entire taxonomy relationship containing term $object_id. The
2433 * term IDs have to exist within the taxonomy $object_type for the deletion to
2436 * @package WordPress
2437 * @subpackage Taxonomy
2440 * @see get_object_taxonomies() for more on $object_type
2441 * @uses do_action() Will call action hook named, 'clean_object_term_cache' after completion.
2442 * Passes, function params in same order.
2444 * @param int|array $object_ids Single or list of term object ID(s)
2445 * @param array|string $object_type The taxonomy object type
2447 function clean_object_term_cache($object_ids, $object_type) {
2448 if ( !is_array($object_ids) )
2449 $object_ids = array($object_ids);
2451 foreach ( $object_ids as $id )
2452 foreach ( get_object_taxonomies($object_type) as $taxonomy )
2453 wp_cache_delete($id, "{$taxonomy}_relationships");
2455 do_action('clean_object_term_cache', $object_ids, $object_type);
2460 * Will remove all of the term ids from the cache.
2462 * @package WordPress
2463 * @subpackage Taxonomy
2467 * @param int|array $ids Single or list of Term IDs
2468 * @param string $taxonomy Can be empty and will assume tt_ids, else will use for context.
2469 * @param bool $clean_taxonomy Whether to clean taxonomy wide caches (true), or just individual term object caches (false). Default is true.
2471 function clean_term_cache($ids, $taxonomy = '', $clean_taxonomy = true) {
2473 static $cleaned = array();
2475 if ( !is_array($ids) )
2478 $taxonomies = array();
2479 // If no taxonomy, assume tt_ids.
2480 if ( empty($taxonomy) ) {
2481 $tt_ids = array_map('intval', $ids);
2482 $tt_ids = implode(', ', $tt_ids);
2483 $terms = $wpdb->get_results("SELECT term_id, taxonomy FROM $wpdb->term_taxonomy WHERE term_taxonomy_id IN ($tt_ids)");
2485 foreach ( (array) $terms as $term ) {
2486 $taxonomies[] = $term->taxonomy;
2487 $ids[] = $term->term_id;
2488 wp_cache_delete($term->term_id, $term->taxonomy);
2490 $taxonomies = array_unique($taxonomies);
2492 $taxonomies = array($taxonomy);
2493 foreach ( $taxonomies as $taxonomy ) {
2494 foreach ( $ids as $id ) {
2495 wp_cache_delete($id, $taxonomy);
2500 foreach ( $taxonomies as $taxonomy ) {
2501 if ( isset($cleaned[$taxonomy]) )
2503 $cleaned[$taxonomy] = true;
2505 if ( $clean_taxonomy ) {
2506 wp_cache_delete('all_ids', $taxonomy);
2507 wp_cache_delete('get', $taxonomy);
2508 delete_option("{$taxonomy}_children");
2509 // Regenerate {$taxonomy}_children
2510 _get_term_hierarchy($taxonomy);
2513 do_action('clean_term_cache', $ids, $taxonomy);
2516 wp_cache_set('last_changed', time(), 'terms');
2521 * Retrieves the taxonomy relationship to the term object id.
2523 * @package WordPress
2524 * @subpackage Taxonomy
2527 * @uses wp_cache_get() Retrieves taxonomy relationship from cache
2529 * @param int|array $id Term object ID
2530 * @param string $taxonomy Taxonomy Name
2531 * @return bool|array Empty array if $terms found, but not $taxonomy. False if nothing is in cache for $taxonomy and $id.
2533 function &get_object_term_cache($id, $taxonomy) {
2534 $cache = wp_cache_get($id, "{$taxonomy}_relationships");
2540 * Updates the cache for Term ID(s).
2542 * Will only update the cache for terms not already cached.
2544 * The $object_ids expects that the ids be separated by commas, if it is a
2547 * It should be noted that update_object_term_cache() is very time extensive. It
2548 * is advised that the function is not called very often or at least not for a
2549 * lot of terms that exist in a lot of taxonomies. The amount of time increases
2550 * for each term and it also increases for each taxonomy the term belongs to.
2552 * @package WordPress
2553 * @subpackage Taxonomy
2555 * @uses wp_get_object_terms() Used to get terms from the database to update
2557 * @param string|array $object_ids Single or list of term object ID(s)
2558 * @param array|string $object_type The taxonomy object type
2559 * @return null|bool Null value is given with empty $object_ids. False if
2561 function update_object_term_cache($object_ids, $object_type) {
2562 if ( empty($object_ids) )
2565 if ( !is_array($object_ids) )
2566 $object_ids = explode(',', $object_ids);
2568 $object_ids = array_map('intval', $object_ids);
2570 $taxonomies = get_object_taxonomies($object_type);
2573 foreach ( (array) $object_ids as $id ) {
2574 foreach ( $taxonomies as $taxonomy ) {
2575 if ( false === wp_cache_get($id, "{$taxonomy}_relationships") ) {
2582 if ( empty( $ids ) )
2585 $terms = wp_get_object_terms($ids, $taxonomies, array('fields' => 'all_with_object_id'));
2587 $object_terms = array();
2588 foreach ( (array) $terms as $term )
2589 $object_terms[$term->object_id][$term->taxonomy][$term->term_id] = $term;
2591 foreach ( $ids as $id ) {
2592 foreach ( $taxonomies as $taxonomy ) {
2593 if ( ! isset($object_terms[$id][$taxonomy]) ) {
2594 if ( !isset($object_terms[$id]) )
2595 $object_terms[$id] = array();
2596 $object_terms[$id][$taxonomy] = array();
2601 foreach ( $object_terms as $id => $value ) {
2602 foreach ( $value as $taxonomy => $terms ) {
2603 wp_cache_set($id, $terms, "{$taxonomy}_relationships");
2610 * Updates Terms to Taxonomy in cache.
2612 * @package WordPress
2613 * @subpackage Taxonomy
2616 * @param array $terms List of Term objects to change
2617 * @param string $taxonomy Optional. Update Term to this taxonomy in cache
2619 function update_term_cache($terms, $taxonomy = '') {
2620 foreach ( (array) $terms as $term ) {
2621 $term_taxonomy = $taxonomy;
2622 if ( empty($term_taxonomy) )
2623 $term_taxonomy = $term->taxonomy;
2625 wp_cache_add($term->term_id, $term, $term_taxonomy);
2635 * Retrieves children of taxonomy as Term IDs.
2637 * @package WordPress
2638 * @subpackage Taxonomy
2642 * @uses update_option() Stores all of the children in "$taxonomy_children"
2643 * option. That is the name of the taxonomy, immediately followed by '_children'.
2645 * @param string $taxonomy Taxonomy Name
2646 * @return array Empty if $taxonomy isn't hierarchical or returns children as Term IDs.
2648 function _get_term_hierarchy($taxonomy) {
2649 if ( !is_taxonomy_hierarchical($taxonomy) )
2651 $children = get_option("{$taxonomy}_children");
2653 if ( is_array($children) )
2655 $children = array();
2656 $terms = get_terms($taxonomy, array('get' => 'all', 'orderby' => 'id', 'fields' => 'id=>parent'));
2657 foreach ( $terms as $term_id => $parent ) {
2659 $children[$parent][] = $term_id;
2661 update_option("{$taxonomy}_children", $children);
2668 * Get the subset of $terms that are descendants of $term_id.
2670 * If $terms is an array of objects, then _get_term_children returns an array of objects.
2671 * If $terms is an array of IDs, then _get_term_children returns an array of IDs.
2673 * @package WordPress
2674 * @subpackage Taxonomy
2678 * @param int $term_id The ancestor term: all returned terms should be descendants of $term_id.
2679 * @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.
2680 * @param string $taxonomy The taxonomy which determines the hierarchy of the terms.
2681 * @return array The subset of $terms that are descendants of $term_id.
2683 function &_get_term_children($term_id, $terms, $taxonomy) {
2684 $empty_array = array();
2685 if ( empty($terms) )
2686 return $empty_array;
2688 $term_list = array();
2689 $has_children = _get_term_hierarchy($taxonomy);
2691 if ( ( 0 != $term_id ) && ! isset($has_children[$term_id]) )
2692 return $empty_array;
2694 foreach ( (array) $terms as $term ) {
2696 if ( !is_object($term) ) {
2697 $term = get_term($term, $taxonomy);
2698 if ( is_wp_error( $term ) )
2703 if ( $term->term_id == $term_id )
2706 if ( $term->parent == $term_id ) {
2708 $term_list[] = $term->term_id;
2710 $term_list[] = $term;
2712 if ( !isset($has_children[$term->term_id]) )
2715 if ( $children = _get_term_children($term->term_id, $terms, $taxonomy) )
2716 $term_list = array_merge($term_list, $children);
2725 * Add count of children to parent count.
2727 * Recalculates term counts by including items from child terms. Assumes all
2728 * relevant children are already in the $terms argument.
2730 * @package WordPress
2731 * @subpackage Taxonomy
2736 * @param array $terms List of Term IDs
2737 * @param string $taxonomy Term Context
2738 * @return null Will break from function if conditions are not met.
2740 function _pad_term_counts(&$terms, $taxonomy) {
2743 // This function only works for hierarchical taxonomies like post categories.
2744 if ( !is_taxonomy_hierarchical( $taxonomy ) )
2747 $term_hier = _get_term_hierarchy($taxonomy);
2749 if ( empty($term_hier) )
2752 $term_items = array();
2754 foreach ( (array) $terms as $key => $term ) {
2755 $terms_by_id[$term->term_id] = & $terms[$key];
2756 $term_ids[$term->term_taxonomy_id] = $term->term_id;
2759 // Get the object and term ids and stick them in a lookup table
2760 $tax_obj = get_taxonomy($taxonomy);
2761 $object_types = esc_sql($tax_obj->object_type);
2762 $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'");
2763 foreach ( $results as $row ) {
2764 $id = $term_ids[$row->term_taxonomy_id];
2765 $term_items[$id][$row->object_id] = isset($term_items[$id][$row->object_id]) ? ++$term_items[$id][$row->object_id] : 1;
2768 // Touch every ancestor's lookup row for each post in each term
2769 foreach ( $term_ids as $term_id ) {
2771 while ( $parent = $terms_by_id[$child]->parent ) {
2772 if ( !empty($term_items[$term_id]) )
2773 foreach ( $term_items[$term_id] as $item_id => $touches ) {
2774 $term_items[$parent][$item_id] = isset($term_items[$parent][$item_id]) ? ++$term_items[$parent][$item_id]: 1;
2780 // Transfer the touched cells
2781 foreach ( (array) $term_items as $id => $items )
2782 if ( isset($terms_by_id[$id]) )
2783 $terms_by_id[$id]->count = count($items);
2787 // Default callbacks
2791 * Will update term count based on object types of the current taxonomy.
2793 * Private function for the default callback for post_tag and category
2796 * @package WordPress
2797 * @subpackage Taxonomy
2802 * @param array $terms List of Term taxonomy IDs
2803 * @param object $taxonomy Current taxonomy object of terms
2805 function _update_post_term_count( $terms, $taxonomy ) {
2808 $object_types = is_array($taxonomy->object_type) ? $taxonomy->object_type : array($taxonomy->object_type);
2809 $object_types = esc_sql($object_types);
2811 foreach ( (array) $terms as $term ) {
2812 $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 ) );
2813 do_action( 'edit_term_taxonomy', $term, $taxonomy );
2814 $wpdb->update( $wpdb->term_taxonomy, compact( 'count' ), array( 'term_taxonomy_id' => $term ) );
2815 do_action( 'edited_term_taxonomy', $term, $taxonomy );
2821 * Generates a permalink for a taxonomy term archive.
2825 * @uses apply_filters() Calls 'term_link' with term link and term object, and taxonomy parameters.
2826 * @uses apply_filters() For the post_tag Taxonomy, Calls 'tag_link' with tag link and tag ID as parameters.
2827 * @uses apply_filters() For the category Taxonomy, Calls 'category_link' filter on category link and category ID.
2829 * @param object|int|string $term
2830 * @param string $taxonomy (optional if $term is object)
2831 * @return string|WP_Error HTML link to taxonomy term archive on success, WP_Error if term does not exist.
2833 function get_term_link( $term, $taxonomy = '') {
2836 if ( !is_object($term) ) {
2837 if ( is_int($term) ) {
2838 $term = &get_term($term, $taxonomy);
2840 $term = &get_term_by('slug', $term, $taxonomy);
2844 if ( !is_object($term) )
2845 $term = new WP_Error('invalid_term', __('Empty Term'));
2847 if ( is_wp_error( $term ) )
2850 $taxonomy = $term->taxonomy;
2852 $termlink = $wp_rewrite->get_extra_permastruct($taxonomy);
2854 $slug = $term->slug;
2855 $t = get_taxonomy($taxonomy);
2857 if ( empty($termlink) ) {
2858 if ( 'category' == $taxonomy )
2859 $termlink = '?cat=' . $term->term_id;
2860 elseif ( $t->query_var )
2861 $termlink = "?$t->query_var=$slug";
2863 $termlink = "?taxonomy=$taxonomy&term=$slug";
2864 $termlink = home_url($termlink);
2866 if ( $t->rewrite['hierarchical'] ) {
2867 $hierarchical_slugs = array();
2868 $ancestors = get_ancestors($term->term_id, $taxonomy);
2869 foreach ( (array)$ancestors as $ancestor ) {
2870 $ancestor_term = get_term($ancestor, $taxonomy);
2871 $hierarchical_slugs[] = $ancestor_term->slug;
2873 $hierarchical_slugs = array_reverse($hierarchical_slugs);
2874 $hierarchical_slugs[] = $slug;
2875 $termlink = str_replace("%$taxonomy%", implode('/', $hierarchical_slugs), $termlink);
2877 $termlink = str_replace("%$taxonomy%", $slug, $termlink);
2879 $termlink = home_url( user_trailingslashit($termlink, 'category') );
2881 // Back Compat filters.
2882 if ( 'post_tag' == $taxonomy )
2883 $termlink = apply_filters( 'tag_link', $termlink, $term->term_id );
2884 elseif ( 'category' == $taxonomy )
2885 $termlink = apply_filters( 'category_link', $termlink, $term->term_id );
2887 return apply_filters('term_link', $termlink, $term, $taxonomy);
2891 * Display the taxonomies of a post with available options.
2893 * This function can be used within the loop to display the taxonomies for a
2894 * post without specifying the Post ID. You can also use it outside the Loop to
2895 * display the taxonomies for a specific post.
2897 * The available defaults are:
2898 * 'post' : default is 0. The post ID to get taxonomies of.
2899 * 'before' : default is empty string. Display before taxonomies list.
2900 * 'sep' : default is empty string. Separate every taxonomy with value in this.
2901 * 'after' : default is empty string. Display this after the taxonomies list.
2902 * 'template' : The template to use for displaying the taxonomy terms.
2905 * @uses get_the_taxonomies()
2907 * @param array $args Override the defaults.
2909 function the_taxonomies($args = array()) {
2915 'template' => '%s: %l.'
2918 $r = wp_parse_args( $args, $defaults );
2919 extract( $r, EXTR_SKIP );
2921 echo $before . join($sep, get_the_taxonomies($post, $r)) . $after;
2925 * Retrieve all taxonomies associated with a post.
2927 * This function can be used within the loop. It will also return an array of
2928 * the taxonomies with links to the taxonomy and name.
2932 * @param int $post Optional. Post ID or will use Global Post ID (in loop).
2933 * @param array $args Override the defaults.
2936 function get_the_taxonomies($post = 0, $args = array() ) {
2937 if ( is_int($post) )
2938 $post =& get_post($post);
2939 elseif ( !is_object($post) )
2940 $post =& $GLOBALS['post'];
2942 $args = wp_parse_args( $args, array(
2943 'template' => '%s: %l.',
2945 extract( $args, EXTR_SKIP );
2947 $taxonomies = array();
2952 foreach ( get_object_taxonomies($post) as $taxonomy ) {
2953 $t = (array) get_taxonomy($taxonomy);
2954 if ( empty($t['label']) )
2955 $t['label'] = $taxonomy;
2956 if ( empty($t['args']) )
2957 $t['args'] = array();
2958 if ( empty($t['template']) )
2959 $t['template'] = $template;
2961 $terms = get_object_term_cache($post->ID, $taxonomy);
2962 if ( empty($terms) )
2963 $terms = wp_get_object_terms($post->ID, $taxonomy, $t['args']);
2967 foreach ( $terms as $term )
2968 $links[] = "<a href='" . esc_attr( get_term_link($term) ) . "'>$term->name</a>";
2971 $taxonomies[$taxonomy] = wp_sprintf($t['template'], $t['label'], $links, $terms);
2977 * Retrieve all taxonomies of a post with just the names.
2980 * @uses get_object_taxonomies()
2982 * @param int $post Optional. Post ID
2985 function get_post_taxonomies($post = 0) {
2986 $post =& get_post($post);
2988 return get_object_taxonomies($post);
2992 * Determine if the given object is associated with any of the given terms.
2994 * The given terms are checked against the object's terms' term_ids, names and slugs.
2995 * Terms given as integers will only be checked against the object's terms' term_ids.
2996 * If no terms are given, determines if object is associated with any terms in the given taxonomy.
2999 * @uses get_object_term_cache()
3000 * @uses wp_get_object_terms()
3002 * @param int $object_id ID of the object (post ID, link ID, ...)
3003 * @param string $taxonomy Single taxonomy name
3004 * @param int|string|array $terms Optional. Term term_id, name, slug or array of said
3005 * @return bool|WP_Error. WP_Error on input error.
3007 function is_object_in_term( $object_id, $taxonomy, $terms = null ) {
3008 if ( !$object_id = (int) $object_id )
3009 return new WP_Error( 'invalid_object', __( 'Invalid object ID' ) );
3011 $object_terms = get_object_term_cache( $object_id, $taxonomy );
3012 if ( empty( $object_terms ) )
3013 $object_terms = wp_get_object_terms( $object_id, $taxonomy );
3015 if ( is_wp_error( $object_terms ) )
3016 return $object_terms;
3017 if ( empty( $object_terms ) )
3019 if ( empty( $terms ) )
3020 return ( !empty( $object_terms ) );
3022 $terms = (array) $terms;
3024 if ( $ints = array_filter( $terms, 'is_int' ) )
3025 $strs = array_diff( $terms, $ints );
3029 foreach ( $object_terms as $object_term ) {
3030 if ( $ints && in_array( $object_term->term_id, $ints ) ) return true; // If int, check against term_id
3032 if ( in_array( $object_term->term_id, $strs ) ) return true;
3033 if ( in_array( $object_term->name, $strs ) ) return true;
3034 if ( in_array( $object_term->slug, $strs ) ) return true;
3042 * Determine if the given object type is associated with the given taxonomy.
3045 * @uses get_object_taxonomies()
3047 * @param string $object_type Object type string
3048 * @param string $taxonomy Single taxonomy name
3049 * @return bool True if object is associated with the taxonomy, otherwise false.
3051 function is_object_in_taxonomy($object_type, $taxonomy) {
3052 $taxonomies = get_object_taxonomies($object_type);
3054 if ( empty($taxonomies) )
3057 if ( in_array($taxonomy, $taxonomies) )
3064 * Get an array of ancestor IDs for a given object.
3066 * @param int $object_id The ID of the object
3067 * @param string $object_type The type of object for which we'll be retrieving ancestors.
3068 * @return array of ancestors from lowest to highest in the hierarchy.
3070 function get_ancestors($object_id = 0, $object_type = '') {
3071 $object_id = (int) $object_id;
3073 $ancestors = array();
3075 if ( empty( $object_id ) ) {
3076 return apply_filters('get_ancestors', $ancestors, $object_id, $object_type);
3079 if ( is_taxonomy_hierarchical( $object_type ) ) {
3080 $term = get_term($object_id, $object_type);
3081 while ( ! is_wp_error($term) && ! empty( $term->parent ) && ! in_array( $term->parent, $ancestors ) ) {
3082 $ancestors[] = (int) $term->parent;
3083 $term = get_term($term->parent, $object_type);
3085 } elseif ( null !== get_post_type_object( $object_type ) ) {
3086 $object = get_post($object_id);
3087 if ( ! is_wp_error( $object ) && isset( $object->ancestors ) && is_array( $object->ancestors ) )
3088 $ancestors = $object->ancestors;
3090 while ( ! is_wp_error($object) && ! empty( $object->post_parent ) && ! in_array( $object->post_parent, $ancestors ) ) {
3091 $ancestors[] = (int) $object->post_parent;
3092 $object = get_post($object->post_parent);
3097 return apply_filters('get_ancestors', $ancestors, $object_id, $object_type);
3101 * Returns the term's parent's term_ID
3105 * @param int $term_id
3106 * @param string $taxonomy
3108 * @return int|bool false on error
3110 function wp_get_term_taxonomy_parent_id( $term_id, $taxonomy ) {
3111 $term = get_term( $term_id, $taxonomy );
3112 if ( !$term || is_wp_error( $term ) )
3114 return (int) $term->parent;
3118 * Checks the given subset of the term hierarchy for hierarchy loops.
3119 * Prevents loops from forming and breaks those that it finds.
3121 * Attached to the wp_update_term_parent filter.
3124 * @uses wp_find_hierarchy_loop()
3126 * @param int $parent term_id of the parent for the term we're checking.
3127 * @param int $term_id The term we're checking.
3128 * @param string $taxonomy The taxonomy of the term we're checking.
3130 * @return int The new parent for the term.
3132 function wp_check_term_hierarchy_for_loops( $parent, $term_id, $taxonomy ) {
3133 // Nothing fancy here - bail
3137 // Can't be its own parent
3138 if ( $parent == $term_id )
3141 // Now look for larger loops
3143 if ( !$loop = wp_find_hierarchy_loop( 'wp_get_term_taxonomy_parent_id', $term_id, $parent, array( $taxonomy ) ) )
3144 return $parent; // No loop
3146 // Setting $parent to the given value causes a loop
3147 if ( isset( $loop[$term_id] ) )
3150 // There's a loop, but it doesn't contain $term_id. Break the loop.
3151 foreach ( array_keys( $loop ) as $loop_member )
3152 wp_update_term( $loop_member, $taxonomy, array( 'parent' => 0 ) );