11 // Taxonomy Registration
15 * Creates the initial taxonomies.
17 * This function fires twice: in wp-settings.php before plugins are loaded (for
18 * backwards compatibility reasons), and again on the 'init' action. We must avoid
19 * registering rewrite rules before the 'init' action.
21 function create_initial_taxonomies() {
24 if ( ! did_action( 'init' ) ) {
25 $rewrite = array( 'category' => false, 'post_tag' => false, 'post_format' => false );
27 $post_format_base = apply_filters( 'post_format_rewrite_base', 'type' );
30 'hierarchical' => true,
31 'slug' => get_option('category_base') ? get_option('category_base') : 'category',
32 'with_front' => ! get_option('category_base') || $wp_rewrite->using_index_permalinks(),
33 'ep_mask' => EP_CATEGORIES,
36 'slug' => get_option('tag_base') ? get_option('tag_base') : 'tag',
37 'with_front' => ! get_option('tag_base') || $wp_rewrite->using_index_permalinks(),
40 'post_format' => $post_format_base ? array( 'slug' => $post_format_base ) : false,
44 register_taxonomy( 'category', 'post', array(
45 'hierarchical' => true,
46 'query_var' => 'category_name',
47 'rewrite' => $rewrite['category'],
53 register_taxonomy( 'post_tag', 'post', array(
54 'hierarchical' => false,
56 'rewrite' => $rewrite['post_tag'],
62 register_taxonomy( 'nav_menu', 'nav_menu_item', array(
64 'hierarchical' => false,
66 'name' => __( 'Navigation Menus' ),
67 'singular_name' => __( 'Navigation Menu' ),
73 'show_in_nav_menus' => false,
76 register_taxonomy( 'link_category', 'link', array(
77 'hierarchical' => false,
79 'name' => __( 'Link Categories' ),
80 'singular_name' => __( 'Link Category' ),
81 'search_items' => __( 'Search Link Categories' ),
82 'popular_items' => null,
83 'all_items' => __( 'All Link Categories' ),
84 'edit_item' => __( 'Edit Link Category' ),
85 'update_item' => __( 'Update Link Category' ),
86 'add_new_item' => __( 'Add New Link Category' ),
87 'new_item_name' => __( 'New Link Category Name' ),
88 'separate_items_with_commas' => null,
89 'add_or_remove_items' => null,
90 'choose_from_most_used' => null,
99 register_taxonomy( 'post_format', 'post', array(
101 'hierarchical' => false,
103 'name' => _x( 'Format', 'post format' ),
104 'singular_name' => _x( 'Format', 'post format' ),
107 'rewrite' => $rewrite['post_format'],
110 'show_in_nav_menus' => current_theme_supports( 'post-formats' ),
113 add_action( 'init', 'create_initial_taxonomies', 0 ); // highest priority
116 * Get a list of registered taxonomy objects.
119 * @subpackage Taxonomy
121 * @uses $wp_taxonomies
122 * @see register_taxonomy
124 * @param array $args An array of key => value arguments to match against the taxonomy objects.
125 * @param string $output The type of output to return, either taxonomy 'names' or 'objects'. 'names' is the default.
126 * @param string $operator The logical operation to perform. 'or' means only one element
127 * from the array needs to match; 'and' means all elements must match. The default is 'and'.
128 * @return array A list of taxonomy names or objects
130 function get_taxonomies( $args = array(), $output = 'names', $operator = 'and' ) {
131 global $wp_taxonomies;
133 $field = ('names' == $output) ? 'name' : false;
135 return wp_filter_object_list($wp_taxonomies, $args, $operator, $field);
139 * Return all of the taxonomy names that are of $object_type.
141 * It appears that this function can be used to find all of the names inside of
142 * $wp_taxonomies global variable.
144 * <code><?php $taxonomies = get_object_taxonomies('post'); ?></code> Should
145 * result in <code>Array('category', 'post_tag')</code>
148 * @subpackage Taxonomy
151 * @uses $wp_taxonomies
153 * @param array|string|object $object Name of the type of taxonomy object, or an object (row from posts)
154 * @param string $output The type of output to return, either taxonomy 'names' or 'objects'. 'names' is the default.
155 * @return array The names of all taxonomy of $object_type.
157 function get_object_taxonomies($object, $output = 'names') {
158 global $wp_taxonomies;
160 if ( is_object($object) ) {
161 if ( $object->post_type == 'attachment' )
162 return get_attachment_taxonomies($object);
163 $object = $object->post_type;
166 $object = (array) $object;
168 $taxonomies = array();
169 foreach ( (array) $wp_taxonomies as $tax_name => $tax_obj ) {
170 if ( array_intersect($object, (array) $tax_obj->object_type) ) {
171 if ( 'names' == $output )
172 $taxonomies[] = $tax_name;
174 $taxonomies[ $tax_name ] = $tax_obj;
182 * Retrieves the taxonomy object of $taxonomy.
184 * The get_taxonomy function will first check that the parameter string given
185 * is a taxonomy object and if it is, it will return it.
188 * @subpackage Taxonomy
191 * @uses $wp_taxonomies
192 * @uses taxonomy_exists() Checks whether taxonomy exists
194 * @param string $taxonomy Name of taxonomy object to return
195 * @return object|bool The Taxonomy Object or false if $taxonomy doesn't exist
197 function get_taxonomy( $taxonomy ) {
198 global $wp_taxonomies;
200 if ( ! taxonomy_exists( $taxonomy ) )
203 return $wp_taxonomies[$taxonomy];
207 * Checks that the taxonomy name exists.
209 * Formerly is_taxonomy(), introduced in 2.3.0.
212 * @subpackage Taxonomy
215 * @uses $wp_taxonomies
217 * @param string $taxonomy Name of taxonomy object
218 * @return bool Whether the taxonomy exists.
220 function taxonomy_exists( $taxonomy ) {
221 global $wp_taxonomies;
223 return isset( $wp_taxonomies[$taxonomy] );
227 * Whether the taxonomy object is hierarchical.
229 * Checks to make sure that the taxonomy is an object first. Then Gets the
230 * object, and finally returns the hierarchical value in the object.
232 * A false return value might also mean that the taxonomy does not exist.
235 * @subpackage Taxonomy
238 * @uses taxonomy_exists() Checks whether taxonomy exists
239 * @uses get_taxonomy() Used to get the taxonomy object
241 * @param string $taxonomy Name of taxonomy object
242 * @return bool Whether the taxonomy is hierarchical
244 function is_taxonomy_hierarchical($taxonomy) {
245 if ( ! taxonomy_exists($taxonomy) )
248 $taxonomy = get_taxonomy($taxonomy);
249 return $taxonomy->hierarchical;
253 * Create or modify a taxonomy object. Do not use before init.
255 * A simple function for creating or modifying a taxonomy object based on the
256 * parameters given. The function will accept an array (third optional
257 * parameter), along with strings for the taxonomy name and another string for
260 * Nothing is returned, so expect error maybe or use taxonomy_exists() to check
261 * whether taxonomy exists.
263 * Optional $args contents:
265 * label - Name of the taxonomy shown in the menu. Usually plural. If not set, labels['name'] will be used.
267 * hierarchical - has some defined purpose at other parts of the API and is a
270 * update_count_callback - works much like a hook, in that it will be called when the count is updated.
271 * Defaults to _update_post_term_count() for taxonomies attached to post types, which then confirms
272 * that the objects are published before counting them.
273 * Defaults to _update_generic_term_count() for taxonomies attached to other object types, such as links.
275 * rewrite - false to prevent rewrite, or array('slug'=>$slug) to customize
276 * permastruct; default will use $taxonomy as slug.
278 * query_var - false to prevent queries, or string to customize query var
279 * (?$query_var=$term); default will use $taxonomy as query var.
281 * public - If the taxonomy should be publicly queryable; //@TODO not implemented.
284 * show_ui - If the WordPress UI admin tags UI should apply to this taxonomy;
285 * defaults to public.
287 * show_in_nav_menus - true makes this taxonomy available for selection in navigation menus.
288 * Defaults to public.
290 * show_tagcloud - false to prevent the taxonomy being listed in the Tag Cloud Widget;
291 * defaults to show_ui which defaults to public.
293 * labels - An array of labels for this taxonomy. You can see accepted values in {@link get_taxonomy_labels()}. By default tag labels are used for non-hierarchical types and category labels for hierarchical ones.
296 * @subpackage Taxonomy
298 * @uses $wp_taxonomies Inserts new taxonomy object into the list
299 * @uses $wp Adds query vars
301 * @param string $taxonomy Name of taxonomy object
302 * @param array|string $object_type Name of the object type for the taxonomy object.
303 * @param array|string $args See above description for the two keys values.
305 function register_taxonomy( $taxonomy, $object_type, $args = array() ) {
306 global $wp_taxonomies, $wp;
308 if ( ! is_array($wp_taxonomies) )
309 $wp_taxonomies = array();
311 $defaults = array( 'hierarchical' => false,
312 'update_count_callback' => '',
314 'query_var' => $taxonomy,
317 'show_tagcloud' => null,
320 'capabilities' => array(),
321 'show_in_nav_menus' => null,
323 $args = wp_parse_args($args, $defaults);
325 if ( false !== $args['query_var'] && !empty($wp) ) {
326 if ( true === $args['query_var'] )
327 $args['query_var'] = $taxonomy;
328 $args['query_var'] = sanitize_title_with_dashes($args['query_var']);
329 $wp->add_query_var($args['query_var']);
332 if ( false !== $args['rewrite'] && ( is_admin() || '' != get_option('permalink_structure') ) ) {
333 $args['rewrite'] = wp_parse_args($args['rewrite'], array(
334 'slug' => sanitize_title_with_dashes($taxonomy),
335 'with_front' => true,
336 'hierarchical' => false,
337 'ep_mask' => EP_NONE,
340 if ( $args['hierarchical'] && $args['rewrite']['hierarchical'] )
345 add_rewrite_tag( "%$taxonomy%", $tag, $args['query_var'] ? "{$args['query_var']}=" : "taxonomy=$taxonomy&term=" );
346 add_permastruct( $taxonomy, "{$args['rewrite']['slug']}/%$taxonomy%", $args['rewrite'] );
349 if ( is_null($args['show_ui']) )
350 $args['show_ui'] = $args['public'];
352 // Whether to show this type in nav-menus.php. Defaults to the setting for public.
353 if ( null === $args['show_in_nav_menus'] )
354 $args['show_in_nav_menus'] = $args['public'];
356 if ( is_null($args['show_tagcloud']) )
357 $args['show_tagcloud'] = $args['show_ui'];
359 $default_caps = array(
360 'manage_terms' => 'manage_categories',
361 'edit_terms' => 'manage_categories',
362 'delete_terms' => 'manage_categories',
363 'assign_terms' => 'edit_posts',
365 $args['cap'] = (object) array_merge( $default_caps, $args['capabilities'] );
366 unset( $args['capabilities'] );
368 $args['name'] = $taxonomy;
369 $args['object_type'] = array_unique( (array)$object_type );
371 $args['labels'] = get_taxonomy_labels( (object) $args );
372 $args['label'] = $args['labels']->name;
374 $wp_taxonomies[$taxonomy] = (object) $args;
376 // register callback handling for metabox
377 add_filter('wp_ajax_add-' . $taxonomy, '_wp_ajax_add_hierarchical_term');
379 do_action( 'registered_taxonomy', $taxonomy, $object_type, $args );
383 * Builds an object with all taxonomy labels out of a taxonomy object
385 * Accepted keys of the label array in the taxonomy object:
386 * - name - general name for the taxonomy, usually plural. The same as and overridden by $tax->label. Default is Tags/Categories
387 * - singular_name - name for one object of this taxonomy. Default is Tag/Category
388 * - search_items - Default is Search Tags/Search Categories
389 * - popular_items - This string isn't used on hierarchical taxonomies. Default is Popular Tags
390 * - all_items - Default is All Tags/All Categories
391 * - parent_item - This string isn't used on non-hierarchical taxonomies. In hierarchical ones the default is Parent Category
392 * - parent_item_colon - The same as <code>parent_item</code>, but with colon <code>:</code> in the end
393 * - edit_item - Default is Edit Tag/Edit Category
394 * - view_item - Default is View Tag/View Category
395 * - update_item - Default is Update Tag/Update Category
396 * - add_new_item - Default is Add New Tag/Add New Category
397 * - new_item_name - Default is New Tag Name/New Category Name
398 * - separate_items_with_commas - This string isn't used on hierarchical taxonomies. Default is "Separate tags with commas", used in the meta box.
399 * - add_or_remove_items - This string isn't used on hierarchical taxonomies. Default is "Add or remove tags", used in the meta box when JavaScript is disabled.
400 * - choose_from_most_used - This string isn't used on hierarchical taxonomies. Default is "Choose from the most used tags", used in the meta box.
402 * Above, the first default value is for non-hierarchical taxonomies (like tags) and the second one is for hierarchical taxonomies (like categories).
405 * @param object $tax Taxonomy object
406 * @return object object with all the labels as member variables
409 function get_taxonomy_labels( $tax ) {
410 if ( isset( $tax->helps ) && empty( $tax->labels['separate_items_with_commas'] ) )
411 $tax->labels['separate_items_with_commas'] = $tax->helps;
413 $nohier_vs_hier_defaults = array(
414 'name' => array( _x( 'Tags', 'taxonomy general name' ), _x( 'Categories', 'taxonomy general name' ) ),
415 'singular_name' => array( _x( 'Tag', 'taxonomy singular name' ), _x( 'Category', 'taxonomy singular name' ) ),
416 'search_items' => array( __( 'Search Tags' ), __( 'Search Categories' ) ),
417 'popular_items' => array( __( 'Popular Tags' ), null ),
418 'all_items' => array( __( 'All Tags' ), __( 'All Categories' ) ),
419 'parent_item' => array( null, __( 'Parent Category' ) ),
420 'parent_item_colon' => array( null, __( 'Parent Category:' ) ),
421 'edit_item' => array( __( 'Edit Tag' ), __( 'Edit Category' ) ),
422 'view_item' => array( __( 'View Tag' ), __( 'View Category' ) ),
423 'update_item' => array( __( 'Update Tag' ), __( 'Update Category' ) ),
424 'add_new_item' => array( __( 'Add New Tag' ), __( 'Add New Category' ) ),
425 'new_item_name' => array( __( 'New Tag Name' ), __( 'New Category Name' ) ),
426 'separate_items_with_commas' => array( __( 'Separate tags with commas' ), null ),
427 'add_or_remove_items' => array( __( 'Add or remove tags' ), null ),
428 'choose_from_most_used' => array( __( 'Choose from the most used tags' ), null ),
430 $nohier_vs_hier_defaults['menu_name'] = $nohier_vs_hier_defaults['name'];
432 return _get_custom_object_labels( $tax, $nohier_vs_hier_defaults );
436 * Add an already registered taxonomy to an object type.
439 * @subpackage Taxonomy
441 * @uses $wp_taxonomies Modifies taxonomy object
443 * @param string $taxonomy Name of taxonomy object
444 * @param string $object_type Name of the object type
445 * @return bool True if successful, false if not
447 function register_taxonomy_for_object_type( $taxonomy, $object_type) {
448 global $wp_taxonomies;
450 if ( !isset($wp_taxonomies[$taxonomy]) )
453 if ( ! get_post_type_object($object_type) )
456 if ( ! in_array( $object_type, $wp_taxonomies[$taxonomy]->object_type ) )
457 $wp_taxonomies[$taxonomy]->object_type[] = $object_type;
467 * Retrieve object_ids of valid taxonomy and term.
469 * The strings of $taxonomies must exist before this function will continue. On
470 * failure of finding a valid taxonomy, it will return an WP_Error class, kind
471 * of like Exceptions in PHP 5, except you can't catch them. Even so, you can
472 * still test for the WP_Error class and get the error message.
474 * The $terms aren't checked the same as $taxonomies, but still need to exist
475 * for $object_ids to be returned.
477 * It is possible to change the order that object_ids is returned by either
478 * using PHP sort family functions or using the database by using $args with
479 * either ASC or DESC array. The value should be in the key named 'order'.
482 * @subpackage Taxonomy
486 * @uses wp_parse_args() Creates an array from string $args.
488 * @param int|array $term_ids Term id or array of term ids of terms that will be used
489 * @param string|array $taxonomies String of taxonomy name or Array of string values of taxonomy names
490 * @param array|string $args Change the order of the object_ids, either ASC or DESC
491 * @return WP_Error|array If the taxonomy does not exist, then WP_Error will be returned. On success
492 * the array can be empty meaning that there are no $object_ids found or it will return the $object_ids found.
494 function get_objects_in_term( $term_ids, $taxonomies, $args = array() ) {
497 if ( ! is_array( $term_ids ) )
498 $term_ids = array( $term_ids );
500 if ( ! is_array( $taxonomies ) )
501 $taxonomies = array( $taxonomies );
503 foreach ( (array) $taxonomies as $taxonomy ) {
504 if ( ! taxonomy_exists( $taxonomy ) )
505 return new WP_Error( 'invalid_taxonomy', __( 'Invalid taxonomy' ) );
508 $defaults = array( 'order' => 'ASC' );
509 $args = wp_parse_args( $args, $defaults );
510 extract( $args, EXTR_SKIP );
512 $order = ( 'desc' == strtolower( $order ) ) ? 'DESC' : 'ASC';
514 $term_ids = array_map('intval', $term_ids );
516 $taxonomies = "'" . implode( "', '", $taxonomies ) . "'";
517 $term_ids = "'" . implode( "', '", $term_ids ) . "'";
519 $object_ids = $wpdb->get_col("SELECT tr.object_id FROM $wpdb->term_relationships AS tr INNER JOIN $wpdb->term_taxonomy AS tt ON tr.term_taxonomy_id = tt.term_taxonomy_id WHERE tt.taxonomy IN ($taxonomies) AND tt.term_id IN ($term_ids) ORDER BY tr.object_id $order");
528 * Given a taxonomy query, generates SQL to be appended to a main query.
534 * @param array $tax_query A compact tax query
535 * @param string $primary_table
536 * @param string $primary_id_column
539 function get_tax_sql( $tax_query, $primary_table, $primary_id_column ) {
540 $tax_query_obj = new WP_Tax_Query( $tax_query );
541 return $tax_query_obj->get_sql( $primary_table, $primary_id_column );
545 * Container class for a multiple taxonomy query.
552 * List of taxonomy queries. A single taxonomy query is an associative array:
553 * - 'taxonomy' string The taxonomy being queried
554 * - 'terms' string|array The list of terms
555 * - 'field' string (optional) Which term field is being used.
556 * Possible values: 'term_id', 'slug' or 'name'
558 * - 'operator' string (optional)
559 * Possible values: 'AND', 'IN' or 'NOT IN'.
561 * - 'include_children' bool (optional) Whether to include child terms.
568 public $queries = array();
571 * The relation between the queries. Can be one of 'AND' or 'OR'.
580 * Standard response when the query should not return any rows.
586 private static $no_results = array( 'join' => '', 'where' => ' AND 0 = 1' );
591 * Parses a compact tax query and sets defaults.
596 * @param array $tax_query A compact tax query:
598 * 'relation' => 'OR',
600 * 'taxonomy' => 'tax1',
601 * 'terms' => array( 'term1', 'term2' ),
605 * 'taxonomy' => 'tax2',
606 * 'terms' => array( 'term-a', 'term-b' ),
611 public function __construct( $tax_query ) {
612 if ( isset( $tax_query['relation'] ) && strtoupper( $tax_query['relation'] ) == 'OR' ) {
613 $this->relation = 'OR';
615 $this->relation = 'AND';
621 'include_children' => true,
622 'field' => 'term_id',
626 foreach ( $tax_query as $query ) {
627 if ( ! is_array( $query ) )
630 $query = array_merge( $defaults, $query );
632 $query['terms'] = (array) $query['terms'];
634 $this->queries[] = $query;
639 * Generates SQL clauses to be appended to a main query.
644 * @param string $primary_table
645 * @param string $primary_id_column
648 public function get_sql( $primary_table, $primary_id_column ) {
655 foreach ( $this->queries as $query ) {
656 $this->clean_query( $query );
658 if ( is_wp_error( $query ) ) {
659 return self::$no_results;
664 if ( 'IN' == $operator ) {
666 if ( empty( $terms ) ) {
667 if ( 'OR' == $this->relation )
670 return self::$no_results;
673 $terms = implode( ',', $terms );
675 $alias = $i ? 'tt' . $i : $wpdb->term_relationships;
677 $join .= " INNER JOIN $wpdb->term_relationships";
678 $join .= $i ? " AS $alias" : '';
679 $join .= " ON ($primary_table.$primary_id_column = $alias.object_id)";
681 $where[] = "$alias.term_taxonomy_id $operator ($terms)";
682 } elseif ( 'NOT IN' == $operator ) {
684 if ( empty( $terms ) )
687 $terms = implode( ',', $terms );
689 $where[] = "$primary_table.$primary_id_column NOT IN (
691 FROM $wpdb->term_relationships
692 WHERE term_taxonomy_id IN ($terms)
694 } elseif ( 'AND' == $operator ) {
696 if ( empty( $terms ) )
699 $num_terms = count( $terms );
701 $terms = implode( ',', $terms );
705 FROM $wpdb->term_relationships
706 WHERE term_taxonomy_id IN ($terms)
707 AND object_id = $primary_table.$primary_id_column
714 if ( !empty( $where ) )
715 $where = ' AND ( ' . implode( " $this->relation ", $where ) . ' )';
719 return compact( 'join', 'where' );
723 * Validates a single query.
728 * @param array &$query The single query
730 private function clean_query( &$query ) {
731 if ( ! taxonomy_exists( $query['taxonomy'] ) ) {
732 $query = new WP_Error( 'Invalid taxonomy' );
736 $query['terms'] = array_unique( (array) $query['terms'] );
738 if ( is_taxonomy_hierarchical( $query['taxonomy'] ) && $query['include_children'] ) {
739 $this->transform_query( $query, 'term_id' );
741 if ( is_wp_error( $query ) )
745 foreach ( $query['terms'] as $term ) {
746 $children = array_merge( $children, get_term_children( $term, $query['taxonomy'] ) );
749 $query['terms'] = $children;
752 $this->transform_query( $query, 'term_taxonomy_id' );
756 * Transforms a single query, from one field to another.
761 * @param array &$query The single query
762 * @param string $resulting_field The resulting field
764 private function transform_query( &$query, $resulting_field ) {
767 if ( empty( $query['terms'] ) )
770 if ( $query['field'] == $resulting_field )
773 $resulting_field = esc_sql( $resulting_field );
775 switch ( $query['field'] ) {
778 $terms = "'" . implode( "','", array_map( 'sanitize_title_for_query', $query['terms'] ) ) . "'";
779 $terms = $wpdb->get_col( "
780 SELECT $wpdb->term_taxonomy.$resulting_field
781 FROM $wpdb->term_taxonomy
782 INNER JOIN $wpdb->terms USING (term_id)
783 WHERE taxonomy = '{$query['taxonomy']}'
784 AND $wpdb->terms.{$query['field']} IN ($terms)
789 $terms = implode( ',', array_map( 'intval', $query['terms'] ) );
790 $terms = $wpdb->get_col( "
791 SELECT $resulting_field
792 FROM $wpdb->term_taxonomy
793 WHERE taxonomy = '{$query['taxonomy']}'
794 AND term_id IN ($terms)
798 if ( 'AND' == $query['operator'] && count( $terms ) < count( $query['terms'] ) ) {
799 $query = new WP_Error( 'Inexistent terms' );
803 $query['terms'] = $terms;
804 $query['field'] = $resulting_field;
809 * Get all Term data from database by Term ID.
811 * The usage of the get_term function is to apply filters to a term object. It
812 * is possible to get a term object from the database before applying the
815 * $term ID must be part of $taxonomy, to get from the database. Failure, might
816 * be able to be captured by the hooks. Failure would be the same value as $wpdb
817 * returns for the get_row method.
819 * There are two hooks, one is specifically for each term, named 'get_term', and
820 * the second is for the taxonomy name, 'term_$taxonomy'. Both hooks gets the
821 * term object, and the taxonomy name as parameters. Both hooks are expected to
822 * return a Term object.
824 * 'get_term' hook - Takes two parameters the term Object and the taxonomy name.
825 * Must return term object. Used in get_term() as a catch-all filter for every
828 * 'get_$taxonomy' hook - Takes two parameters the term Object and the taxonomy
829 * name. Must return term object. $taxonomy will be the taxonomy name, so for
830 * example, if 'category', it would be 'get_category' as the filter name. Useful
831 * for custom taxonomies or plugging into default taxonomies.
834 * @subpackage Taxonomy
838 * @uses sanitize_term() Cleanses the term based on $filter context before returning.
839 * @see sanitize_term_field() The $context param lists the available values for get_term_by() $filter param.
841 * @param int|object $term If integer, will get from database. If object will apply filters and return $term.
842 * @param string $taxonomy Taxonomy name that $term is part of.
843 * @param string $output Constant OBJECT, ARRAY_A, or ARRAY_N
844 * @param string $filter Optional, default is raw or no WordPress defined filter will applied.
845 * @return mixed|null|WP_Error Term Row from database. Will return null if $term is empty. If taxonomy does not
846 * exist then WP_Error will be returned.
848 function &get_term($term, $taxonomy, $output = OBJECT, $filter = 'raw') {
852 if ( empty($term) ) {
853 $error = new WP_Error('invalid_term', __('Empty Term'));
857 if ( ! taxonomy_exists($taxonomy) ) {
858 $error = new WP_Error('invalid_taxonomy', __('Invalid taxonomy'));
862 if ( is_object($term) && empty($term->filter) ) {
863 wp_cache_add($term->term_id, $term, $taxonomy);
866 if ( is_object($term) )
867 $term = $term->term_id;
868 if ( !$term = (int) $term )
870 if ( ! $_term = wp_cache_get($term, $taxonomy) ) {
871 $_term = $wpdb->get_row( $wpdb->prepare( "SELECT t.*, tt.* FROM $wpdb->terms AS t INNER JOIN $wpdb->term_taxonomy AS tt ON t.term_id = tt.term_id WHERE tt.taxonomy = %s AND t.term_id = %d LIMIT 1", $taxonomy, $term) );
874 wp_cache_add($term, $_term, $taxonomy);
878 $_term = apply_filters('get_term', $_term, $taxonomy);
879 $_term = apply_filters("get_$taxonomy", $_term, $taxonomy);
880 $_term = sanitize_term($_term, $taxonomy, $filter);
882 if ( $output == OBJECT ) {
884 } elseif ( $output == ARRAY_A ) {
885 $__term = get_object_vars($_term);
887 } elseif ( $output == ARRAY_N ) {
888 $__term = array_values(get_object_vars($_term));
896 * Get all Term data from database by Term field and data.
898 * Warning: $value is not escaped for 'name' $field. You must do it yourself, if
901 * The default $field is 'id', therefore it is possible to also use null for
902 * field, but not recommended that you do so.
904 * If $value does not exist, the return value will be false. If $taxonomy exists
905 * and $field and $value combinations exist, the Term will be returned.
908 * @subpackage Taxonomy
912 * @uses sanitize_term() Cleanses the term based on $filter context before returning.
913 * @see sanitize_term_field() The $context param lists the available values for get_term_by() $filter param.
915 * @param string $field Either 'slug', 'name', or 'id'
916 * @param string|int $value Search for this term value
917 * @param string $taxonomy Taxonomy Name
918 * @param string $output Constant OBJECT, ARRAY_A, or ARRAY_N
919 * @param string $filter Optional, default is raw or no WordPress defined filter will applied.
920 * @return mixed Term Row from database. Will return false if $taxonomy does not exist or $term was not found.
922 function get_term_by($field, $value, $taxonomy, $output = OBJECT, $filter = 'raw') {
925 if ( ! taxonomy_exists($taxonomy) )
928 if ( 'slug' == $field ) {
930 $value = sanitize_title($value);
933 } else if ( 'name' == $field ) {
934 // Assume already escaped
935 $value = stripslashes($value);
938 $term = get_term( (int) $value, $taxonomy, $output, $filter);
939 if ( is_wp_error( $term ) )
944 $term = $wpdb->get_row( $wpdb->prepare( "SELECT t.*, tt.* FROM $wpdb->terms AS t INNER JOIN $wpdb->term_taxonomy AS tt ON t.term_id = tt.term_id WHERE tt.taxonomy = %s AND $field = %s LIMIT 1", $taxonomy, $value) );
948 wp_cache_add($term->term_id, $term, $taxonomy);
950 $term = apply_filters('get_term', $term, $taxonomy);
951 $term = apply_filters("get_$taxonomy", $term, $taxonomy);
952 $term = sanitize_term($term, $taxonomy, $filter);
954 if ( $output == OBJECT ) {
956 } elseif ( $output == ARRAY_A ) {
957 return get_object_vars($term);
958 } elseif ( $output == ARRAY_N ) {
959 return array_values(get_object_vars($term));
966 * Merge all term children into a single array of their IDs.
968 * This recursive function will merge all of the children of $term into the same
969 * array of term IDs. Only useful for taxonomies which are hierarchical.
971 * Will return an empty array if $term does not exist in $taxonomy.
974 * @subpackage Taxonomy
978 * @uses _get_term_hierarchy()
979 * @uses get_term_children() Used to get the children of both $taxonomy and the parent $term
981 * @param string $term_id ID of Term to get children
982 * @param string $taxonomy Taxonomy Name
983 * @return array|WP_Error List of Term Objects. WP_Error returned if $taxonomy does not exist
985 function get_term_children( $term_id, $taxonomy ) {
986 if ( ! taxonomy_exists($taxonomy) )
987 return new WP_Error('invalid_taxonomy', __('Invalid taxonomy'));
989 $term_id = intval( $term_id );
991 $terms = _get_term_hierarchy($taxonomy);
993 if ( ! isset($terms[$term_id]) )
996 $children = $terms[$term_id];
998 foreach ( (array) $terms[$term_id] as $child ) {
999 if ( isset($terms[$child]) )
1000 $children = array_merge($children, get_term_children($child, $taxonomy));
1007 * Get sanitized Term field.
1009 * Does checks for $term, based on the $taxonomy. The function is for contextual
1010 * reasons and for simplicity of usage. See sanitize_term_field() for more
1013 * @package WordPress
1014 * @subpackage Taxonomy
1017 * @uses sanitize_term_field() Passes the return value in sanitize_term_field on success.
1019 * @param string $field Term field to fetch
1020 * @param int $term Term ID
1021 * @param string $taxonomy Taxonomy Name
1022 * @param string $context Optional, default is display. Look at sanitize_term_field() for available options.
1023 * @return mixed Will return an empty string if $term is not an object or if $field is not set in $term.
1025 function get_term_field( $field, $term, $taxonomy, $context = 'display' ) {
1026 $term = (int) $term;
1027 $term = get_term( $term, $taxonomy );
1028 if ( is_wp_error($term) )
1031 if ( !is_object($term) )
1034 if ( !isset($term->$field) )
1037 return sanitize_term_field($field, $term->$field, $term->term_id, $taxonomy, $context);
1041 * Sanitizes Term for editing.
1043 * Return value is sanitize_term() and usage is for sanitizing the term for
1044 * editing. Function is for contextual and simplicity.
1046 * @package WordPress
1047 * @subpackage Taxonomy
1050 * @uses sanitize_term() Passes the return value on success
1052 * @param int|object $id Term ID or Object
1053 * @param string $taxonomy Taxonomy Name
1054 * @return mixed|null|WP_Error Will return empty string if $term is not an object.
1056 function get_term_to_edit( $id, $taxonomy ) {
1057 $term = get_term( $id, $taxonomy );
1059 if ( is_wp_error($term) )
1062 if ( !is_object($term) )
1065 return sanitize_term($term, $taxonomy, 'edit');
1069 * Retrieve the terms in a given taxonomy or list of taxonomies.
1071 * You can fully inject any customizations to the query before it is sent, as
1072 * well as control the output with a filter.
1074 * The 'get_terms' filter will be called when the cache has the term and will
1075 * pass the found term along with the array of $taxonomies and array of $args.
1076 * This filter is also called before the array of terms is passed and will pass
1077 * the array of terms, along with the $taxonomies and $args.
1079 * The 'list_terms_exclusions' filter passes the compiled exclusions along with
1082 * The 'get_terms_orderby' filter passes the ORDER BY clause for the query
1083 * along with the $args array.
1085 * The 'get_terms_fields' filter passes the fields for the SELECT query
1086 * along with the $args array.
1088 * The list of arguments that $args can contain, which will overwrite the defaults:
1090 * orderby - Default is 'name'. Can be name, count, term_group, slug or nothing
1091 * (will use term_id), Passing a custom value other than these will cause it to
1092 * order based on the custom value.
1094 * order - Default is ASC. Can use DESC.
1096 * hide_empty - Default is true. Will not return empty terms, which means
1097 * terms whose count is 0 according to the given taxonomy.
1099 * exclude - Default is an empty array. An array, comma- or space-delimited string
1100 * of term ids to exclude from the return array. If 'include' is non-empty,
1101 * 'exclude' is ignored.
1103 * exclude_tree - Default is an empty array. An array, comma- or space-delimited
1104 * string of term ids to exclude from the return array, along with all of their
1105 * descendant terms according to the primary taxonomy. If 'include' is non-empty,
1106 * 'exclude_tree' is ignored.
1108 * include - Default is an empty array. An array, comma- or space-delimited string
1109 * of term ids to include in the return array.
1111 * number - The maximum number of terms to return. Default is to return them all.
1113 * offset - The number by which to offset the terms query.
1115 * fields - Default is 'all', which returns an array of term objects.
1116 * If 'fields' is 'ids' or 'names', returns an array of
1117 * integers or strings, respectively.
1119 * slug - Returns terms whose "slug" matches this value. Default is empty string.
1121 * hierarchical - Whether to include terms that have non-empty descendants
1122 * (even if 'hide_empty' is set to true).
1124 * search - Returned terms' names will contain the value of 'search',
1125 * case-insensitive. Default is an empty string.
1127 * name__like - Returned terms' names will begin with the value of 'name__like',
1128 * case-insensitive. Default is empty string.
1130 * The argument 'pad_counts', if set to true will include the quantity of a term's
1131 * children in the quantity of each term's "count" object variable.
1133 * The 'get' argument, if set to 'all' instead of its default empty string,
1134 * returns terms regardless of ancestry or whether the terms are empty.
1136 * The 'child_of' argument, when used, should be set to the integer of a term ID. Its default
1137 * is 0. If set to a non-zero value, all returned terms will be descendants
1138 * of that term according to the given taxonomy. Hence 'child_of' is set to 0
1139 * if more than one taxonomy is passed in $taxonomies, because multiple taxonomies
1140 * make term ancestry ambiguous.
1142 * The 'parent' argument, when used, should be set to the integer of a term ID. Its default is
1143 * the empty string '', which has a different meaning from the integer 0.
1144 * If set to an integer value, all returned terms will have as an immediate
1145 * ancestor the term whose ID is specified by that integer according to the given taxonomy.
1146 * The 'parent' argument is different from 'child_of' in that a term X is considered a 'parent'
1147 * of term Y only if term X is the father of term Y, not its grandfather or great-grandfather, etc.
1149 * The 'cache_domain' argument enables a unique cache key to be produced when this query is stored
1150 * in object cache. For instance, if you are using one of this function's filters to modify the
1151 * query (such as 'terms_clauses'), setting 'cache_domain' to a unique value will not overwrite
1152 * the cache for similar queries. Default value is 'core'.
1154 * @package WordPress
1155 * @subpackage Taxonomy
1159 * @uses wp_parse_args() Merges the defaults with those defined by $args and allows for strings.
1161 * @param string|array $taxonomies Taxonomy name or list of Taxonomy names
1162 * @param string|array $args The values of what to search for when returning terms
1163 * @return array|WP_Error List of Term Objects and their children. Will return WP_Error, if any of $taxonomies do not exist.
1165 function &get_terms($taxonomies, $args = '') {
1167 $empty_array = array();
1169 $single_taxonomy = false;
1170 if ( !is_array($taxonomies) ) {
1171 $single_taxonomy = true;
1172 $taxonomies = array($taxonomies);
1175 foreach ( $taxonomies as $taxonomy ) {
1176 if ( ! taxonomy_exists($taxonomy) ) {
1177 $error = new WP_Error('invalid_taxonomy', __('Invalid taxonomy'));
1182 $defaults = array('orderby' => 'name', 'order' => 'ASC',
1183 'hide_empty' => true, 'exclude' => array(), 'exclude_tree' => array(), 'include' => array(),
1184 'number' => '', 'fields' => 'all', 'slug' => '', 'parent' => '',
1185 'hierarchical' => true, 'child_of' => 0, 'get' => '', 'name__like' => '',
1186 'pad_counts' => false, 'offset' => '', 'search' => '', 'cache_domain' => 'core' );
1187 $args = wp_parse_args( $args, $defaults );
1188 $args['number'] = absint( $args['number'] );
1189 $args['offset'] = absint( $args['offset'] );
1190 if ( !$single_taxonomy || !is_taxonomy_hierarchical($taxonomies[0]) ||
1191 '' !== $args['parent'] ) {
1192 $args['child_of'] = 0;
1193 $args['hierarchical'] = false;
1194 $args['pad_counts'] = false;
1197 if ( 'all' == $args['get'] ) {
1198 $args['child_of'] = 0;
1199 $args['hide_empty'] = 0;
1200 $args['hierarchical'] = false;
1201 $args['pad_counts'] = false;
1204 $args = apply_filters( 'get_terms_args', $args, $taxonomies );
1206 extract($args, EXTR_SKIP);
1209 $hierarchy = _get_term_hierarchy($taxonomies[0]);
1210 if ( !isset($hierarchy[$child_of]) )
1211 return $empty_array;
1215 $hierarchy = _get_term_hierarchy($taxonomies[0]);
1216 if ( !isset($hierarchy[$parent]) )
1217 return $empty_array;
1220 // $args can be whatever, only use the args defined in defaults to compute the key
1221 $filter_key = ( has_filter('list_terms_exclusions') ) ? serialize($GLOBALS['wp_filter']['list_terms_exclusions']) : '';
1222 $key = md5( serialize( compact(array_keys($defaults)) ) . serialize( $taxonomies ) . $filter_key );
1223 $last_changed = wp_cache_get('last_changed', 'terms');
1224 if ( !$last_changed ) {
1225 $last_changed = time();
1226 wp_cache_set('last_changed', $last_changed, 'terms');
1228 $cache_key = "get_terms:$key:$last_changed";
1229 $cache = wp_cache_get( $cache_key, 'terms' );
1230 if ( false !== $cache ) {
1231 $cache = apply_filters('get_terms', $cache, $taxonomies, $args);
1235 $_orderby = strtolower($orderby);
1236 if ( 'count' == $_orderby )
1237 $orderby = 'tt.count';
1238 else if ( 'name' == $_orderby )
1239 $orderby = 't.name';
1240 else if ( 'slug' == $_orderby )
1241 $orderby = 't.slug';
1242 else if ( 'term_group' == $_orderby )
1243 $orderby = 't.term_group';
1244 else if ( 'none' == $_orderby )
1246 elseif ( empty($_orderby) || 'id' == $_orderby )
1247 $orderby = 't.term_id';
1249 $orderby = 't.name';
1251 $orderby = apply_filters( 'get_terms_orderby', $orderby, $args );
1253 if ( !empty($orderby) )
1254 $orderby = "ORDER BY $orderby";
1258 $order = strtoupper( $order );
1259 if ( '' !== $order && !in_array( $order, array( 'ASC', 'DESC' ) ) )
1262 $where = "tt.taxonomy IN ('" . implode("', '", $taxonomies) . "')";
1264 if ( !empty($include) ) {
1267 $interms = wp_parse_id_list($include);
1268 foreach ( $interms as $interm ) {
1269 if ( empty($inclusions) )
1270 $inclusions = ' AND ( t.term_id = ' . intval($interm) . ' ';
1272 $inclusions .= ' OR t.term_id = ' . intval($interm) . ' ';
1276 if ( !empty($inclusions) )
1278 $where .= $inclusions;
1281 if ( !empty( $exclude_tree ) ) {
1282 $excluded_trunks = wp_parse_id_list($exclude_tree);
1283 foreach ( $excluded_trunks as $extrunk ) {
1284 $excluded_children = (array) get_terms($taxonomies[0], array('child_of' => intval($extrunk), 'fields' => 'ids', 'hide_empty' => 0));
1285 $excluded_children[] = $extrunk;
1286 foreach( $excluded_children as $exterm ) {
1287 if ( empty($exclusions) )
1288 $exclusions = ' AND ( t.term_id <> ' . intval($exterm) . ' ';
1290 $exclusions .= ' AND t.term_id <> ' . intval($exterm) . ' ';
1295 if ( !empty($exclude) ) {
1296 $exterms = wp_parse_id_list($exclude);
1297 foreach ( $exterms as $exterm ) {
1298 if ( empty($exclusions) )
1299 $exclusions = ' AND ( t.term_id <> ' . intval($exterm) . ' ';
1301 $exclusions .= ' AND t.term_id <> ' . intval($exterm) . ' ';
1305 if ( !empty($exclusions) )
1307 $exclusions = apply_filters('list_terms_exclusions', $exclusions, $args );
1308 $where .= $exclusions;
1310 if ( !empty($slug) ) {
1311 $slug = sanitize_title($slug);
1312 $where .= " AND t.slug = '$slug'";
1315 if ( !empty($name__like) ) {
1316 $name__like = like_escape( $name__like );
1317 $where .= $wpdb->prepare( " AND t.name LIKE %s", $name__like . '%' );
1320 if ( '' !== $parent ) {
1321 $parent = (int) $parent;
1322 $where .= " AND tt.parent = '$parent'";
1325 if ( $hide_empty && !$hierarchical )
1326 $where .= ' AND tt.count > 0';
1328 // don't limit the query results when we have to descend the family tree
1329 if ( ! empty($number) && ! $hierarchical && empty( $child_of ) && '' === $parent ) {
1331 $limits = 'LIMIT ' . $offset . ',' . $number;
1333 $limits = 'LIMIT ' . $number;
1338 if ( !empty($search) ) {
1339 $search = like_escape($search);
1340 $where .= $wpdb->prepare( " AND (t.name LIKE %s)", '%' . $search . '%');
1344 switch ( $fields ) {
1346 $selects = array('t.*', 'tt.*');
1350 $selects = array('t.term_id', 'tt.parent', 'tt.count');
1353 $selects = array('t.term_id', 'tt.parent', 'tt.count', 't.name');
1358 $selects = array('COUNT(*)');
1363 $fields = implode(', ', apply_filters( 'get_terms_fields', $selects, $args ));
1365 $join = "INNER JOIN $wpdb->term_taxonomy AS tt ON t.term_id = tt.term_id";
1367 $pieces = array( 'fields', 'join', 'where', 'orderby', 'order', 'limits' );
1368 $clauses = apply_filters( 'terms_clauses', compact( $pieces ), $taxonomies, $args );
1369 foreach ( $pieces as $piece )
1370 $$piece = isset( $clauses[ $piece ] ) ? $clauses[ $piece ] : '';
1372 $query = "SELECT $fields FROM $wpdb->terms AS t $join WHERE $where $orderby $order $limits";
1376 if ( 'count' == $fields ) {
1377 $term_count = $wpdb->get_var($query);
1381 $terms = $wpdb->get_results($query);
1382 if ( 'all' == $fields ) {
1383 update_term_cache($terms);
1386 if ( empty($terms) ) {
1387 wp_cache_add( $cache_key, array(), 'terms', 86400 ); // one day
1388 $terms = apply_filters('get_terms', array(), $taxonomies, $args);
1393 $children = _get_term_hierarchy($taxonomies[0]);
1394 if ( ! empty($children) )
1395 $terms = & _get_term_children($child_of, $terms, $taxonomies[0]);
1398 // Update term counts to include children.
1399 if ( $pad_counts && 'all' == $fields )
1400 _pad_term_counts($terms, $taxonomies[0]);
1402 // Make sure we show empty categories that have children.
1403 if ( $hierarchical && $hide_empty && is_array($terms) ) {
1404 foreach ( $terms as $k => $term ) {
1405 if ( ! $term->count ) {
1406 $children = _get_term_children($term->term_id, $terms, $taxonomies[0]);
1407 if ( is_array($children) )
1408 foreach ( $children as $child )
1409 if ( $child->count )
1412 // It really is empty
1420 if ( 'id=>parent' == $fields ) {
1421 while ( $term = array_shift($terms) )
1422 $_terms[$term->term_id] = $term->parent;
1424 } elseif ( 'ids' == $fields ) {
1425 while ( $term = array_shift($terms) )
1426 $_terms[] = $term->term_id;
1428 } elseif ( 'names' == $fields ) {
1429 while ( $term = array_shift($terms) )
1430 $_terms[] = $term->name;
1434 if ( 0 < $number && intval(@count($terms)) > $number ) {
1435 $terms = array_slice($terms, $offset, $number);
1438 wp_cache_add( $cache_key, $terms, 'terms', 86400 ); // one day
1440 $terms = apply_filters('get_terms', $terms, $taxonomies, $args);
1445 * Check if Term exists.
1447 * Formerly is_term(), introduced in 2.3.0.
1449 * @package WordPress
1450 * @subpackage Taxonomy
1455 * @param int|string $term The term to check
1456 * @param string $taxonomy The taxonomy name to use
1457 * @param int $parent ID of parent term under which to confine the exists search.
1458 * @return mixed Returns 0 if the term does not exist. Returns the term ID if no taxonomy is specified
1459 * and the term ID exists. Returns an array of the term ID and the taxonomy if the pairing exists.
1461 function term_exists($term, $taxonomy = '', $parent = 0) {
1464 $select = "SELECT term_id FROM $wpdb->terms as t WHERE ";
1465 $tax_select = "SELECT tt.term_id, tt.term_taxonomy_id FROM $wpdb->terms AS t INNER JOIN $wpdb->term_taxonomy as tt ON tt.term_id = t.term_id WHERE ";
1467 if ( is_int($term) ) {
1470 $where = 't.term_id = %d';
1471 if ( !empty($taxonomy) )
1472 return $wpdb->get_row( $wpdb->prepare( $tax_select . $where . " AND tt.taxonomy = %s", $term, $taxonomy ), ARRAY_A );
1474 return $wpdb->get_var( $wpdb->prepare( $select . $where, $term ) );
1477 $term = trim( stripslashes( $term ) );
1479 if ( '' === $slug = sanitize_title($term) )
1482 $where = 't.slug = %s';
1483 $else_where = 't.name = %s';
1484 $where_fields = array($slug);
1485 $else_where_fields = array($term);
1486 if ( !empty($taxonomy) ) {
1487 $parent = (int) $parent;
1488 if ( $parent > 0 ) {
1489 $where_fields[] = $parent;
1490 $else_where_fields[] = $parent;
1491 $where .= ' AND tt.parent = %d';
1492 $else_where .= ' AND tt.parent = %d';
1495 $where_fields[] = $taxonomy;
1496 $else_where_fields[] = $taxonomy;
1498 if ( $result = $wpdb->get_row( $wpdb->prepare("SELECT tt.term_id, tt.term_taxonomy_id FROM $wpdb->terms AS t INNER JOIN $wpdb->term_taxonomy as tt ON tt.term_id = t.term_id WHERE $where AND tt.taxonomy = %s", $where_fields), ARRAY_A) )
1501 return $wpdb->get_row( $wpdb->prepare("SELECT tt.term_id, tt.term_taxonomy_id FROM $wpdb->terms AS t INNER JOIN $wpdb->term_taxonomy as tt ON tt.term_id = t.term_id WHERE $else_where AND tt.taxonomy = %s", $else_where_fields), ARRAY_A);
1504 if ( $result = $wpdb->get_var( $wpdb->prepare("SELECT term_id FROM $wpdb->terms as t WHERE $where", $where_fields) ) )
1507 return $wpdb->get_var( $wpdb->prepare("SELECT term_id FROM $wpdb->terms as t WHERE $else_where", $else_where_fields) );
1511 * Check if a term is an ancestor of another term.
1513 * You can use either an id or the term object for both parameters.
1517 * @param int|object $term1 ID or object to check if this is the parent term.
1518 * @param int|object $term2 The child term.
1519 * @param string $taxonomy Taxonomy name that $term1 and $term2 belong to.
1520 * @return bool Whether $term2 is child of $term1
1522 function term_is_ancestor_of( $term1, $term2, $taxonomy ) {
1523 if ( ! isset( $term1->term_id ) )
1524 $term1 = get_term( $term1, $taxonomy );
1525 if ( ! isset( $term2->parent ) )
1526 $term2 = get_term( $term2, $taxonomy );
1528 if ( empty( $term1->term_id ) || empty( $term2->parent ) )
1530 if ( $term2->parent == $term1->term_id )
1533 return term_is_ancestor_of( $term1, get_term( $term2->parent, $taxonomy ), $taxonomy );
1537 * Sanitize Term all fields.
1539 * Relies on sanitize_term_field() to sanitize the term. The difference is that
1540 * this function will sanitize <strong>all</strong> fields. The context is based
1541 * on sanitize_term_field().
1543 * The $term is expected to be either an array or an object.
1545 * @package WordPress
1546 * @subpackage Taxonomy
1549 * @uses sanitize_term_field Used to sanitize all fields in a term
1551 * @param array|object $term The term to check
1552 * @param string $taxonomy The taxonomy name to use
1553 * @param string $context Default is 'display'.
1554 * @return array|object Term with all fields sanitized
1556 function sanitize_term($term, $taxonomy, $context = 'display') {
1558 if ( 'raw' == $context )
1561 $fields = array('term_id', 'name', 'description', 'slug', 'count', 'parent', 'term_group');
1564 if ( is_object($term) )
1567 $term_id = $do_object ? $term->term_id : (isset($term['term_id']) ? $term['term_id'] : 0);
1569 foreach ( (array) $fields as $field ) {
1571 if ( isset($term->$field) )
1572 $term->$field = sanitize_term_field($field, $term->$field, $term_id, $taxonomy, $context);
1574 if ( isset($term[$field]) )
1575 $term[$field] = sanitize_term_field($field, $term[$field], $term_id, $taxonomy, $context);
1580 $term->filter = $context;
1582 $term['filter'] = $context;
1588 * Cleanse the field value in the term based on the context.
1590 * Passing a term field value through the function should be assumed to have
1591 * cleansed the value for whatever context the term field is going to be used.
1593 * If no context or an unsupported context is given, then default filters will
1596 * There are enough filters for each context to support a custom filtering
1597 * without creating your own filter function. Simply create a function that
1598 * hooks into the filter you need.
1600 * @package WordPress
1601 * @subpackage Taxonomy
1606 * @param string $field Term field to sanitize
1607 * @param string $value Search for this term value
1608 * @param int $term_id Term ID
1609 * @param string $taxonomy Taxonomy Name
1610 * @param string $context Either edit, db, display, attribute, or js.
1611 * @return mixed sanitized field
1613 function sanitize_term_field($field, $value, $term_id, $taxonomy, $context) {
1614 if ( 'parent' == $field || 'term_id' == $field || 'count' == $field || 'term_group' == $field ) {
1615 $value = (int) $value;
1620 if ( 'raw' == $context )
1623 if ( 'edit' == $context ) {
1624 $value = apply_filters("edit_term_{$field}", $value, $term_id, $taxonomy);
1625 $value = apply_filters("edit_{$taxonomy}_{$field}", $value, $term_id);
1626 if ( 'description' == $field )
1627 $value = esc_html($value); // textarea_escaped
1629 $value = esc_attr($value);
1630 } else if ( 'db' == $context ) {
1631 $value = apply_filters("pre_term_{$field}", $value, $taxonomy);
1632 $value = apply_filters("pre_{$taxonomy}_{$field}", $value);
1633 // Back compat filters
1634 if ( 'slug' == $field )
1635 $value = apply_filters('pre_category_nicename', $value);
1637 } else if ( 'rss' == $context ) {
1638 $value = apply_filters("term_{$field}_rss", $value, $taxonomy);
1639 $value = apply_filters("{$taxonomy}_{$field}_rss", $value);
1641 // Use display filters by default.
1642 $value = apply_filters("term_{$field}", $value, $term_id, $taxonomy, $context);
1643 $value = apply_filters("{$taxonomy}_{$field}", $value, $term_id, $context);
1646 if ( 'attribute' == $context )
1647 $value = esc_attr($value);
1648 else if ( 'js' == $context )
1649 $value = esc_js($value);
1655 * Count how many terms are in Taxonomy.
1657 * Default $args is 'hide_empty' which can be 'hide_empty=true' or array('hide_empty' => true).
1659 * @package WordPress
1660 * @subpackage Taxonomy
1664 * @uses wp_parse_args() Turns strings into arrays and merges defaults into an array.
1666 * @param string $taxonomy Taxonomy name
1667 * @param array|string $args Overwrite defaults. See get_terms()
1668 * @return int How many terms are in $taxonomy
1670 function wp_count_terms( $taxonomy, $args = array() ) {
1671 $defaults = array('hide_empty' => false);
1672 $args = wp_parse_args($args, $defaults);
1674 // backwards compatibility
1675 if ( isset($args['ignore_empty']) ) {
1676 $args['hide_empty'] = $args['ignore_empty'];
1677 unset($args['ignore_empty']);
1680 $args['fields'] = 'count';
1682 return get_terms($taxonomy, $args);
1686 * Will unlink the object from the taxonomy or taxonomies.
1688 * Will remove all relationships between the object and any terms in
1689 * a particular taxonomy or taxonomies. Does not remove the term or
1692 * @package WordPress
1693 * @subpackage Taxonomy
1697 * @param int $object_id The term Object Id that refers to the term
1698 * @param string|array $taxonomies List of Taxonomy Names or single Taxonomy name.
1700 function wp_delete_object_term_relationships( $object_id, $taxonomies ) {
1703 $object_id = (int) $object_id;
1705 if ( !is_array($taxonomies) )
1706 $taxonomies = array($taxonomies);
1708 foreach ( (array) $taxonomies as $taxonomy ) {
1709 $tt_ids = wp_get_object_terms($object_id, $taxonomy, array('fields' => 'tt_ids'));
1710 $in_tt_ids = "'" . implode("', '", $tt_ids) . "'";
1711 do_action( 'delete_term_relationships', $object_id, $tt_ids );
1712 $wpdb->query( $wpdb->prepare("DELETE FROM $wpdb->term_relationships WHERE object_id = %d AND term_taxonomy_id IN ($in_tt_ids)", $object_id) );
1713 do_action( 'deleted_term_relationships', $object_id, $tt_ids );
1714 wp_update_term_count($tt_ids, $taxonomy);
1719 * Removes a term from the database.
1721 * If the term is a parent of other terms, then the children will be updated to
1722 * that term's parent.
1724 * The $args 'default' will only override the terms found, if there is only one
1725 * term found. Any other and the found terms are used.
1727 * The $args 'force_default' will force the term supplied as default to be
1728 * assigned even if the object was not going to be termless
1729 * @package WordPress
1730 * @subpackage Taxonomy
1734 * @uses do_action() Calls both 'delete_term' and 'delete_$taxonomy' action
1735 * hooks, passing term object, term id. 'delete_term' gets an additional
1736 * parameter with the $taxonomy parameter.
1738 * @param int $term Term ID
1739 * @param string $taxonomy Taxonomy Name
1740 * @param array|string $args Optional. Change 'default' term id and override found term ids.
1741 * @return bool|WP_Error Returns false if not term; true if completes delete action.
1743 function wp_delete_term( $term, $taxonomy, $args = array() ) {
1746 $term = (int) $term;
1748 if ( ! $ids = term_exists($term, $taxonomy) )
1750 if ( is_wp_error( $ids ) )
1753 $tt_id = $ids['term_taxonomy_id'];
1755 $defaults = array();
1757 if ( 'category' == $taxonomy ) {
1758 $defaults['default'] = get_option( 'default_category' );
1759 if ( $defaults['default'] == $term )
1760 return 0; // Don't delete the default category
1763 $args = wp_parse_args($args, $defaults);
1764 extract($args, EXTR_SKIP);
1766 if ( isset( $default ) ) {
1767 $default = (int) $default;
1768 if ( ! term_exists($default, $taxonomy) )
1772 // Update children to point to new parent
1773 if ( is_taxonomy_hierarchical($taxonomy) ) {
1774 $term_obj = get_term($term, $taxonomy);
1775 if ( is_wp_error( $term_obj ) )
1777 $parent = $term_obj->parent;
1779 $edit_tt_ids = $wpdb->get_col( "SELECT `term_taxonomy_id` FROM $wpdb->term_taxonomy WHERE `parent` = " . (int)$term_obj->term_id );
1780 do_action( 'edit_term_taxonomies', $edit_tt_ids );
1781 $wpdb->update( $wpdb->term_taxonomy, compact( 'parent' ), array( 'parent' => $term_obj->term_id) + compact( 'taxonomy' ) );
1782 do_action( 'edited_term_taxonomies', $edit_tt_ids );
1785 $objects = $wpdb->get_col( $wpdb->prepare( "SELECT object_id FROM $wpdb->term_relationships WHERE term_taxonomy_id = %d", $tt_id ) );
1787 foreach ( (array) $objects as $object ) {
1788 $terms = wp_get_object_terms($object, $taxonomy, array('fields' => 'ids', 'orderby' => 'none'));
1789 if ( 1 == count($terms) && isset($default) ) {
1790 $terms = array($default);
1792 $terms = array_diff($terms, array($term));
1793 if (isset($default) && isset($force_default) && $force_default)
1794 $terms = array_merge($terms, array($default));
1796 $terms = array_map('intval', $terms);
1797 wp_set_object_terms($object, $terms, $taxonomy);
1800 // Clean the relationship caches for all object types using this term
1801 $tax_object = get_taxonomy( $taxonomy );
1802 foreach ( $tax_object->object_type as $object_type )
1803 clean_object_term_cache( $objects, $object_type );
1805 do_action( 'delete_term_taxonomy', $tt_id );
1806 $wpdb->delete( $wpdb->term_taxonomy, array( 'term_taxonomy_id' => $tt_id ) );
1807 do_action( 'deleted_term_taxonomy', $tt_id );
1809 // Delete the term if no taxonomies use it.
1810 if ( !$wpdb->get_var( $wpdb->prepare( "SELECT COUNT(*) FROM $wpdb->term_taxonomy WHERE term_id = %d", $term) ) )
1811 $wpdb->delete( $wpdb->terms, array( 'term_id' => $term ) );
1813 clean_term_cache($term, $taxonomy);
1815 do_action('delete_term', $term, $tt_id, $taxonomy);
1816 do_action("delete_$taxonomy", $term, $tt_id);
1822 * Deletes one existing category.
1825 * @uses wp_delete_term()
1827 * @param int $cat_ID
1828 * @return mixed Returns true if completes delete action; false if term doesn't exist;
1829 * Zero on attempted deletion of default Category; WP_Error object is also a possibility.
1831 function wp_delete_category( $cat_ID ) {
1832 return wp_delete_term( $cat_ID, 'category' );
1836 * Retrieves the terms associated with the given object(s), in the supplied taxonomies.
1838 * The following information has to do the $args parameter and for what can be
1839 * contained in the string or array of that parameter, if it exists.
1841 * The first argument is called, 'orderby' and has the default value of 'name'.
1842 * The other value that is supported is 'count'.
1844 * The second argument is called, 'order' and has the default value of 'ASC'.
1845 * The only other value that will be acceptable is 'DESC'.
1847 * The final argument supported is called, 'fields' and has the default value of
1848 * 'all'. There are multiple other options that can be used instead. Supported
1849 * values are as follows: 'all', 'ids', 'names', and finally
1850 * 'all_with_object_id'.
1852 * The fields argument also decides what will be returned. If 'all' or
1853 * 'all_with_object_id' is chosen or the default kept intact, then all matching
1854 * terms objects will be returned. If either 'ids' or 'names' is used, then an
1855 * array of all matching term ids or term names will be returned respectively.
1857 * @package WordPress
1858 * @subpackage Taxonomy
1862 * @param int|array $object_ids The ID(s) of the object(s) to retrieve.
1863 * @param string|array $taxonomies The taxonomies to retrieve terms from.
1864 * @param array|string $args Change what is returned
1865 * @return array|WP_Error The requested term data or empty array if no terms found. WP_Error if any of the $taxonomies don't exist.
1867 function wp_get_object_terms($object_ids, $taxonomies, $args = array()) {
1870 if ( empty( $object_ids ) || empty( $taxonomies ) )
1873 if ( !is_array($taxonomies) )
1874 $taxonomies = array($taxonomies);
1876 foreach ( (array) $taxonomies as $taxonomy ) {
1877 if ( ! taxonomy_exists($taxonomy) )
1878 return new WP_Error('invalid_taxonomy', __('Invalid taxonomy'));
1881 if ( !is_array($object_ids) )
1882 $object_ids = array($object_ids);
1883 $object_ids = array_map('intval', $object_ids);
1885 $defaults = array('orderby' => 'name', 'order' => 'ASC', 'fields' => 'all');
1886 $args = wp_parse_args( $args, $defaults );
1889 if ( count($taxonomies) > 1 ) {
1890 foreach ( $taxonomies as $index => $taxonomy ) {
1891 $t = get_taxonomy($taxonomy);
1892 if ( isset($t->args) && is_array($t->args) && $args != array_merge($args, $t->args) ) {
1893 unset($taxonomies[$index]);
1894 $terms = array_merge($terms, wp_get_object_terms($object_ids, $taxonomy, array_merge($args, $t->args)));
1898 $t = get_taxonomy($taxonomies[0]);
1899 if ( isset($t->args) && is_array($t->args) )
1900 $args = array_merge($args, $t->args);
1903 extract($args, EXTR_SKIP);
1905 if ( 'count' == $orderby )
1906 $orderby = 'tt.count';
1907 else if ( 'name' == $orderby )
1908 $orderby = 't.name';
1909 else if ( 'slug' == $orderby )
1910 $orderby = 't.slug';
1911 else if ( 'term_group' == $orderby )
1912 $orderby = 't.term_group';
1913 else if ( 'term_order' == $orderby )
1914 $orderby = 'tr.term_order';
1915 else if ( 'none' == $orderby ) {
1919 $orderby = 't.term_id';
1922 // tt_ids queries can only be none or tr.term_taxonomy_id
1923 if ( ('tt_ids' == $fields) && !empty($orderby) )
1924 $orderby = 'tr.term_taxonomy_id';
1926 if ( !empty($orderby) )
1927 $orderby = "ORDER BY $orderby";
1929 $order = strtoupper( $order );
1930 if ( '' !== $order && ! in_array( $order, array( 'ASC', 'DESC' ) ) )
1933 $taxonomies = "'" . implode("', '", $taxonomies) . "'";
1934 $object_ids = implode(', ', $object_ids);
1937 if ( 'all' == $fields )
1938 $select_this = 't.*, tt.*';
1939 else if ( 'ids' == $fields )
1940 $select_this = 't.term_id';
1941 else if ( 'names' == $fields )
1942 $select_this = 't.name';
1943 else if ( 'slugs' == $fields )
1944 $select_this = 't.slug';
1945 else if ( 'all_with_object_id' == $fields )
1946 $select_this = 't.*, tt.*, tr.object_id';
1948 $query = "SELECT $select_this FROM $wpdb->terms AS t INNER JOIN $wpdb->term_taxonomy AS tt ON tt.term_id = t.term_id INNER JOIN $wpdb->term_relationships AS tr ON tr.term_taxonomy_id = tt.term_taxonomy_id WHERE tt.taxonomy IN ($taxonomies) AND tr.object_id IN ($object_ids) $orderby $order";
1950 if ( 'all' == $fields || 'all_with_object_id' == $fields ) {
1951 $terms = array_merge($terms, $wpdb->get_results($query));
1952 update_term_cache($terms);
1953 } else if ( 'ids' == $fields || 'names' == $fields || 'slugs' == $fields ) {
1954 $terms = array_merge($terms, $wpdb->get_col($query));
1955 } else if ( 'tt_ids' == $fields ) {
1956 $terms = $wpdb->get_col("SELECT tr.term_taxonomy_id FROM $wpdb->term_relationships AS tr INNER JOIN $wpdb->term_taxonomy AS tt ON tr.term_taxonomy_id = tt.term_taxonomy_id WHERE tr.object_id IN ($object_ids) AND tt.taxonomy IN ($taxonomies) $orderby $order");
1962 return apply_filters('wp_get_object_terms', $terms, $object_ids, $taxonomies, $args);
1966 * Adds a new term to the database. Optionally marks it as an alias of an existing term.
1968 * Error handling is assigned for the nonexistence of the $taxonomy and $term
1969 * parameters before inserting. If both the term id and taxonomy exist
1970 * previously, then an array will be returned that contains the term id and the
1971 * contents of what is returned. The keys of the array are 'term_id' and
1972 * 'term_taxonomy_id' containing numeric values.
1974 * It is assumed that the term does not yet exist or the above will apply. The
1975 * term will be first added to the term table and then related to the taxonomy
1976 * if everything is well. If everything is correct, then several actions will be
1977 * run prior to a filter and then several actions will be run after the filter
1980 * The arguments decide how the term is handled based on the $args parameter.
1981 * The following is a list of the available overrides and the defaults.
1983 * 'alias_of'. There is no default, but if added, expected is the slug that the
1984 * term will be an alias of. Expected to be a string.
1986 * 'description'. There is no default. If exists, will be added to the database
1987 * along with the term. Expected to be a string.
1989 * 'parent'. Expected to be numeric and default is 0 (zero). Will assign value
1990 * of 'parent' to the term.
1992 * 'slug'. Expected to be a string. There is no default.
1994 * If 'slug' argument exists then the slug will be checked to see if it is not
1995 * a valid term. If that check succeeds (it is not a valid term), then it is
1996 * added and the term id is given. If it fails, then a check is made to whether
1997 * the taxonomy is hierarchical and the parent argument is not empty. If the
1998 * second check succeeds, the term will be inserted and the term id will be
2001 * @package WordPress
2002 * @subpackage Taxonomy
2006 * @uses apply_filters() Calls 'pre_insert_term' hook with term and taxonomy as parameters.
2007 * @uses do_action() Calls 'create_term' hook with the term id and taxonomy id as parameters.
2008 * @uses do_action() Calls 'create_$taxonomy' hook with term id and taxonomy id as parameters.
2009 * @uses apply_filters() Calls 'term_id_filter' hook with term id and taxonomy id as parameters.
2010 * @uses do_action() Calls 'created_term' hook with the term id and taxonomy id as parameters.
2011 * @uses do_action() Calls 'created_$taxonomy' hook with term id and taxonomy id as parameters.
2013 * @param string $term The term to add or update.
2014 * @param string $taxonomy The taxonomy to which to add the term
2015 * @param array|string $args Change the values of the inserted term
2016 * @return array|WP_Error The Term ID and Term Taxonomy ID
2018 function wp_insert_term( $term, $taxonomy, $args = array() ) {
2021 if ( ! taxonomy_exists($taxonomy) )
2022 return new WP_Error('invalid_taxonomy', __('Invalid taxonomy'));
2024 $term = apply_filters( 'pre_insert_term', $term, $taxonomy );
2025 if ( is_wp_error( $term ) )
2028 if ( is_int($term) && 0 == $term )
2029 return new WP_Error('invalid_term_id', __('Invalid term ID'));
2031 if ( '' == trim($term) )
2032 return new WP_Error('empty_term_name', __('A name is required for this term'));
2034 $defaults = array( 'alias_of' => '', 'description' => '', 'parent' => 0, 'slug' => '');
2035 $args = wp_parse_args($args, $defaults);
2036 $args['name'] = $term;
2037 $args['taxonomy'] = $taxonomy;
2038 $args = sanitize_term($args, $taxonomy, 'db');
2039 extract($args, EXTR_SKIP);
2041 // expected_slashed ($name)
2042 $name = stripslashes($name);
2043 $description = stripslashes($description);
2046 $slug = sanitize_title($name);
2050 $alias = $wpdb->get_row( $wpdb->prepare( "SELECT term_id, term_group FROM $wpdb->terms WHERE slug = %s", $alias_of) );
2051 if ( $alias->term_group ) {
2052 // The alias we want is already in a group, so let's use that one.
2053 $term_group = $alias->term_group;
2055 // The alias isn't in a group, so let's create a new one and firstly add the alias term to it.
2056 $term_group = $wpdb->get_var("SELECT MAX(term_group) FROM $wpdb->terms") + 1;
2057 do_action( 'edit_terms', $alias->term_id );
2058 $wpdb->update($wpdb->terms, compact('term_group'), array('term_id' => $alias->term_id) );
2059 do_action( 'edited_terms', $alias->term_id );
2063 if ( $term_id = term_exists($slug) ) {
2064 $existing_term = $wpdb->get_row( $wpdb->prepare( "SELECT name FROM $wpdb->terms WHERE term_id = %d", $term_id), ARRAY_A );
2065 // We've got an existing term in the same taxonomy, which matches the name of the new term:
2066 if ( is_taxonomy_hierarchical($taxonomy) && $existing_term['name'] == $name && $exists = term_exists( (int) $term_id, $taxonomy ) ) {
2067 // Hierarchical, and it matches an existing term, Do not allow same "name" in the same level.
2068 $siblings = get_terms($taxonomy, array('fields' => 'names', 'get' => 'all', 'parent' => (int)$parent) );
2069 if ( in_array($name, $siblings) ) {
2070 return new WP_Error('term_exists', __('A term with the name provided already exists with this parent.'), $exists['term_id']);
2072 $slug = wp_unique_term_slug($slug, (object) $args);
2073 if ( false === $wpdb->insert( $wpdb->terms, compact( 'name', 'slug', 'term_group' ) ) )
2074 return new WP_Error('db_insert_error', __('Could not insert term into the database'), $wpdb->last_error);
2075 $term_id = (int) $wpdb->insert_id;
2077 } elseif ( $existing_term['name'] != $name ) {
2078 // We've got an existing term, with a different name, Create the new term.
2079 $slug = wp_unique_term_slug($slug, (object) $args);
2080 if ( false === $wpdb->insert( $wpdb->terms, compact( 'name', 'slug', 'term_group' ) ) )
2081 return new WP_Error('db_insert_error', __('Could not insert term into the database'), $wpdb->last_error);
2082 $term_id = (int) $wpdb->insert_id;
2083 } elseif ( $exists = term_exists( (int) $term_id, $taxonomy ) ) {
2084 // Same name, same slug.
2085 return new WP_Error('term_exists', __('A term with the name provided already exists.'), $exists['term_id']);
2088 // This term does not exist at all in the database, Create it.
2089 $slug = wp_unique_term_slug($slug, (object) $args);
2090 if ( false === $wpdb->insert( $wpdb->terms, compact( 'name', 'slug', 'term_group' ) ) )
2091 return new WP_Error('db_insert_error', __('Could not insert term into the database'), $wpdb->last_error);
2092 $term_id = (int) $wpdb->insert_id;
2095 // Seems unreachable, However, Is used in the case that a term name is provided, which sanitizes to an empty string.
2096 if ( empty($slug) ) {
2097 $slug = sanitize_title($slug, $term_id);
2098 do_action( 'edit_terms', $term_id );
2099 $wpdb->update( $wpdb->terms, compact( 'slug' ), compact( 'term_id' ) );
2100 do_action( 'edited_terms', $term_id );
2103 $tt_id = $wpdb->get_var( $wpdb->prepare( "SELECT tt.term_taxonomy_id FROM $wpdb->term_taxonomy AS tt INNER JOIN $wpdb->terms AS t ON tt.term_id = t.term_id WHERE tt.taxonomy = %s AND t.term_id = %d", $taxonomy, $term_id ) );
2105 if ( !empty($tt_id) )
2106 return array('term_id' => $term_id, 'term_taxonomy_id' => $tt_id);
2108 $wpdb->insert( $wpdb->term_taxonomy, compact( 'term_id', 'taxonomy', 'description', 'parent') + array( 'count' => 0 ) );
2109 $tt_id = (int) $wpdb->insert_id;
2111 do_action("create_term", $term_id, $tt_id, $taxonomy);
2112 do_action("create_$taxonomy", $term_id, $tt_id);
2114 $term_id = apply_filters('term_id_filter', $term_id, $tt_id);
2116 clean_term_cache($term_id, $taxonomy);
2118 do_action("created_term", $term_id, $tt_id, $taxonomy);
2119 do_action("created_$taxonomy", $term_id, $tt_id);
2121 return array('term_id' => $term_id, 'term_taxonomy_id' => $tt_id);
2125 * Create Term and Taxonomy Relationships.
2127 * Relates an object (post, link etc) to a term and taxonomy type. Creates the
2128 * term and taxonomy relationship if it doesn't already exist. Creates a term if
2129 * it doesn't exist (using the slug).
2131 * A relationship means that the term is grouped in or belongs to the taxonomy.
2132 * A term has no meaning until it is given context by defining which taxonomy it
2135 * @package WordPress
2136 * @subpackage Taxonomy
2140 * @param int $object_id The object to relate to.
2141 * @param array|int|string $terms The slug or id of the term, will replace all existing
2142 * related terms in this taxonomy.
2143 * @param array|string $taxonomy The context in which to relate the term to the object.
2144 * @param bool $append If false will delete difference of terms.
2145 * @return array|WP_Error Affected Term IDs
2147 function wp_set_object_terms($object_id, $terms, $taxonomy, $append = false) {
2150 $object_id = (int) $object_id;
2152 if ( ! taxonomy_exists($taxonomy) )
2153 return new WP_Error('invalid_taxonomy', __('Invalid taxonomy'));
2155 if ( !is_array($terms) )
2156 $terms = array($terms);
2159 $old_tt_ids = wp_get_object_terms($object_id, $taxonomy, array('fields' => 'tt_ids', 'orderby' => 'none'));
2161 $old_tt_ids = array();
2164 $term_ids = array();
2165 $new_tt_ids = array();
2167 foreach ( (array) $terms as $term) {
2168 if ( !strlen(trim($term)) )
2171 if ( !$term_info = term_exists($term, $taxonomy) ) {
2172 // Skip if a non-existent term ID is passed.
2173 if ( is_int($term) )
2175 $term_info = wp_insert_term($term, $taxonomy);
2177 if ( is_wp_error($term_info) )
2179 $term_ids[] = $term_info['term_id'];
2180 $tt_id = $term_info['term_taxonomy_id'];
2183 if ( $wpdb->get_var( $wpdb->prepare( "SELECT term_taxonomy_id FROM $wpdb->term_relationships WHERE object_id = %d AND term_taxonomy_id = %d", $object_id, $tt_id ) ) )
2185 do_action( 'add_term_relationship', $object_id, $tt_id );
2186 $wpdb->insert( $wpdb->term_relationships, array( 'object_id' => $object_id, 'term_taxonomy_id' => $tt_id ) );
2187 do_action( 'added_term_relationship', $object_id, $tt_id );
2188 $new_tt_ids[] = $tt_id;
2192 wp_update_term_count( $new_tt_ids, $taxonomy );
2195 $delete_terms = array_diff($old_tt_ids, $tt_ids);
2196 if ( $delete_terms ) {
2197 $in_delete_terms = "'" . implode("', '", $delete_terms) . "'";
2198 do_action( 'delete_term_relationships', $object_id, $delete_terms );
2199 $wpdb->query( $wpdb->prepare("DELETE FROM $wpdb->term_relationships WHERE object_id = %d AND term_taxonomy_id IN ($in_delete_terms)", $object_id) );
2200 do_action( 'deleted_term_relationships', $object_id, $delete_terms );
2201 wp_update_term_count($delete_terms, $taxonomy);
2205 $t = get_taxonomy($taxonomy);
2206 if ( ! $append && isset($t->sort) && $t->sort ) {
2209 $final_tt_ids = wp_get_object_terms($object_id, $taxonomy, array('fields' => 'tt_ids'));
2210 foreach ( $tt_ids as $tt_id )
2211 if ( in_array($tt_id, $final_tt_ids) )
2212 $values[] = $wpdb->prepare( "(%d, %d, %d)", $object_id, $tt_id, ++$term_order);
2214 $wpdb->query("INSERT INTO $wpdb->term_relationships (object_id, term_taxonomy_id, term_order) VALUES " . join(',', $values) . " ON DUPLICATE KEY UPDATE term_order = VALUES(term_order)");
2217 do_action('set_object_terms', $object_id, $terms, $tt_ids, $taxonomy, $append, $old_tt_ids);
2222 * Will make slug unique, if it isn't already.
2224 * The $slug has to be unique global to every taxonomy, meaning that one
2225 * taxonomy term can't have a matching slug with another taxonomy term. Each
2226 * slug has to be globally unique for every taxonomy.
2228 * The way this works is that if the taxonomy that the term belongs to is
2229 * hierarchical and has a parent, it will append that parent to the $slug.
2231 * If that still doesn't return an unique slug, then it try to append a number
2232 * until it finds a number that is truly unique.
2234 * The only purpose for $term is for appending a parent, if one exists.
2236 * @package WordPress
2237 * @subpackage Taxonomy
2241 * @param string $slug The string that will be tried for a unique slug
2242 * @param object $term The term object that the $slug will belong too
2243 * @return string Will return a true unique slug.
2245 function wp_unique_term_slug($slug, $term) {
2248 if ( ! term_exists( $slug ) )
2251 // If the taxonomy supports hierarchy and the term has a parent, make the slug unique
2252 // by incorporating parent slugs.
2253 if ( is_taxonomy_hierarchical($term->taxonomy) && !empty($term->parent) ) {
2254 $the_parent = $term->parent;
2255 while ( ! empty($the_parent) ) {
2256 $parent_term = get_term($the_parent, $term->taxonomy);
2257 if ( is_wp_error($parent_term) || empty($parent_term) )
2259 $slug .= '-' . $parent_term->slug;
2260 if ( ! term_exists( $slug ) )
2263 if ( empty($parent_term->parent) )
2265 $the_parent = $parent_term->parent;
2269 // If we didn't get a unique slug, try appending a number to make it unique.
2270 if ( !empty($args['term_id']) )
2271 $query = $wpdb->prepare( "SELECT slug FROM $wpdb->terms WHERE slug = %s AND term_id != %d", $slug, $args['term_id'] );
2273 $query = $wpdb->prepare( "SELECT slug FROM $wpdb->terms WHERE slug = %s", $slug );
2275 if ( $wpdb->get_var( $query ) ) {
2278 $alt_slug = $slug . "-$num";
2280 $slug_check = $wpdb->get_var( $wpdb->prepare( "SELECT slug FROM $wpdb->terms WHERE slug = %s", $alt_slug ) );
2281 } while ( $slug_check );
2289 * Update term based on arguments provided.
2291 * The $args will indiscriminately override all values with the same field name.
2292 * Care must be taken to not override important information need to update or
2293 * update will fail (or perhaps create a new term, neither would be acceptable).
2295 * Defaults will set 'alias_of', 'description', 'parent', and 'slug' if not
2296 * defined in $args already.
2298 * 'alias_of' will create a term group, if it doesn't already exist, and update
2301 * If the 'slug' argument in $args is missing, then the 'name' in $args will be
2302 * used. It should also be noted that if you set 'slug' and it isn't unique then
2303 * a WP_Error will be passed back. If you don't pass any slug, then a unique one
2304 * will be created for you.
2306 * For what can be overrode in $args, check the term scheme can contain and stay
2307 * away from the term keys.
2309 * @package WordPress
2310 * @subpackage Taxonomy
2314 * @uses do_action() Will call both 'edit_term' and 'edit_$taxonomy' twice.
2315 * @uses apply_filters() Will call the 'term_id_filter' filter and pass the term
2316 * id and taxonomy id.
2318 * @param int $term_id The ID of the term
2319 * @param string $taxonomy The context in which to relate the term to the object.
2320 * @param array|string $args Overwrite term field values
2321 * @return array|WP_Error Returns Term ID and Taxonomy Term ID
2323 function wp_update_term( $term_id, $taxonomy, $args = array() ) {
2326 if ( ! taxonomy_exists($taxonomy) )
2327 return new WP_Error('invalid_taxonomy', __('Invalid taxonomy'));
2329 $term_id = (int) $term_id;
2331 // First, get all of the original args
2332 $term = get_term ($term_id, $taxonomy, ARRAY_A);
2334 if ( is_wp_error( $term ) )
2337 // Escape data pulled from DB.
2338 $term = add_magic_quotes($term);
2340 // Merge old and new args with new args overwriting old ones.
2341 $args = array_merge($term, $args);
2343 $defaults = array( 'alias_of' => '', 'description' => '', 'parent' => 0, 'slug' => '');
2344 $args = wp_parse_args($args, $defaults);
2345 $args = sanitize_term($args, $taxonomy, 'db');
2346 extract($args, EXTR_SKIP);
2348 // expected_slashed ($name)
2349 $name = stripslashes($name);
2350 $description = stripslashes($description);
2352 if ( '' == trim($name) )
2353 return new WP_Error('empty_term_name', __('A name is required for this term'));
2355 $empty_slug = false;
2356 if ( empty($slug) ) {
2358 $slug = sanitize_title($name);
2362 $alias = $wpdb->get_row( $wpdb->prepare( "SELECT term_id, term_group FROM $wpdb->terms WHERE slug = %s", $alias_of) );
2363 if ( $alias->term_group ) {
2364 // The alias we want is already in a group, so let's use that one.
2365 $term_group = $alias->term_group;
2367 // The alias isn't in a group, so let's create a new one and firstly add the alias term to it.
2368 $term_group = $wpdb->get_var("SELECT MAX(term_group) FROM $wpdb->terms") + 1;
2369 do_action( 'edit_terms', $alias->term_id );
2370 $wpdb->update( $wpdb->terms, compact('term_group'), array( 'term_id' => $alias->term_id ) );
2371 do_action( 'edited_terms', $alias->term_id );
2375 // Check $parent to see if it will cause a hierarchy loop
2376 $parent = apply_filters( 'wp_update_term_parent', $parent, $term_id, $taxonomy, compact( array_keys( $args ) ), $args );
2378 // Check for duplicate slug
2379 $id = $wpdb->get_var( $wpdb->prepare( "SELECT term_id FROM $wpdb->terms WHERE slug = %s", $slug ) );
2380 if ( $id && ($id != $term_id) ) {
2381 // If an empty slug was passed or the parent changed, reset the slug to something unique.
2383 if ( $empty_slug || ( $parent != $term['parent']) )
2384 $slug = wp_unique_term_slug($slug, (object) $args);
2386 return new WP_Error('duplicate_term_slug', sprintf(__('The slug “%s” is already in use by another term'), $slug));
2388 do_action( 'edit_terms', $term_id );
2389 $wpdb->update($wpdb->terms, compact( 'name', 'slug', 'term_group' ), compact( 'term_id' ) );
2390 if ( empty($slug) ) {
2391 $slug = sanitize_title($name, $term_id);
2392 $wpdb->update( $wpdb->terms, compact( 'slug' ), compact( 'term_id' ) );
2394 do_action( 'edited_terms', $term_id );
2396 $tt_id = $wpdb->get_var( $wpdb->prepare( "SELECT tt.term_taxonomy_id FROM $wpdb->term_taxonomy AS tt INNER JOIN $wpdb->terms AS t ON tt.term_id = t.term_id WHERE tt.taxonomy = %s AND t.term_id = %d", $taxonomy, $term_id) );
2397 do_action( 'edit_term_taxonomy', $tt_id, $taxonomy );
2398 $wpdb->update( $wpdb->term_taxonomy, compact( 'term_id', 'taxonomy', 'description', 'parent' ), array( 'term_taxonomy_id' => $tt_id ) );
2399 do_action( 'edited_term_taxonomy', $tt_id, $taxonomy );
2401 do_action("edit_term", $term_id, $tt_id, $taxonomy);
2402 do_action("edit_$taxonomy", $term_id, $tt_id);
2404 $term_id = apply_filters('term_id_filter', $term_id, $tt_id);
2406 clean_term_cache($term_id, $taxonomy);
2408 do_action("edited_term", $term_id, $tt_id, $taxonomy);
2409 do_action("edited_$taxonomy", $term_id, $tt_id);
2411 return array('term_id' => $term_id, 'term_taxonomy_id' => $tt_id);
2415 * Enable or disable term counting.
2419 * @param bool $defer Optional. Enable if true, disable if false.
2420 * @return bool Whether term counting is enabled or disabled.
2422 function wp_defer_term_counting($defer=null) {
2423 static $_defer = false;
2425 if ( is_bool($defer) ) {
2427 // flush any deferred counts
2429 wp_update_term_count( null, null, true );
2436 * Updates the amount of terms in taxonomy.
2438 * If there is a taxonomy callback applied, then it will be called for updating
2441 * The default action is to count what the amount of terms have the relationship
2442 * of term ID. Once that is done, then update the database.
2444 * @package WordPress
2445 * @subpackage Taxonomy
2449 * @param int|array $terms The term_taxonomy_id of the terms
2450 * @param string $taxonomy The context of the term.
2451 * @return bool If no terms will return false, and if successful will return true.
2453 function wp_update_term_count( $terms, $taxonomy, $do_deferred=false ) {
2454 static $_deferred = array();
2456 if ( $do_deferred ) {
2457 foreach ( (array) array_keys($_deferred) as $tax ) {
2458 wp_update_term_count_now( $_deferred[$tax], $tax );
2459 unset( $_deferred[$tax] );
2463 if ( empty($terms) )
2466 if ( !is_array($terms) )
2467 $terms = array($terms);
2469 if ( wp_defer_term_counting() ) {
2470 if ( !isset($_deferred[$taxonomy]) )
2471 $_deferred[$taxonomy] = array();
2472 $_deferred[$taxonomy] = array_unique( array_merge($_deferred[$taxonomy], $terms) );
2476 return wp_update_term_count_now( $terms, $taxonomy );
2480 * Perform term count update immediately.
2484 * @param array $terms The term_taxonomy_id of terms to update.
2485 * @param string $taxonomy The context of the term.
2486 * @return bool Always true when complete.
2488 function wp_update_term_count_now( $terms, $taxonomy ) {
2491 $terms = array_map('intval', $terms);
2493 $taxonomy = get_taxonomy($taxonomy);
2494 if ( !empty($taxonomy->update_count_callback) ) {
2495 call_user_func($taxonomy->update_count_callback, $terms, $taxonomy);
2497 $object_types = (array) $taxonomy->object_type;
2498 foreach ( $object_types as &$object_type ) {
2499 if ( 0 === strpos( $object_type, 'attachment:' ) )
2500 list( $object_type ) = explode( ':', $object_type );
2503 if ( $object_types == array_filter( $object_types, 'post_type_exists' ) ) {
2504 // Only post types are attached to this taxonomy
2505 _update_post_term_count( $terms, $taxonomy );
2507 // Default count updater
2508 _update_generic_term_count( $terms, $taxonomy );
2512 clean_term_cache($terms, '', false);
2522 * Removes the taxonomy relationship to terms from the cache.
2524 * Will remove the entire taxonomy relationship containing term $object_id. The
2525 * term IDs have to exist within the taxonomy $object_type for the deletion to
2528 * @package WordPress
2529 * @subpackage Taxonomy
2532 * @see get_object_taxonomies() for more on $object_type
2533 * @uses do_action() Will call action hook named, 'clean_object_term_cache' after completion.
2534 * Passes, function params in same order.
2536 * @param int|array $object_ids Single or list of term object ID(s)
2537 * @param array|string $object_type The taxonomy object type
2539 function clean_object_term_cache($object_ids, $object_type) {
2540 if ( !is_array($object_ids) )
2541 $object_ids = array($object_ids);
2543 foreach ( $object_ids as $id )
2544 foreach ( get_object_taxonomies($object_type) as $taxonomy )
2545 wp_cache_delete($id, "{$taxonomy}_relationships");
2547 do_action('clean_object_term_cache', $object_ids, $object_type);
2551 * Will remove all of the term ids from the cache.
2553 * @package WordPress
2554 * @subpackage Taxonomy
2558 * @param int|array $ids Single or list of Term IDs
2559 * @param string $taxonomy Can be empty and will assume tt_ids, else will use for context.
2560 * @param bool $clean_taxonomy Whether to clean taxonomy wide caches (true), or just individual term object caches (false). Default is true.
2562 function clean_term_cache($ids, $taxonomy = '', $clean_taxonomy = true) {
2564 static $cleaned = array();
2566 if ( !is_array($ids) )
2569 $taxonomies = array();
2570 // If no taxonomy, assume tt_ids.
2571 if ( empty($taxonomy) ) {
2572 $tt_ids = array_map('intval', $ids);
2573 $tt_ids = implode(', ', $tt_ids);
2574 $terms = $wpdb->get_results("SELECT term_id, taxonomy FROM $wpdb->term_taxonomy WHERE term_taxonomy_id IN ($tt_ids)");
2576 foreach ( (array) $terms as $term ) {
2577 $taxonomies[] = $term->taxonomy;
2578 $ids[] = $term->term_id;
2579 wp_cache_delete($term->term_id, $term->taxonomy);
2581 $taxonomies = array_unique($taxonomies);
2583 $taxonomies = array($taxonomy);
2584 foreach ( $taxonomies as $taxonomy ) {
2585 foreach ( $ids as $id ) {
2586 wp_cache_delete($id, $taxonomy);
2591 foreach ( $taxonomies as $taxonomy ) {
2592 if ( isset($cleaned[$taxonomy]) )
2594 $cleaned[$taxonomy] = true;
2596 if ( $clean_taxonomy ) {
2597 wp_cache_delete('all_ids', $taxonomy);
2598 wp_cache_delete('get', $taxonomy);
2599 delete_option("{$taxonomy}_children");
2600 // Regenerate {$taxonomy}_children
2601 _get_term_hierarchy($taxonomy);
2604 do_action('clean_term_cache', $ids, $taxonomy);
2607 wp_cache_set('last_changed', time(), 'terms');
2611 * Retrieves the taxonomy relationship to the term object id.
2613 * @package WordPress
2614 * @subpackage Taxonomy
2617 * @uses wp_cache_get() Retrieves taxonomy relationship from cache
2619 * @param int|array $id Term object ID
2620 * @param string $taxonomy Taxonomy Name
2621 * @return bool|array Empty array if $terms found, but not $taxonomy. False if nothing is in cache for $taxonomy and $id.
2623 function &get_object_term_cache($id, $taxonomy) {
2624 $cache = wp_cache_get($id, "{$taxonomy}_relationships");
2629 * Updates the cache for Term ID(s).
2631 * Will only update the cache for terms not already cached.
2633 * The $object_ids expects that the ids be separated by commas, if it is a
2636 * It should be noted that update_object_term_cache() is very time extensive. It
2637 * is advised that the function is not called very often or at least not for a
2638 * lot of terms that exist in a lot of taxonomies. The amount of time increases
2639 * for each term and it also increases for each taxonomy the term belongs to.
2641 * @package WordPress
2642 * @subpackage Taxonomy
2644 * @uses wp_get_object_terms() Used to get terms from the database to update
2646 * @param string|array $object_ids Single or list of term object ID(s)
2647 * @param array|string $object_type The taxonomy object type
2648 * @return null|bool Null value is given with empty $object_ids. False if
2650 function update_object_term_cache($object_ids, $object_type) {
2651 if ( empty($object_ids) )
2654 if ( !is_array($object_ids) )
2655 $object_ids = explode(',', $object_ids);
2657 $object_ids = array_map('intval', $object_ids);
2659 $taxonomies = get_object_taxonomies($object_type);
2662 foreach ( (array) $object_ids as $id ) {
2663 foreach ( $taxonomies as $taxonomy ) {
2664 if ( false === wp_cache_get($id, "{$taxonomy}_relationships") ) {
2671 if ( empty( $ids ) )
2674 $terms = wp_get_object_terms($ids, $taxonomies, array('fields' => 'all_with_object_id'));
2676 $object_terms = array();
2677 foreach ( (array) $terms as $term )
2678 $object_terms[$term->object_id][$term->taxonomy][$term->term_id] = $term;
2680 foreach ( $ids as $id ) {
2681 foreach ( $taxonomies as $taxonomy ) {
2682 if ( ! isset($object_terms[$id][$taxonomy]) ) {
2683 if ( !isset($object_terms[$id]) )
2684 $object_terms[$id] = array();
2685 $object_terms[$id][$taxonomy] = array();
2690 foreach ( $object_terms as $id => $value ) {
2691 foreach ( $value as $taxonomy => $terms ) {
2692 wp_cache_add( $id, $terms, "{$taxonomy}_relationships" );
2698 * Updates Terms to Taxonomy in cache.
2700 * @package WordPress
2701 * @subpackage Taxonomy
2704 * @param array $terms List of Term objects to change
2705 * @param string $taxonomy Optional. Update Term to this taxonomy in cache
2707 function update_term_cache($terms, $taxonomy = '') {
2708 foreach ( (array) $terms as $term ) {
2709 $term_taxonomy = $taxonomy;
2710 if ( empty($term_taxonomy) )
2711 $term_taxonomy = $term->taxonomy;
2713 wp_cache_add($term->term_id, $term, $term_taxonomy);
2722 * Retrieves children of taxonomy as Term IDs.
2724 * @package WordPress
2725 * @subpackage Taxonomy
2729 * @uses update_option() Stores all of the children in "$taxonomy_children"
2730 * option. That is the name of the taxonomy, immediately followed by '_children'.
2732 * @param string $taxonomy Taxonomy Name
2733 * @return array Empty if $taxonomy isn't hierarchical or returns children as Term IDs.
2735 function _get_term_hierarchy($taxonomy) {
2736 if ( !is_taxonomy_hierarchical($taxonomy) )
2738 $children = get_option("{$taxonomy}_children");
2740 if ( is_array($children) )
2742 $children = array();
2743 $terms = get_terms($taxonomy, array('get' => 'all', 'orderby' => 'id', 'fields' => 'id=>parent'));
2744 foreach ( $terms as $term_id => $parent ) {
2746 $children[$parent][] = $term_id;
2748 update_option("{$taxonomy}_children", $children);
2754 * Get the subset of $terms that are descendants of $term_id.
2756 * If $terms is an array of objects, then _get_term_children returns an array of objects.
2757 * If $terms is an array of IDs, then _get_term_children returns an array of IDs.
2759 * @package WordPress
2760 * @subpackage Taxonomy
2764 * @param int $term_id The ancestor term: all returned terms should be descendants of $term_id.
2765 * @param array $terms The set of terms---either an array of term objects or term IDs---from which those that are descendants of $term_id will be chosen.
2766 * @param string $taxonomy The taxonomy which determines the hierarchy of the terms.
2767 * @return array The subset of $terms that are descendants of $term_id.
2769 function &_get_term_children($term_id, $terms, $taxonomy) {
2770 $empty_array = array();
2771 if ( empty($terms) )
2772 return $empty_array;
2774 $term_list = array();
2775 $has_children = _get_term_hierarchy($taxonomy);
2777 if ( ( 0 != $term_id ) && ! isset($has_children[$term_id]) )
2778 return $empty_array;
2780 foreach ( (array) $terms as $term ) {
2782 if ( !is_object($term) ) {
2783 $term = get_term($term, $taxonomy);
2784 if ( is_wp_error( $term ) )
2789 if ( $term->term_id == $term_id )
2792 if ( $term->parent == $term_id ) {
2794 $term_list[] = $term->term_id;
2796 $term_list[] = $term;
2798 if ( !isset($has_children[$term->term_id]) )
2801 if ( $children = _get_term_children($term->term_id, $terms, $taxonomy) )
2802 $term_list = array_merge($term_list, $children);
2810 * Add count of children to parent count.
2812 * Recalculates term counts by including items from child terms. Assumes all
2813 * relevant children are already in the $terms argument.
2815 * @package WordPress
2816 * @subpackage Taxonomy
2821 * @param array $terms List of Term IDs
2822 * @param string $taxonomy Term Context
2823 * @return null Will break from function if conditions are not met.
2825 function _pad_term_counts(&$terms, $taxonomy) {
2828 // This function only works for hierarchical taxonomies like post categories.
2829 if ( !is_taxonomy_hierarchical( $taxonomy ) )
2832 $term_hier = _get_term_hierarchy($taxonomy);
2834 if ( empty($term_hier) )
2837 $term_items = array();
2839 foreach ( (array) $terms as $key => $term ) {
2840 $terms_by_id[$term->term_id] = & $terms[$key];
2841 $term_ids[$term->term_taxonomy_id] = $term->term_id;
2844 // Get the object and term ids and stick them in a lookup table
2845 $tax_obj = get_taxonomy($taxonomy);
2846 $object_types = esc_sql($tax_obj->object_type);
2847 $results = $wpdb->get_results("SELECT object_id, term_taxonomy_id FROM $wpdb->term_relationships INNER JOIN $wpdb->posts ON object_id = ID WHERE term_taxonomy_id IN (" . implode(',', array_keys($term_ids)) . ") AND post_type IN ('" . implode("', '", $object_types) . "') AND post_status = 'publish'");
2848 foreach ( $results as $row ) {
2849 $id = $term_ids[$row->term_taxonomy_id];
2850 $term_items[$id][$row->object_id] = isset($term_items[$id][$row->object_id]) ? ++$term_items[$id][$row->object_id] : 1;
2853 // Touch every ancestor's lookup row for each post in each term
2854 foreach ( $term_ids as $term_id ) {
2856 while ( !empty( $terms_by_id[$child] ) && $parent = $terms_by_id[$child]->parent ) {
2857 if ( !empty( $term_items[$term_id] ) )
2858 foreach ( $term_items[$term_id] as $item_id => $touches ) {
2859 $term_items[$parent][$item_id] = isset($term_items[$parent][$item_id]) ? ++$term_items[$parent][$item_id]: 1;
2865 // Transfer the touched cells
2866 foreach ( (array) $term_items as $id => $items )
2867 if ( isset($terms_by_id[$id]) )
2868 $terms_by_id[$id]->count = count($items);
2872 // Default callbacks
2876 * Will update term count based on object types of the current taxonomy.
2878 * Private function for the default callback for post_tag and category
2881 * @package WordPress
2882 * @subpackage Taxonomy
2887 * @param array $terms List of Term taxonomy IDs
2888 * @param object $taxonomy Current taxonomy object of terms
2890 function _update_post_term_count( $terms, $taxonomy ) {
2893 $object_types = (array) $taxonomy->object_type;
2895 foreach ( $object_types as &$object_type )
2896 list( $object_type ) = explode( ':', $object_type );
2898 $object_types = array_unique( $object_types );
2900 if ( false !== ( $check_attachments = array_search( 'attachment', $object_types ) ) ) {
2901 unset( $object_types[ $check_attachments ] );
2902 $check_attachments = true;
2905 if ( $object_types )
2906 $object_types = esc_sql( array_filter( $object_types, 'post_type_exists' ) );
2908 foreach ( (array) $terms as $term ) {
2911 // Attachments can be 'inherit' status, we need to base count off the parent's status if so
2912 if ( $check_attachments )
2913 $count += (int) $wpdb->get_var( $wpdb->prepare( "SELECT COUNT(*) FROM $wpdb->term_relationships, $wpdb->posts p1 WHERE p1.ID = $wpdb->term_relationships.object_id AND ( post_status = 'publish' OR ( post_status = 'inherit' AND post_parent > 0 AND ( SELECT post_status FROM $wpdb->posts WHERE ID = p1.post_parent ) = 'publish' ) ) AND post_type = 'attachment' AND term_taxonomy_id = %d", $term ) );
2915 if ( $object_types )
2916 $count += (int) $wpdb->get_var( $wpdb->prepare( "SELECT COUNT(*) FROM $wpdb->term_relationships, $wpdb->posts WHERE $wpdb->posts.ID = $wpdb->term_relationships.object_id AND post_status = 'publish' AND post_type IN ('" . implode("', '", $object_types ) . "') AND term_taxonomy_id = %d", $term ) );
2918 do_action( 'edit_term_taxonomy', $term, $taxonomy );
2919 $wpdb->update( $wpdb->term_taxonomy, compact( 'count' ), array( 'term_taxonomy_id' => $term ) );
2920 do_action( 'edited_term_taxonomy', $term, $taxonomy );
2925 * Will update term count based on number of objects.
2927 * Default callback for the link_category taxonomy.
2929 * @package WordPress
2930 * @subpackage Taxonomy
2934 * @param array $terms List of Term taxonomy IDs
2935 * @param object $taxonomy Current taxonomy object of terms
2937 function _update_generic_term_count( $terms, $taxonomy ) {
2940 foreach ( (array) $terms as $term ) {
2941 $count = $wpdb->get_var( $wpdb->prepare( "SELECT COUNT(*) FROM $wpdb->term_relationships WHERE term_taxonomy_id = %d", $term ) );
2943 do_action( 'edit_term_taxonomy', $term, $taxonomy );
2944 $wpdb->update( $wpdb->term_taxonomy, compact( 'count' ), array( 'term_taxonomy_id' => $term ) );
2945 do_action( 'edited_term_taxonomy', $term, $taxonomy );
2950 * Generates a permalink for a taxonomy term archive.
2954 * @uses apply_filters() Calls 'term_link' with term link and term object, and taxonomy parameters.
2955 * @uses apply_filters() For the post_tag Taxonomy, Calls 'tag_link' with tag link and tag ID as parameters.
2956 * @uses apply_filters() For the category Taxonomy, Calls 'category_link' filter on category link and category ID.
2958 * @param object|int|string $term
2959 * @param string $taxonomy (optional if $term is object)
2960 * @return string|WP_Error HTML link to taxonomy term archive on success, WP_Error if term does not exist.
2962 function get_term_link( $term, $taxonomy = '') {
2965 if ( !is_object($term) ) {
2966 if ( is_int($term) ) {
2967 $term = &get_term($term, $taxonomy);
2969 $term = &get_term_by('slug', $term, $taxonomy);
2973 if ( !is_object($term) )
2974 $term = new WP_Error('invalid_term', __('Empty Term'));
2976 if ( is_wp_error( $term ) )
2979 $taxonomy = $term->taxonomy;
2981 $termlink = $wp_rewrite->get_extra_permastruct($taxonomy);
2983 $slug = $term->slug;
2984 $t = get_taxonomy($taxonomy);
2986 if ( empty($termlink) ) {
2987 if ( 'category' == $taxonomy )
2988 $termlink = '?cat=' . $term->term_id;
2989 elseif ( $t->query_var )
2990 $termlink = "?$t->query_var=$slug";
2992 $termlink = "?taxonomy=$taxonomy&term=$slug";
2993 $termlink = home_url($termlink);
2995 if ( $t->rewrite['hierarchical'] ) {
2996 $hierarchical_slugs = array();
2997 $ancestors = get_ancestors($term->term_id, $taxonomy);
2998 foreach ( (array)$ancestors as $ancestor ) {
2999 $ancestor_term = get_term($ancestor, $taxonomy);
3000 $hierarchical_slugs[] = $ancestor_term->slug;
3002 $hierarchical_slugs = array_reverse($hierarchical_slugs);
3003 $hierarchical_slugs[] = $slug;
3004 $termlink = str_replace("%$taxonomy%", implode('/', $hierarchical_slugs), $termlink);
3006 $termlink = str_replace("%$taxonomy%", $slug, $termlink);
3008 $termlink = home_url( user_trailingslashit($termlink, 'category') );
3010 // Back Compat filters.
3011 if ( 'post_tag' == $taxonomy )
3012 $termlink = apply_filters( 'tag_link', $termlink, $term->term_id );
3013 elseif ( 'category' == $taxonomy )
3014 $termlink = apply_filters( 'category_link', $termlink, $term->term_id );
3016 return apply_filters('term_link', $termlink, $term, $taxonomy);
3020 * Display the taxonomies of a post with available options.
3022 * This function can be used within the loop to display the taxonomies for a
3023 * post without specifying the Post ID. You can also use it outside the Loop to
3024 * display the taxonomies for a specific post.
3026 * The available defaults are:
3027 * 'post' : default is 0. The post ID to get taxonomies of.
3028 * 'before' : default is empty string. Display before taxonomies list.
3029 * 'sep' : default is empty string. Separate every taxonomy with value in this.
3030 * 'after' : default is empty string. Display this after the taxonomies list.
3031 * 'template' : The template to use for displaying the taxonomy terms.
3034 * @uses get_the_taxonomies()
3036 * @param array $args Override the defaults.
3038 function the_taxonomies($args = array()) {
3044 'template' => '%s: %l.'
3047 $r = wp_parse_args( $args, $defaults );
3048 extract( $r, EXTR_SKIP );
3050 echo $before . join($sep, get_the_taxonomies($post, $r)) . $after;
3054 * Retrieve all taxonomies associated with a post.
3056 * This function can be used within the loop. It will also return an array of
3057 * the taxonomies with links to the taxonomy and name.
3061 * @param int $post Optional. Post ID or will use Global Post ID (in loop).
3062 * @param array $args Override the defaults.
3065 function get_the_taxonomies($post = 0, $args = array() ) {
3066 if ( is_int($post) )
3067 $post =& get_post($post);
3068 elseif ( !is_object($post) )
3069 $post =& $GLOBALS['post'];
3071 $args = wp_parse_args( $args, array(
3072 'template' => '%s: %l.',
3074 extract( $args, EXTR_SKIP );
3076 $taxonomies = array();
3081 foreach ( get_object_taxonomies($post) as $taxonomy ) {
3082 $t = (array) get_taxonomy($taxonomy);
3083 if ( empty($t['label']) )
3084 $t['label'] = $taxonomy;
3085 if ( empty($t['args']) )
3086 $t['args'] = array();
3087 if ( empty($t['template']) )
3088 $t['template'] = $template;
3090 $terms = get_object_term_cache($post->ID, $taxonomy);
3091 if ( empty($terms) )
3092 $terms = wp_get_object_terms($post->ID, $taxonomy, $t['args']);
3096 foreach ( $terms as $term )
3097 $links[] = "<a href='" . esc_attr( get_term_link($term) ) . "'>$term->name</a>";
3100 $taxonomies[$taxonomy] = wp_sprintf($t['template'], $t['label'], $links, $terms);
3106 * Retrieve all taxonomies of a post with just the names.
3109 * @uses get_object_taxonomies()
3111 * @param int $post Optional. Post ID
3114 function get_post_taxonomies($post = 0) {
3115 $post =& get_post($post);
3117 return get_object_taxonomies($post);
3121 * Determine if the given object is associated with any of the given terms.
3123 * The given terms are checked against the object's terms' term_ids, names and slugs.
3124 * Terms given as integers will only be checked against the object's terms' term_ids.
3125 * If no terms are given, determines if object is associated with any terms in the given taxonomy.
3128 * @uses get_object_term_cache()
3129 * @uses wp_get_object_terms()
3131 * @param int $object_id ID of the object (post ID, link ID, ...)
3132 * @param string $taxonomy Single taxonomy name
3133 * @param int|string|array $terms Optional. Term term_id, name, slug or array of said
3134 * @return bool|WP_Error. WP_Error on input error.
3136 function is_object_in_term( $object_id, $taxonomy, $terms = null ) {
3137 if ( !$object_id = (int) $object_id )
3138 return new WP_Error( 'invalid_object', __( 'Invalid object ID' ) );
3140 $object_terms = get_object_term_cache( $object_id, $taxonomy );
3141 if ( empty( $object_terms ) )
3142 $object_terms = wp_get_object_terms( $object_id, $taxonomy );
3144 if ( is_wp_error( $object_terms ) )
3145 return $object_terms;
3146 if ( empty( $object_terms ) )
3148 if ( empty( $terms ) )
3149 return ( !empty( $object_terms ) );
3151 $terms = (array) $terms;
3153 if ( $ints = array_filter( $terms, 'is_int' ) )
3154 $strs = array_diff( $terms, $ints );
3158 foreach ( $object_terms as $object_term ) {
3159 if ( $ints && in_array( $object_term->term_id, $ints ) ) return true; // If int, check against term_id
3161 if ( in_array( $object_term->term_id, $strs ) ) return true;
3162 if ( in_array( $object_term->name, $strs ) ) return true;
3163 if ( in_array( $object_term->slug, $strs ) ) return true;
3171 * Determine if the given object type is associated with the given taxonomy.
3174 * @uses get_object_taxonomies()
3176 * @param string $object_type Object type string
3177 * @param string $taxonomy Single taxonomy name
3178 * @return bool True if object is associated with the taxonomy, otherwise false.
3180 function is_object_in_taxonomy($object_type, $taxonomy) {
3181 $taxonomies = get_object_taxonomies($object_type);
3183 if ( empty($taxonomies) )
3186 if ( in_array($taxonomy, $taxonomies) )
3193 * Get an array of ancestor IDs for a given object.
3195 * @param int $object_id The ID of the object
3196 * @param string $object_type The type of object for which we'll be retrieving ancestors.
3197 * @return array of ancestors from lowest to highest in the hierarchy.
3199 function get_ancestors($object_id = 0, $object_type = '') {
3200 $object_id = (int) $object_id;
3202 $ancestors = array();
3204 if ( empty( $object_id ) ) {
3205 return apply_filters('get_ancestors', $ancestors, $object_id, $object_type);
3208 if ( is_taxonomy_hierarchical( $object_type ) ) {
3209 $term = get_term($object_id, $object_type);
3210 while ( ! is_wp_error($term) && ! empty( $term->parent ) && ! in_array( $term->parent, $ancestors ) ) {
3211 $ancestors[] = (int) $term->parent;
3212 $term = get_term($term->parent, $object_type);
3214 } elseif ( null !== get_post_type_object( $object_type ) ) {
3215 $object = get_post($object_id);
3216 if ( ! is_wp_error( $object ) && isset( $object->ancestors ) && is_array( $object->ancestors ) )
3217 $ancestors = $object->ancestors;
3219 while ( ! is_wp_error($object) && ! empty( $object->post_parent ) && ! in_array( $object->post_parent, $ancestors ) ) {
3220 $ancestors[] = (int) $object->post_parent;
3221 $object = get_post($object->post_parent);
3226 return apply_filters('get_ancestors', $ancestors, $object_id, $object_type);
3230 * Returns the term's parent's term_ID
3234 * @param int $term_id
3235 * @param string $taxonomy
3237 * @return int|bool false on error
3239 function wp_get_term_taxonomy_parent_id( $term_id, $taxonomy ) {
3240 $term = get_term( $term_id, $taxonomy );
3241 if ( !$term || is_wp_error( $term ) )
3243 return (int) $term->parent;
3247 * Checks the given subset of the term hierarchy for hierarchy loops.
3248 * Prevents loops from forming and breaks those that it finds.
3250 * Attached to the wp_update_term_parent filter.
3253 * @uses wp_find_hierarchy_loop()
3255 * @param int $parent term_id of the parent for the term we're checking.
3256 * @param int $term_id The term we're checking.
3257 * @param string $taxonomy The taxonomy of the term we're checking.
3259 * @return int The new parent for the term.
3261 function wp_check_term_hierarchy_for_loops( $parent, $term_id, $taxonomy ) {
3262 // Nothing fancy here - bail
3266 // Can't be its own parent
3267 if ( $parent == $term_id )
3270 // Now look for larger loops
3272 if ( !$loop = wp_find_hierarchy_loop( 'wp_get_term_taxonomy_parent_id', $term_id, $parent, array( $taxonomy ) ) )
3273 return $parent; // No loop
3275 // Setting $parent to the given value causes a loop
3276 if ( isset( $loop[$term_id] ) )
3279 // There's a loop, but it doesn't contain $term_id. Break the loop.
3280 foreach ( array_keys( $loop ) as $loop_member )
3281 wp_update_term( $loop_member, $taxonomy, array( 'parent' => 0 ) );