11 // Taxonomy Registration
15 * Creates the initial taxonomies when 'init' action is fired.
17 function create_initial_taxonomies() {
20 register_taxonomy( 'category', 'post', array(
21 'hierarchical' => true,
22 'query_var' => 'category_name',
23 'rewrite' => did_action( 'init' ) ? array(
24 'hierarchical' => true,
25 'slug' => get_option('category_base') ? get_option('category_base') : 'category',
26 'with_front' => ( get_option('category_base') && ! $wp_rewrite->using_index_permalinks() ) ? false : true ) : false,
32 register_taxonomy( 'post_tag', 'post', array(
33 'hierarchical' => false,
35 'rewrite' => did_action( 'init' ) ? array(
36 'slug' => get_option('tag_base') ? get_option('tag_base') : 'tag',
37 'with_front' => ( get_option('tag_base') && ! $wp_rewrite->using_index_permalinks() ) ? false : true ) : false,
43 register_taxonomy( 'nav_menu', 'nav_menu_item', array(
45 'hierarchical' => false,
47 'name' => __( 'Navigation Menus' ),
48 'singular_name' => __( 'Navigation Menu' ),
54 'show_in_nav_menus' => false,
57 register_taxonomy( 'link_category', 'link', array(
58 'hierarchical' => false,
60 'name' => __( 'Link Categories' ),
61 'singular_name' => __( 'Link Category' ),
62 'search_items' => __( 'Search Link Categories' ),
63 'popular_items' => null,
64 'all_items' => __( 'All Link Categories' ),
65 'edit_item' => __( 'Edit Link Category' ),
66 'update_item' => __( 'Update Link Category' ),
67 'add_new_item' => __( 'Add New Link Category' ),
68 'new_item_name' => __( 'New Link Category Name' ),
69 'separate_items_with_commas' => null,
70 'add_or_remove_items' => null,
71 'choose_from_most_used' => null,
81 if ( did_action( 'init' ) ) {
82 $rewrite = apply_filters( 'post_format_rewrite_base', 'type' );
83 $rewrite = $rewrite ? array( 'slug' => $rewrite ) : false;
86 register_taxonomy( 'post_format', 'post', array(
88 'hierarchical' => false,
90 'name' => _x( 'Format', 'post format' ),
91 'singular_name' => _x( 'Format', 'post format' ),
94 'rewrite' => $rewrite,
97 'show_in_nav_menus' => false,
100 add_action( 'init', 'create_initial_taxonomies', 0 ); // highest priority
103 * Get a list of registered taxonomy objects.
106 * @subpackage Taxonomy
108 * @uses $wp_taxonomies
109 * @see register_taxonomy
111 * @param array $args An array of key => value arguments to match against the taxonomy objects.
112 * @param string $output The type of output to return, either taxonomy 'names' or 'objects'. 'names' is the default.
113 * @param string $operator The logical operation to perform. 'or' means only one element
114 * from the array needs to match; 'and' means all elements must match. The default is 'and'.
115 * @return array A list of taxonomy names or objects
117 function get_taxonomies( $args = array(), $output = 'names', $operator = 'and' ) {
118 global $wp_taxonomies;
120 $field = ('names' == $output) ? 'name' : false;
122 return wp_filter_object_list($wp_taxonomies, $args, $operator, $field);
127 * Return all of the taxonomy names that are of $object_type.
129 * It appears that this function can be used to find all of the names inside of
130 * $wp_taxonomies global variable.
132 * <code><?php $taxonomies = get_object_taxonomies('post'); ?></code> Should
133 * result in <code>Array('category', 'post_tag')</code>
136 * @subpackage Taxonomy
139 * @uses $wp_taxonomies
141 * @param array|string|object $object Name of the type of taxonomy object, or an object (row from posts)
142 * @param string $output The type of output to return, either taxonomy 'names' or 'objects'. 'names' is the default.
143 * @return array The names of all taxonomy of $object_type.
145 function get_object_taxonomies($object, $output = 'names') {
146 global $wp_taxonomies;
148 if ( is_object($object) ) {
149 if ( $object->post_type == 'attachment' )
150 return get_attachment_taxonomies($object);
151 $object = $object->post_type;
154 $object = (array) $object;
156 $taxonomies = array();
157 foreach ( (array) $wp_taxonomies as $tax_name => $tax_obj ) {
158 if ( array_intersect($object, (array) $tax_obj->object_type) ) {
159 if ( 'names' == $output )
160 $taxonomies[] = $tax_name;
162 $taxonomies[ $tax_name ] = $tax_obj;
170 * Retrieves the taxonomy object of $taxonomy.
172 * The get_taxonomy function will first check that the parameter string given
173 * is a taxonomy object and if it is, it will return it.
176 * @subpackage Taxonomy
179 * @uses $wp_taxonomies
180 * @uses taxonomy_exists() Checks whether taxonomy exists
182 * @param string $taxonomy Name of taxonomy object to return
183 * @return object|bool The Taxonomy Object or false if $taxonomy doesn't exist
185 function get_taxonomy( $taxonomy ) {
186 global $wp_taxonomies;
188 if ( ! taxonomy_exists( $taxonomy ) )
191 return $wp_taxonomies[$taxonomy];
195 * Checks that the taxonomy name exists.
197 * Formerly is_taxonomy(), introduced in 2.3.0.
200 * @subpackage Taxonomy
203 * @uses $wp_taxonomies
205 * @param string $taxonomy Name of taxonomy object
206 * @return bool Whether the taxonomy exists.
208 function taxonomy_exists( $taxonomy ) {
209 global $wp_taxonomies;
211 return isset( $wp_taxonomies[$taxonomy] );
215 * Whether the taxonomy object is hierarchical.
217 * Checks to make sure that the taxonomy is an object first. Then Gets the
218 * object, and finally returns the hierarchical value in the object.
220 * A false return value might also mean that the taxonomy does not exist.
223 * @subpackage Taxonomy
226 * @uses taxonomy_exists() Checks whether taxonomy exists
227 * @uses get_taxonomy() Used to get the taxonomy object
229 * @param string $taxonomy Name of taxonomy object
230 * @return bool Whether the taxonomy is hierarchical
232 function is_taxonomy_hierarchical($taxonomy) {
233 if ( ! taxonomy_exists($taxonomy) )
236 $taxonomy = get_taxonomy($taxonomy);
237 return $taxonomy->hierarchical;
241 * Create or modify a taxonomy object. Do not use before init.
243 * A simple function for creating or modifying a taxonomy object based on the
244 * parameters given. The function will accept an array (third optional
245 * parameter), along with strings for the taxonomy name and another string for
248 * Nothing is returned, so expect error maybe or use taxonomy_exists() to check
249 * whether taxonomy exists.
251 * Optional $args contents:
253 * label - Name of the taxonomy shown in the menu. Usually plural. If not set, labels['name'] will be used.
255 * hierarchical - has some defined purpose at other parts of the API and is a
258 * update_count_callback - works much like a hook, in that it will be called when the count is updated.
259 * Defaults to _update_post_term_count() for taxonomies attached to post types, which then confirms
260 * that the objects are published before counting them.
261 * Defaults to _update_generic_term_count() for taxonomies attached to other object types, such as links.
263 * rewrite - false to prevent rewrite, or array('slug'=>$slug) to customize
264 * permastruct; default will use $taxonomy as slug.
266 * query_var - false to prevent queries, or string to customize query var
267 * (?$query_var=$term); default will use $taxonomy as query var.
269 * public - If the taxonomy should be publicly queryable; //@TODO not implemented.
272 * show_ui - If the WordPress UI admin tags UI should apply to this taxonomy;
273 * defaults to public.
275 * show_in_nav_menus - true makes this taxonomy available for selection in navigation menus.
276 * Defaults to public.
278 * show_tagcloud - false to prevent the taxonomy being listed in the Tag Cloud Widget;
279 * defaults to show_ui which defaults to public.
281 * labels - An array of labels for this taxonomy. You can see accepted values in {@link get_taxonomy_labels()}. By default tag labels are used for non-hierarchical types and category labels for hierarchical ones.
284 * @subpackage Taxonomy
286 * @uses $wp_taxonomies Inserts new taxonomy object into the list
287 * @uses $wp_rewrite Adds rewrite tags and permastructs
288 * @uses $wp Adds query vars
290 * @param string $taxonomy Name of taxonomy object
291 * @param array|string $object_type Name of the object type for the taxonomy object.
292 * @param array|string $args See above description for the two keys values.
294 function register_taxonomy( $taxonomy, $object_type, $args = array() ) {
295 global $wp_taxonomies, $wp_rewrite, $wp;
297 if ( ! is_array($wp_taxonomies) )
298 $wp_taxonomies = array();
300 $defaults = array( 'hierarchical' => false,
301 'update_count_callback' => '',
303 'query_var' => $taxonomy,
306 'show_tagcloud' => null,
309 'capabilities' => array(),
310 'show_in_nav_menus' => null,
312 $args = wp_parse_args($args, $defaults);
314 if ( false !== $args['query_var'] && !empty($wp) ) {
315 if ( true === $args['query_var'] )
316 $args['query_var'] = $taxonomy;
317 $args['query_var'] = sanitize_title_with_dashes($args['query_var']);
318 $wp->add_query_var($args['query_var']);
321 if ( false !== $args['rewrite'] && '' != get_option('permalink_structure') ) {
322 $args['rewrite'] = wp_parse_args($args['rewrite'], array(
323 'slug' => sanitize_title_with_dashes($taxonomy),
324 'with_front' => true,
325 'hierarchical' => false
328 if ( $args['hierarchical'] && $args['rewrite']['hierarchical'] )
333 $wp_rewrite->add_rewrite_tag("%$taxonomy%", $tag, $args['query_var'] ? "{$args['query_var']}=" : "taxonomy=$taxonomy&term=");
334 $wp_rewrite->add_permastruct($taxonomy, "{$args['rewrite']['slug']}/%$taxonomy%", $args['rewrite']['with_front']);
337 if ( is_null($args['show_ui']) )
338 $args['show_ui'] = $args['public'];
340 // Whether to show this type in nav-menus.php. Defaults to the setting for public.
341 if ( null === $args['show_in_nav_menus'] )
342 $args['show_in_nav_menus'] = $args['public'];
344 if ( is_null($args['show_tagcloud']) )
345 $args['show_tagcloud'] = $args['show_ui'];
347 $default_caps = array(
348 'manage_terms' => 'manage_categories',
349 'edit_terms' => 'manage_categories',
350 'delete_terms' => 'manage_categories',
351 'assign_terms' => 'edit_posts',
353 $args['cap'] = (object) array_merge( $default_caps, $args['capabilities'] );
354 unset( $args['capabilities'] );
356 $args['name'] = $taxonomy;
357 $args['object_type'] = array_unique( (array)$object_type );
359 $args['labels'] = get_taxonomy_labels( (object) $args );
360 $args['label'] = $args['labels']->name;
362 $wp_taxonomies[$taxonomy] = (object) $args;
364 // register callback handling for metabox
365 add_filter('wp_ajax_add-' . $taxonomy, '_wp_ajax_add_hierarchical_term');
367 do_action( 'registered_taxonomy', $taxonomy, $object_type, $args );
371 * Builds an object with all taxonomy labels out of a taxonomy object
373 * Accepted keys of the label array in the taxonomy object:
374 * - name - general name for the taxonomy, usually plural. The same as and overridden by $tax->label. Default is Tags/Categories
375 * - singular_name - name for one object of this taxonomy. Default is Tag/Category
376 * - search_items - Default is Search Tags/Search Categories
377 * - popular_items - This string isn't used on hierarchical taxonomies. Default is Popular Tags
378 * - all_items - Default is All Tags/All Categories
379 * - parent_item - This string isn't used on non-hierarchical taxonomies. In hierarchical ones the default is Parent Category
380 * - parent_item_colon - The same as <code>parent_item</code>, but with colon <code>:</code> in the end
381 * - edit_item - Default is Edit Tag/Edit Category
382 * - update_item - Default is Update Tag/Update Category
383 * - add_new_item - Default is Add New Tag/Add New Category
384 * - new_item_name - Default is New Tag Name/New Category Name
385 * - separate_items_with_commas - This string isn't used on hierarchical taxonomies. Default is "Separate tags with commas," used in the meta box.
386 * - 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.
387 * - 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.
389 * Above, the first default value is for non-hierarchical taxonomies (like tags) and the second one is for hierarchical taxonomies (like categories.)
392 * @param object $tax Taxonomy object
393 * @return object object with all the labels as member variables
396 function get_taxonomy_labels( $tax ) {
397 if ( isset( $tax->helps ) && empty( $tax->labels['separate_items_with_commas'] ) )
398 $tax->labels['separate_items_with_commas'] = $tax->helps;
400 $nohier_vs_hier_defaults = array(
401 'name' => array( _x( 'Tags', 'taxonomy general name' ), _x( 'Categories', 'taxonomy general name' ) ),
402 'singular_name' => array( _x( 'Tag', 'taxonomy singular name' ), _x( 'Category', 'taxonomy singular name' ) ),
403 'search_items' => array( __( 'Search Tags' ), __( 'Search Categories' ) ),
404 'popular_items' => array( __( 'Popular Tags' ), null ),
405 'all_items' => array( __( 'All Tags' ), __( 'All Categories' ) ),
406 'parent_item' => array( null, __( 'Parent Category' ) ),
407 'parent_item_colon' => array( null, __( 'Parent Category:' ) ),
408 'edit_item' => array( __( 'Edit Tag' ), __( 'Edit Category' ) ),
409 'view_item' => array( __( 'View Tag' ), __( 'View Category' ) ),
410 'update_item' => array( __( 'Update Tag' ), __( 'Update Category' ) ),
411 'add_new_item' => array( __( 'Add New Tag' ), __( 'Add New Category' ) ),
412 'new_item_name' => array( __( 'New Tag Name' ), __( 'New Category Name' ) ),
413 'separate_items_with_commas' => array( __( 'Separate tags with commas' ), null ),
414 'add_or_remove_items' => array( __( 'Add or remove tags' ), null ),
415 'choose_from_most_used' => array( __( 'Choose from the most used tags' ), null ),
417 $nohier_vs_hier_defaults['menu_name'] = $nohier_vs_hier_defaults['name'];
419 return _get_custom_object_labels( $tax, $nohier_vs_hier_defaults );
423 * Add an already registered taxonomy to an object type.
426 * @subpackage Taxonomy
428 * @uses $wp_taxonomies Modifies taxonomy object
430 * @param string $taxonomy Name of taxonomy object
431 * @param array|string $object_type Name of the object type
432 * @return bool True if successful, false if not
434 function register_taxonomy_for_object_type( $taxonomy, $object_type) {
435 global $wp_taxonomies;
437 if ( !isset($wp_taxonomies[$taxonomy]) )
440 if ( ! get_post_type_object($object_type) )
443 if ( ! in_array( $object_type, $wp_taxonomies[$taxonomy]->object_type ) )
444 $wp_taxonomies[$taxonomy]->object_type[] = $object_type;
454 * Retrieve object_ids of valid taxonomy and term.
456 * The strings of $taxonomies must exist before this function will continue. On
457 * failure of finding a valid taxonomy, it will return an WP_Error class, kind
458 * of like Exceptions in PHP 5, except you can't catch them. Even so, you can
459 * still test for the WP_Error class and get the error message.
461 * The $terms aren't checked the same as $taxonomies, but still need to exist
462 * for $object_ids to be returned.
464 * It is possible to change the order that object_ids is returned by either
465 * using PHP sort family functions or using the database by using $args with
466 * either ASC or DESC array. The value should be in the key named 'order'.
469 * @subpackage Taxonomy
473 * @uses wp_parse_args() Creates an array from string $args.
475 * @param int|array $term_ids Term id or array of term ids of terms that will be used
476 * @param string|array $taxonomies String of taxonomy name or Array of string values of taxonomy names
477 * @param array|string $args Change the order of the object_ids, either ASC or DESC
478 * @return WP_Error|array If the taxonomy does not exist, then WP_Error will be returned. On success
479 * the array can be empty meaning that there are no $object_ids found or it will return the $object_ids found.
481 function get_objects_in_term( $term_ids, $taxonomies, $args = array() ) {
484 if ( ! is_array( $term_ids ) )
485 $term_ids = array( $term_ids );
487 if ( ! is_array( $taxonomies ) )
488 $taxonomies = array( $taxonomies );
490 foreach ( (array) $taxonomies as $taxonomy ) {
491 if ( ! taxonomy_exists( $taxonomy ) )
492 return new WP_Error( 'invalid_taxonomy', __( 'Invalid Taxonomy' ) );
495 $defaults = array( 'order' => 'ASC' );
496 $args = wp_parse_args( $args, $defaults );
497 extract( $args, EXTR_SKIP );
499 $order = ( 'desc' == strtolower( $order ) ) ? 'DESC' : 'ASC';
501 $term_ids = array_map('intval', $term_ids );
503 $taxonomies = "'" . implode( "', '", $taxonomies ) . "'";
504 $term_ids = "'" . implode( "', '", $term_ids ) . "'";
506 $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");
515 * Given a taxonomy query, generates SQL to be appended to a main query.
521 * @param array $tax_query A compact tax query
522 * @param string $primary_table
523 * @param string $primary_id_column
526 function get_tax_sql( $tax_query, $primary_table, $primary_id_column ) {
527 $tax_query_obj = new WP_Tax_Query( $tax_query );
528 return $tax_query_obj->get_sql( $primary_table, $primary_id_column );
532 * Container class for a multiple taxonomy query.
539 * List of taxonomy queries. A single taxonomy query is an associative array:
540 * - 'taxonomy' string The taxonomy being queried
541 * - 'terms' string|array The list of terms
542 * - 'field' string (optional) Which term field is being used.
543 * Possible values: 'term_id', 'slug' or 'name'
545 * - 'operator' string (optional)
546 * Possible values: 'AND', 'IN' or 'NOT IN'.
548 * - 'include_children' bool (optional) Whether to include child terms.
555 public $queries = array();
558 * The relation between the queries. Can be one of 'AND' or 'OR'.
567 * Standard response when the query should not return any rows.
573 private static $no_results = array( 'join' => '', 'where' => ' AND 0 = 1' );
578 * Parses a compact tax query and sets defaults.
583 * @param array $tax_query A compact tax query:
585 * 'relation' => 'OR',
587 * 'taxonomy' => 'tax1',
588 * 'terms' => array( 'term1', 'term2' ),
592 * 'taxonomy' => 'tax2',
593 * 'terms' => array( 'term-a', 'term-b' ),
598 public function __construct( $tax_query ) {
599 if ( isset( $tax_query['relation'] ) && strtoupper( $tax_query['relation'] ) == 'OR' ) {
600 $this->relation = 'OR';
602 $this->relation = 'AND';
608 'include_children' => true,
609 'field' => 'term_id',
613 foreach ( $tax_query as $query ) {
614 if ( ! is_array( $query ) )
617 $query = array_merge( $defaults, $query );
619 $query['terms'] = (array) $query['terms'];
621 $this->queries[] = $query;
626 * Generates SQL clauses to be appended to a main query.
631 * @param string $primary_table
632 * @param string $primary_id_column
635 public function get_sql( $primary_table, $primary_id_column ) {
642 foreach ( $this->queries as $query ) {
643 $this->clean_query( $query );
645 if ( is_wp_error( $query ) ) {
646 return self::$no_results;
651 if ( 'IN' == $operator ) {
653 if ( empty( $terms ) ) {
654 if ( 'OR' == $this->relation )
657 return self::$no_results;
660 $terms = implode( ',', $terms );
662 $alias = $i ? 'tt' . $i : $wpdb->term_relationships;
664 $join .= " INNER JOIN $wpdb->term_relationships";
665 $join .= $i ? " AS $alias" : '';
666 $join .= " ON ($primary_table.$primary_id_column = $alias.object_id)";
668 $where[] = "$alias.term_taxonomy_id $operator ($terms)";
669 } elseif ( 'NOT IN' == $operator ) {
671 if ( empty( $terms ) )
674 $terms = implode( ',', $terms );
676 $where[] = "$primary_table.$primary_id_column NOT IN (
678 FROM $wpdb->term_relationships
679 WHERE term_taxonomy_id IN ($terms)
681 } elseif ( 'AND' == $operator ) {
683 if ( empty( $terms ) )
686 $num_terms = count( $terms );
688 $terms = implode( ',', $terms );
692 FROM $wpdb->term_relationships
693 WHERE term_taxonomy_id IN ($terms)
694 AND object_id = $primary_table.$primary_id_column
701 if ( !empty( $where ) )
702 $where = ' AND ( ' . implode( " $this->relation ", $where ) . ' )';
706 return compact( 'join', 'where' );
710 * Validates a single query.
715 * @param array &$query The single query
717 private function clean_query( &$query ) {
718 if ( ! taxonomy_exists( $query['taxonomy'] ) ) {
719 $query = new WP_Error( 'Invalid taxonomy' );
723 $query['terms'] = array_unique( (array) $query['terms'] );
725 if ( is_taxonomy_hierarchical( $query['taxonomy'] ) && $query['include_children'] ) {
726 $this->transform_query( $query, 'term_id' );
728 if ( is_wp_error( $query ) )
732 foreach ( $query['terms'] as $term ) {
733 $children = array_merge( $children, get_term_children( $term, $query['taxonomy'] ) );
736 $query['terms'] = $children;
739 $this->transform_query( $query, 'term_taxonomy_id' );
743 * Transforms a single query, from one field to another.
748 * @param array &$query The single query
749 * @param string $resulting_field The resulting field
751 private function transform_query( &$query, $resulting_field ) {
754 if ( empty( $query['terms'] ) )
757 if ( $query['field'] == $resulting_field )
760 $resulting_field = esc_sql( $resulting_field );
762 switch ( $query['field'] ) {
765 $terms = "'" . implode( "','", array_map( 'sanitize_title_for_query', $query['terms'] ) ) . "'";
766 $terms = $wpdb->get_col( "
767 SELECT $wpdb->term_taxonomy.$resulting_field
768 FROM $wpdb->term_taxonomy
769 INNER JOIN $wpdb->terms USING (term_id)
770 WHERE taxonomy = '{$query['taxonomy']}'
771 AND $wpdb->terms.{$query['field']} IN ($terms)
776 $terms = implode( ',', array_map( 'intval', $query['terms'] ) );
777 $terms = $wpdb->get_col( "
778 SELECT $resulting_field
779 FROM $wpdb->term_taxonomy
780 WHERE taxonomy = '{$query['taxonomy']}'
781 AND term_id IN ($terms)
785 if ( 'AND' == $query['operator'] && count( $terms ) < count( $query['terms'] ) ) {
786 $query = new WP_Error( 'Inexistent terms' );
790 $query['terms'] = $terms;
791 $query['field'] = $resulting_field;
796 * Get all Term data from database by Term ID.
798 * The usage of the get_term function is to apply filters to a term object. It
799 * is possible to get a term object from the database before applying the
802 * $term ID must be part of $taxonomy, to get from the database. Failure, might
803 * be able to be captured by the hooks. Failure would be the same value as $wpdb
804 * returns for the get_row method.
806 * There are two hooks, one is specifically for each term, named 'get_term', and
807 * the second is for the taxonomy name, 'term_$taxonomy'. Both hooks gets the
808 * term object, and the taxonomy name as parameters. Both hooks are expected to
809 * return a Term object.
811 * 'get_term' hook - Takes two parameters the term Object and the taxonomy name.
812 * Must return term object. Used in get_term() as a catch-all filter for every
815 * 'get_$taxonomy' hook - Takes two parameters the term Object and the taxonomy
816 * name. Must return term object. $taxonomy will be the taxonomy name, so for
817 * example, if 'category', it would be 'get_category' as the filter name. Useful
818 * for custom taxonomies or plugging into default taxonomies.
821 * @subpackage Taxonomy
825 * @uses sanitize_term() Cleanses the term based on $filter context before returning.
826 * @see sanitize_term_field() The $context param lists the available values for get_term_by() $filter param.
828 * @param int|object $term If integer, will get from database. If object will apply filters and return $term.
829 * @param string $taxonomy Taxonomy name that $term is part of.
830 * @param string $output Constant OBJECT, ARRAY_A, or ARRAY_N
831 * @param string $filter Optional, default is raw or no WordPress defined filter will applied.
832 * @return mixed|null|WP_Error Term Row from database. Will return null if $term is empty. If taxonomy does not
833 * exist then WP_Error will be returned.
835 function &get_term($term, $taxonomy, $output = OBJECT, $filter = 'raw') {
839 if ( empty($term) ) {
840 $error = new WP_Error('invalid_term', __('Empty Term'));
844 if ( ! taxonomy_exists($taxonomy) ) {
845 $error = new WP_Error('invalid_taxonomy', __('Invalid Taxonomy'));
849 if ( is_object($term) && empty($term->filter) ) {
850 wp_cache_add($term->term_id, $term, $taxonomy);
853 if ( is_object($term) )
854 $term = $term->term_id;
855 if ( !$term = (int) $term )
857 if ( ! $_term = wp_cache_get($term, $taxonomy) ) {
858 $_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) );
861 wp_cache_add($term, $_term, $taxonomy);
865 $_term = apply_filters('get_term', $_term, $taxonomy);
866 $_term = apply_filters("get_$taxonomy", $_term, $taxonomy);
867 $_term = sanitize_term($_term, $taxonomy, $filter);
869 if ( $output == OBJECT ) {
871 } elseif ( $output == ARRAY_A ) {
872 $__term = get_object_vars($_term);
874 } elseif ( $output == ARRAY_N ) {
875 $__term = array_values(get_object_vars($_term));
883 * Get all Term data from database by Term field and data.
885 * Warning: $value is not escaped for 'name' $field. You must do it yourself, if
888 * The default $field is 'id', therefore it is possible to also use null for
889 * field, but not recommended that you do so.
891 * If $value does not exist, the return value will be false. If $taxonomy exists
892 * and $field and $value combinations exist, the Term will be returned.
895 * @subpackage Taxonomy
899 * @uses sanitize_term() Cleanses the term based on $filter context before returning.
900 * @see sanitize_term_field() The $context param lists the available values for get_term_by() $filter param.
902 * @param string $field Either 'slug', 'name', or 'id'
903 * @param string|int $value Search for this term value
904 * @param string $taxonomy Taxonomy Name
905 * @param string $output Constant OBJECT, ARRAY_A, or ARRAY_N
906 * @param string $filter Optional, default is raw or no WordPress defined filter will applied.
907 * @return mixed Term Row from database. Will return false if $taxonomy does not exist or $term was not found.
909 function get_term_by($field, $value, $taxonomy, $output = OBJECT, $filter = 'raw') {
912 if ( ! taxonomy_exists($taxonomy) )
915 if ( 'slug' == $field ) {
917 $value = sanitize_title($value);
920 } else if ( 'name' == $field ) {
921 // Assume already escaped
922 $value = stripslashes($value);
925 $term = get_term( (int) $value, $taxonomy, $output, $filter);
926 if ( is_wp_error( $term ) )
931 $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) );
935 wp_cache_add($term->term_id, $term, $taxonomy);
937 $term = apply_filters('get_term', $term, $taxonomy);
938 $term = apply_filters("get_$taxonomy", $term, $taxonomy);
939 $term = sanitize_term($term, $taxonomy, $filter);
941 if ( $output == OBJECT ) {
943 } elseif ( $output == ARRAY_A ) {
944 return get_object_vars($term);
945 } elseif ( $output == ARRAY_N ) {
946 return array_values(get_object_vars($term));
953 * Merge all term children into a single array of their IDs.
955 * This recursive function will merge all of the children of $term into the same
956 * array of term IDs. Only useful for taxonomies which are hierarchical.
958 * Will return an empty array if $term does not exist in $taxonomy.
961 * @subpackage Taxonomy
965 * @uses _get_term_hierarchy()
966 * @uses get_term_children() Used to get the children of both $taxonomy and the parent $term
968 * @param string $term_id ID of Term to get children
969 * @param string $taxonomy Taxonomy Name
970 * @return array|WP_Error List of Term Objects. WP_Error returned if $taxonomy does not exist
972 function get_term_children( $term_id, $taxonomy ) {
973 if ( ! taxonomy_exists($taxonomy) )
974 return new WP_Error('invalid_taxonomy', __('Invalid Taxonomy'));
976 $term_id = intval( $term_id );
978 $terms = _get_term_hierarchy($taxonomy);
980 if ( ! isset($terms[$term_id]) )
983 $children = $terms[$term_id];
985 foreach ( (array) $terms[$term_id] as $child ) {
986 if ( isset($terms[$child]) )
987 $children = array_merge($children, get_term_children($child, $taxonomy));
994 * Get sanitized Term field.
996 * Does checks for $term, based on the $taxonomy. The function is for contextual
997 * reasons and for simplicity of usage. See sanitize_term_field() for more
1000 * @package WordPress
1001 * @subpackage Taxonomy
1004 * @uses sanitize_term_field() Passes the return value in sanitize_term_field on success.
1006 * @param string $field Term field to fetch
1007 * @param int $term Term ID
1008 * @param string $taxonomy Taxonomy Name
1009 * @param string $context Optional, default is display. Look at sanitize_term_field() for available options.
1010 * @return mixed Will return an empty string if $term is not an object or if $field is not set in $term.
1012 function get_term_field( $field, $term, $taxonomy, $context = 'display' ) {
1013 $term = (int) $term;
1014 $term = get_term( $term, $taxonomy );
1015 if ( is_wp_error($term) )
1018 if ( !is_object($term) )
1021 if ( !isset($term->$field) )
1024 return sanitize_term_field($field, $term->$field, $term->term_id, $taxonomy, $context);
1028 * Sanitizes Term for editing.
1030 * Return value is sanitize_term() and usage is for sanitizing the term for
1031 * editing. Function is for contextual and simplicity.
1033 * @package WordPress
1034 * @subpackage Taxonomy
1037 * @uses sanitize_term() Passes the return value on success
1039 * @param int|object $id Term ID or Object
1040 * @param string $taxonomy Taxonomy Name
1041 * @return mixed|null|WP_Error Will return empty string if $term is not an object.
1043 function get_term_to_edit( $id, $taxonomy ) {
1044 $term = get_term( $id, $taxonomy );
1046 if ( is_wp_error($term) )
1049 if ( !is_object($term) )
1052 return sanitize_term($term, $taxonomy, 'edit');
1056 * Retrieve the terms in a given taxonomy or list of taxonomies.
1058 * You can fully inject any customizations to the query before it is sent, as
1059 * well as control the output with a filter.
1061 * The 'get_terms' filter will be called when the cache has the term and will
1062 * pass the found term along with the array of $taxonomies and array of $args.
1063 * This filter is also called before the array of terms is passed and will pass
1064 * the array of terms, along with the $taxonomies and $args.
1066 * The 'list_terms_exclusions' filter passes the compiled exclusions along with
1069 * The 'get_terms_orderby' filter passes the ORDER BY clause for the query
1070 * along with the $args array.
1072 * The 'get_terms_fields' filter passes the fields for the SELECT query
1073 * along with the $args array.
1075 * The list of arguments that $args can contain, which will overwrite the defaults:
1077 * orderby - Default is 'name'. Can be name, count, term_group, slug or nothing
1078 * (will use term_id), Passing a custom value other than these will cause it to
1079 * order based on the custom value.
1081 * order - Default is ASC. Can use DESC.
1083 * hide_empty - Default is true. Will not return empty terms, which means
1084 * terms whose count is 0 according to the given taxonomy.
1086 * exclude - Default is an empty array. An array, comma- or space-delimited string
1087 * of term ids to exclude from the return array. If 'include' is non-empty,
1088 * 'exclude' is ignored.
1090 * exclude_tree - Default is an empty array. An array, comma- or space-delimited
1091 * string of term ids to exclude from the return array, along with all of their
1092 * descendant terms according to the primary taxonomy. If 'include' is non-empty,
1093 * 'exclude_tree' is ignored.
1095 * include - Default is an empty array. An array, comma- or space-delimited string
1096 * of term ids to include in the return array.
1098 * number - The maximum number of terms to return. Default is to return them all.
1100 * offset - The number by which to offset the terms query.
1102 * fields - Default is 'all', which returns an array of term objects.
1103 * If 'fields' is 'ids' or 'names', returns an array of
1104 * integers or strings, respectively.
1106 * slug - Returns terms whose "slug" matches this value. Default is empty string.
1108 * hierarchical - Whether to include terms that have non-empty descendants
1109 * (even if 'hide_empty' is set to true).
1111 * search - Returned terms' names will contain the value of 'search',
1112 * case-insensitive. Default is an empty string.
1114 * name__like - Returned terms' names will begin with the value of 'name__like',
1115 * case-insensitive. Default is empty string.
1117 * The argument 'pad_counts', if set to true will include the quantity of a term's
1118 * children in the quantity of each term's "count" object variable.
1120 * The 'get' argument, if set to 'all' instead of its default empty string,
1121 * returns terms regardless of ancestry or whether the terms are empty.
1123 * The 'child_of' argument, when used, should be set to the integer of a term ID. Its default
1124 * is 0. If set to a non-zero value, all returned terms will be descendants
1125 * of that term according to the given taxonomy. Hence 'child_of' is set to 0
1126 * if more than one taxonomy is passed in $taxonomies, because multiple taxonomies
1127 * make term ancestry ambiguous.
1129 * The 'parent' argument, when used, should be set to the integer of a term ID. Its default is
1130 * the empty string '', which has a different meaning from the integer 0.
1131 * If set to an integer value, all returned terms will have as an immediate
1132 * ancestor the term whose ID is specified by that integer according to the given taxonomy.
1133 * The 'parent' argument is different from 'child_of' in that a term X is considered a 'parent'
1134 * of term Y only if term X is the father of term Y, not its grandfather or great-grandfather, etc.
1136 * The 'cache_domain' argument enables a unique cache key to be produced when this query is stored
1137 * in object cache. For instance, if you are using one of this function's filters to modify the
1138 * query (such as 'terms_clauses'), setting 'cache_domain' to a unique value will not overwrite
1139 * the cache for similar queries. Default value is 'core'.
1141 * @package WordPress
1142 * @subpackage Taxonomy
1146 * @uses wp_parse_args() Merges the defaults with those defined by $args and allows for strings.
1148 * @param string|array $taxonomies Taxonomy name or list of Taxonomy names
1149 * @param string|array $args The values of what to search for when returning terms
1150 * @return array|WP_Error List of Term Objects and their children. Will return WP_Error, if any of $taxonomies do not exist.
1152 function &get_terms($taxonomies, $args = '') {
1154 $empty_array = array();
1156 $single_taxonomy = false;
1157 if ( !is_array($taxonomies) ) {
1158 $single_taxonomy = true;
1159 $taxonomies = array($taxonomies);
1162 foreach ( $taxonomies as $taxonomy ) {
1163 if ( ! taxonomy_exists($taxonomy) ) {
1164 $error = new WP_Error('invalid_taxonomy', __('Invalid Taxonomy'));
1169 $defaults = array('orderby' => 'name', 'order' => 'ASC',
1170 'hide_empty' => true, 'exclude' => array(), 'exclude_tree' => array(), 'include' => array(),
1171 'number' => '', 'fields' => 'all', 'slug' => '', 'parent' => '',
1172 'hierarchical' => true, 'child_of' => 0, 'get' => '', 'name__like' => '',
1173 'pad_counts' => false, 'offset' => '', 'search' => '', 'cache_domain' => 'core' );
1174 $args = wp_parse_args( $args, $defaults );
1175 $args['number'] = absint( $args['number'] );
1176 $args['offset'] = absint( $args['offset'] );
1177 if ( !$single_taxonomy || !is_taxonomy_hierarchical($taxonomies[0]) ||
1178 '' !== $args['parent'] ) {
1179 $args['child_of'] = 0;
1180 $args['hierarchical'] = false;
1181 $args['pad_counts'] = false;
1184 if ( 'all' == $args['get'] ) {
1185 $args['child_of'] = 0;
1186 $args['hide_empty'] = 0;
1187 $args['hierarchical'] = false;
1188 $args['pad_counts'] = false;
1191 $args = apply_filters( 'get_terms_args', $args, $taxonomies );
1193 extract($args, EXTR_SKIP);
1196 $hierarchy = _get_term_hierarchy($taxonomies[0]);
1197 if ( !isset($hierarchy[$child_of]) )
1198 return $empty_array;
1202 $hierarchy = _get_term_hierarchy($taxonomies[0]);
1203 if ( !isset($hierarchy[$parent]) )
1204 return $empty_array;
1207 // $args can be whatever, only use the args defined in defaults to compute the key
1208 $filter_key = ( has_filter('list_terms_exclusions') ) ? serialize($GLOBALS['wp_filter']['list_terms_exclusions']) : '';
1209 $key = md5( serialize( compact(array_keys($defaults)) ) . serialize( $taxonomies ) . $filter_key );
1210 $last_changed = wp_cache_get('last_changed', 'terms');
1211 if ( !$last_changed ) {
1212 $last_changed = time();
1213 wp_cache_set('last_changed', $last_changed, 'terms');
1215 $cache_key = "get_terms:$key:$last_changed";
1216 $cache = wp_cache_get( $cache_key, 'terms' );
1217 if ( false !== $cache ) {
1218 $cache = apply_filters('get_terms', $cache, $taxonomies, $args);
1222 $_orderby = strtolower($orderby);
1223 if ( 'count' == $_orderby )
1224 $orderby = 'tt.count';
1225 else if ( 'name' == $_orderby )
1226 $orderby = 't.name';
1227 else if ( 'slug' == $_orderby )
1228 $orderby = 't.slug';
1229 else if ( 'term_group' == $_orderby )
1230 $orderby = 't.term_group';
1231 else if ( 'none' == $_orderby )
1233 elseif ( empty($_orderby) || 'id' == $_orderby )
1234 $orderby = 't.term_id';
1236 $orderby = 't.name';
1238 $orderby = apply_filters( 'get_terms_orderby', $orderby, $args );
1240 if ( !empty($orderby) )
1241 $orderby = "ORDER BY $orderby";
1245 $order = strtoupper( $order );
1246 if ( '' !== $order && !in_array( $order, array( 'ASC', 'DESC' ) ) )
1249 $where = "tt.taxonomy IN ('" . implode("', '", $taxonomies) . "')";
1251 if ( !empty($include) ) {
1254 $interms = wp_parse_id_list($include);
1255 foreach ( $interms as $interm ) {
1256 if ( empty($inclusions) )
1257 $inclusions = ' AND ( t.term_id = ' . intval($interm) . ' ';
1259 $inclusions .= ' OR t.term_id = ' . intval($interm) . ' ';
1263 if ( !empty($inclusions) )
1265 $where .= $inclusions;
1268 if ( !empty( $exclude_tree ) ) {
1269 $excluded_trunks = wp_parse_id_list($exclude_tree);
1270 foreach ( $excluded_trunks as $extrunk ) {
1271 $excluded_children = (array) get_terms($taxonomies[0], array('child_of' => intval($extrunk), 'fields' => 'ids', 'hide_empty' => 0));
1272 $excluded_children[] = $extrunk;
1273 foreach( $excluded_children as $exterm ) {
1274 if ( empty($exclusions) )
1275 $exclusions = ' AND ( t.term_id <> ' . intval($exterm) . ' ';
1277 $exclusions .= ' AND t.term_id <> ' . intval($exterm) . ' ';
1282 if ( !empty($exclude) ) {
1283 $exterms = wp_parse_id_list($exclude);
1284 foreach ( $exterms as $exterm ) {
1285 if ( empty($exclusions) )
1286 $exclusions = ' AND ( t.term_id <> ' . intval($exterm) . ' ';
1288 $exclusions .= ' AND t.term_id <> ' . intval($exterm) . ' ';
1292 if ( !empty($exclusions) )
1294 $exclusions = apply_filters('list_terms_exclusions', $exclusions, $args );
1295 $where .= $exclusions;
1297 if ( !empty($slug) ) {
1298 $slug = sanitize_title($slug);
1299 $where .= " AND t.slug = '$slug'";
1302 if ( !empty($name__like) ) {
1303 $name__like = like_escape( $name__like );
1304 $where .= $wpdb->prepare( " AND t.name LIKE %s", $name__like . '%' );
1307 if ( '' !== $parent ) {
1308 $parent = (int) $parent;
1309 $where .= " AND tt.parent = '$parent'";
1312 if ( $hide_empty && !$hierarchical )
1313 $where .= ' AND tt.count > 0';
1315 // don't limit the query results when we have to descend the family tree
1316 if ( ! empty($number) && ! $hierarchical && empty( $child_of ) && '' === $parent ) {
1318 $limits = 'LIMIT ' . $offset . ',' . $number;
1320 $limits = 'LIMIT ' . $number;
1325 if ( !empty($search) ) {
1326 $search = like_escape($search);
1327 $where .= $wpdb->prepare( " AND (t.name LIKE %s)", '%' . $search . '%');
1331 switch ( $fields ) {
1333 $selects = array('t.*', 'tt.*');
1337 $selects = array('t.term_id', 'tt.parent', 'tt.count');
1340 $selects = array('t.term_id', 'tt.parent', 'tt.count', 't.name');
1345 $selects = array('COUNT(*)');
1350 $fields = implode(', ', apply_filters( 'get_terms_fields', $selects, $args ));
1352 $join = "INNER JOIN $wpdb->term_taxonomy AS tt ON t.term_id = tt.term_id";
1354 $pieces = array( 'fields', 'join', 'where', 'orderby', 'order', 'limits' );
1355 $clauses = apply_filters( 'terms_clauses', compact( $pieces ), $taxonomies, $args );
1356 foreach ( $pieces as $piece )
1357 $$piece = isset( $clauses[ $piece ] ) ? $clauses[ $piece ] : '';
1359 $query = "SELECT $fields FROM $wpdb->terms AS t $join WHERE $where $orderby $order $limits";
1363 if ( 'count' == $fields ) {
1364 $term_count = $wpdb->get_var($query);
1368 $terms = $wpdb->get_results($query);
1369 if ( 'all' == $fields ) {
1370 update_term_cache($terms);
1373 if ( empty($terms) ) {
1374 wp_cache_add( $cache_key, array(), 'terms', 86400 ); // one day
1375 $terms = apply_filters('get_terms', array(), $taxonomies, $args);
1380 $children = _get_term_hierarchy($taxonomies[0]);
1381 if ( ! empty($children) )
1382 $terms = & _get_term_children($child_of, $terms, $taxonomies[0]);
1385 // Update term counts to include children.
1386 if ( $pad_counts && 'all' == $fields )
1387 _pad_term_counts($terms, $taxonomies[0]);
1389 // Make sure we show empty categories that have children.
1390 if ( $hierarchical && $hide_empty && is_array($terms) ) {
1391 foreach ( $terms as $k => $term ) {
1392 if ( ! $term->count ) {
1393 $children = _get_term_children($term->term_id, $terms, $taxonomies[0]);
1394 if ( is_array($children) )
1395 foreach ( $children as $child )
1396 if ( $child->count )
1399 // It really is empty
1407 if ( 'id=>parent' == $fields ) {
1408 while ( $term = array_shift($terms) )
1409 $_terms[$term->term_id] = $term->parent;
1411 } elseif ( 'ids' == $fields ) {
1412 while ( $term = array_shift($terms) )
1413 $_terms[] = $term->term_id;
1415 } elseif ( 'names' == $fields ) {
1416 while ( $term = array_shift($terms) )
1417 $_terms[] = $term->name;
1421 if ( 0 < $number && intval(@count($terms)) > $number ) {
1422 $terms = array_slice($terms, $offset, $number);
1425 wp_cache_add( $cache_key, $terms, 'terms', 86400 ); // one day
1427 $terms = apply_filters('get_terms', $terms, $taxonomies, $args);
1432 * Check if Term exists.
1434 * Returns the index of a defined term, or 0 (false) if the term doesn't exist.
1436 * Formerly is_term(), introduced in 2.3.0.
1438 * @package WordPress
1439 * @subpackage Taxonomy
1444 * @param int|string $term The term to check
1445 * @param string $taxonomy The taxonomy name to use
1446 * @param int $parent ID of parent term under which to confine the exists search.
1447 * @return mixed Get the term id or Term Object, if exists.
1449 function term_exists($term, $taxonomy = '', $parent = 0) {
1452 $select = "SELECT term_id FROM $wpdb->terms as t WHERE ";
1453 $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 ";
1455 if ( is_int($term) ) {
1458 $where = 't.term_id = %d';
1459 if ( !empty($taxonomy) )
1460 return $wpdb->get_row( $wpdb->prepare( $tax_select . $where . " AND tt.taxonomy = %s", $term, $taxonomy ), ARRAY_A );
1462 return $wpdb->get_var( $wpdb->prepare( $select . $where, $term ) );
1465 $term = trim( stripslashes( $term ) );
1467 if ( '' === $slug = sanitize_title($term) )
1470 $where = 't.slug = %s';
1471 $else_where = 't.name = %s';
1472 $where_fields = array($slug);
1473 $else_where_fields = array($term);
1474 if ( !empty($taxonomy) ) {
1475 $parent = (int) $parent;
1476 if ( $parent > 0 ) {
1477 $where_fields[] = $parent;
1478 $else_where_fields[] = $parent;
1479 $where .= ' AND tt.parent = %d';
1480 $else_where .= ' AND tt.parent = %d';
1483 $where_fields[] = $taxonomy;
1484 $else_where_fields[] = $taxonomy;
1486 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) )
1489 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);
1492 if ( $result = $wpdb->get_var( $wpdb->prepare("SELECT term_id FROM $wpdb->terms as t WHERE $where", $where_fields) ) )
1495 return $wpdb->get_var( $wpdb->prepare("SELECT term_id FROM $wpdb->terms as t WHERE $else_where", $else_where_fields) );
1499 * Sanitize Term all fields.
1501 * Relies on sanitize_term_field() to sanitize the term. The difference is that
1502 * this function will sanitize <strong>all</strong> fields. The context is based
1503 * on sanitize_term_field().
1505 * The $term is expected to be either an array or an object.
1507 * @package WordPress
1508 * @subpackage Taxonomy
1511 * @uses sanitize_term_field Used to sanitize all fields in a term
1513 * @param array|object $term The term to check
1514 * @param string $taxonomy The taxonomy name to use
1515 * @param string $context Default is 'display'.
1516 * @return array|object Term with all fields sanitized
1518 function sanitize_term($term, $taxonomy, $context = 'display') {
1520 if ( 'raw' == $context )
1523 $fields = array('term_id', 'name', 'description', 'slug', 'count', 'parent', 'term_group');
1526 if ( is_object($term) )
1529 $term_id = $do_object ? $term->term_id : (isset($term['term_id']) ? $term['term_id'] : 0);
1531 foreach ( (array) $fields as $field ) {
1533 if ( isset($term->$field) )
1534 $term->$field = sanitize_term_field($field, $term->$field, $term_id, $taxonomy, $context);
1536 if ( isset($term[$field]) )
1537 $term[$field] = sanitize_term_field($field, $term[$field], $term_id, $taxonomy, $context);
1542 $term->filter = $context;
1544 $term['filter'] = $context;
1550 * Cleanse the field value in the term based on the context.
1552 * Passing a term field value through the function should be assumed to have
1553 * cleansed the value for whatever context the term field is going to be used.
1555 * If no context or an unsupported context is given, then default filters will
1558 * There are enough filters for each context to support a custom filtering
1559 * without creating your own filter function. Simply create a function that
1560 * hooks into the filter you need.
1562 * @package WordPress
1563 * @subpackage Taxonomy
1568 * @param string $field Term field to sanitize
1569 * @param string $value Search for this term value
1570 * @param int $term_id Term ID
1571 * @param string $taxonomy Taxonomy Name
1572 * @param string $context Either edit, db, display, attribute, or js.
1573 * @return mixed sanitized field
1575 function sanitize_term_field($field, $value, $term_id, $taxonomy, $context) {
1576 if ( 'parent' == $field || 'term_id' == $field || 'count' == $field || 'term_group' == $field ) {
1577 $value = (int) $value;
1582 if ( 'raw' == $context )
1585 if ( 'edit' == $context ) {
1586 $value = apply_filters("edit_term_{$field}", $value, $term_id, $taxonomy);
1587 $value = apply_filters("edit_{$taxonomy}_{$field}", $value, $term_id);
1588 if ( 'description' == $field )
1589 $value = esc_html($value); // textarea_escaped
1591 $value = esc_attr($value);
1592 } else if ( 'db' == $context ) {
1593 $value = apply_filters("pre_term_{$field}", $value, $taxonomy);
1594 $value = apply_filters("pre_{$taxonomy}_{$field}", $value);
1595 // Back compat filters
1596 if ( 'slug' == $field )
1597 $value = apply_filters('pre_category_nicename', $value);
1599 } else if ( 'rss' == $context ) {
1600 $value = apply_filters("term_{$field}_rss", $value, $taxonomy);
1601 $value = apply_filters("{$taxonomy}_{$field}_rss", $value);
1603 // Use display filters by default.
1604 $value = apply_filters("term_{$field}", $value, $term_id, $taxonomy, $context);
1605 $value = apply_filters("{$taxonomy}_{$field}", $value, $term_id, $context);
1608 if ( 'attribute' == $context )
1609 $value = esc_attr($value);
1610 else if ( 'js' == $context )
1611 $value = esc_js($value);
1617 * Count how many terms are in Taxonomy.
1619 * Default $args is 'hide_empty' which can be 'hide_empty=true' or array('hide_empty' => true).
1621 * @package WordPress
1622 * @subpackage Taxonomy
1626 * @uses wp_parse_args() Turns strings into arrays and merges defaults into an array.
1628 * @param string $taxonomy Taxonomy name
1629 * @param array|string $args Overwrite defaults. See get_terms()
1630 * @return int How many terms are in $taxonomy
1632 function wp_count_terms( $taxonomy, $args = array() ) {
1633 $defaults = array('hide_empty' => false);
1634 $args = wp_parse_args($args, $defaults);
1636 // backwards compatibility
1637 if ( isset($args['ignore_empty']) ) {
1638 $args['hide_empty'] = $args['ignore_empty'];
1639 unset($args['ignore_empty']);
1642 $args['fields'] = 'count';
1644 return get_terms($taxonomy, $args);
1648 * Will unlink the object from the taxonomy or taxonomies.
1650 * Will remove all relationships between the object and any terms in
1651 * a particular taxonomy or taxonomies. Does not remove the term or
1654 * @package WordPress
1655 * @subpackage Taxonomy
1659 * @param int $object_id The term Object Id that refers to the term
1660 * @param string|array $taxonomies List of Taxonomy Names or single Taxonomy name.
1662 function wp_delete_object_term_relationships( $object_id, $taxonomies ) {
1665 $object_id = (int) $object_id;
1667 if ( !is_array($taxonomies) )
1668 $taxonomies = array($taxonomies);
1670 foreach ( (array) $taxonomies as $taxonomy ) {
1671 $tt_ids = wp_get_object_terms($object_id, $taxonomy, array('fields' => 'tt_ids'));
1672 $in_tt_ids = "'" . implode("', '", $tt_ids) . "'";
1673 do_action( 'delete_term_relationships', $object_id, $tt_ids );
1674 $wpdb->query( $wpdb->prepare("DELETE FROM $wpdb->term_relationships WHERE object_id = %d AND term_taxonomy_id IN ($in_tt_ids)", $object_id) );
1675 do_action( 'deleted_term_relationships', $object_id, $tt_ids );
1676 wp_update_term_count($tt_ids, $taxonomy);
1681 * Removes a term from the database.
1683 * If the term is a parent of other terms, then the children will be updated to
1684 * that term's parent.
1686 * The $args 'default' will only override the terms found, if there is only one
1687 * term found. Any other and the found terms are used.
1689 * The $args 'force_default' will force the term supplied as default to be
1690 * assigned even if the object was not going to be termless
1691 * @package WordPress
1692 * @subpackage Taxonomy
1696 * @uses do_action() Calls both 'delete_term' and 'delete_$taxonomy' action
1697 * hooks, passing term object, term id. 'delete_term' gets an additional
1698 * parameter with the $taxonomy parameter.
1700 * @param int $term Term ID
1701 * @param string $taxonomy Taxonomy Name
1702 * @param array|string $args Optional. Change 'default' term id and override found term ids.
1703 * @return bool|WP_Error Returns false if not term; true if completes delete action.
1705 function wp_delete_term( $term, $taxonomy, $args = array() ) {
1708 $term = (int) $term;
1710 if ( ! $ids = term_exists($term, $taxonomy) )
1712 if ( is_wp_error( $ids ) )
1715 $tt_id = $ids['term_taxonomy_id'];
1717 $defaults = array();
1719 if ( 'category' == $taxonomy ) {
1720 $defaults['default'] = get_option( 'default_category' );
1721 if ( $defaults['default'] == $term )
1722 return 0; // Don't delete the default category
1725 $args = wp_parse_args($args, $defaults);
1726 extract($args, EXTR_SKIP);
1728 if ( isset( $default ) ) {
1729 $default = (int) $default;
1730 if ( ! term_exists($default, $taxonomy) )
1734 // Update children to point to new parent
1735 if ( is_taxonomy_hierarchical($taxonomy) ) {
1736 $term_obj = get_term($term, $taxonomy);
1737 if ( is_wp_error( $term_obj ) )
1739 $parent = $term_obj->parent;
1741 $edit_tt_ids = $wpdb->get_col( "SELECT `term_taxonomy_id` FROM $wpdb->term_taxonomy WHERE `parent` = " . (int)$term_obj->term_id );
1742 do_action( 'edit_term_taxonomies', $edit_tt_ids );
1743 $wpdb->update( $wpdb->term_taxonomy, compact( 'parent' ), array( 'parent' => $term_obj->term_id) + compact( 'taxonomy' ) );
1744 do_action( 'edited_term_taxonomies', $edit_tt_ids );
1747 $objects = $wpdb->get_col( $wpdb->prepare( "SELECT object_id FROM $wpdb->term_relationships WHERE term_taxonomy_id = %d", $tt_id ) );
1749 foreach ( (array) $objects as $object ) {
1750 $terms = wp_get_object_terms($object, $taxonomy, array('fields' => 'ids', 'orderby' => 'none'));
1751 if ( 1 == count($terms) && isset($default) ) {
1752 $terms = array($default);
1754 $terms = array_diff($terms, array($term));
1755 if (isset($default) && isset($force_default) && $force_default)
1756 $terms = array_merge($terms, array($default));
1758 $terms = array_map('intval', $terms);
1759 wp_set_object_terms($object, $terms, $taxonomy);
1762 // Clean the relationship caches for all object types using this term
1763 $tax_object = get_taxonomy( $taxonomy );
1764 foreach ( $tax_object->object_type as $object_type )
1765 clean_object_term_cache( $objects, $object_type );
1767 do_action( 'delete_term_taxonomy', $tt_id );
1768 $wpdb->query( $wpdb->prepare( "DELETE FROM $wpdb->term_taxonomy WHERE term_taxonomy_id = %d", $tt_id ) );
1769 do_action( 'deleted_term_taxonomy', $tt_id );
1771 // Delete the term if no taxonomies use it.
1772 if ( !$wpdb->get_var( $wpdb->prepare( "SELECT COUNT(*) FROM $wpdb->term_taxonomy WHERE term_id = %d", $term) ) )
1773 $wpdb->query( $wpdb->prepare( "DELETE FROM $wpdb->terms WHERE term_id = %d", $term) );
1775 clean_term_cache($term, $taxonomy);
1777 do_action('delete_term', $term, $tt_id, $taxonomy);
1778 do_action("delete_$taxonomy", $term, $tt_id);
1784 * Deletes one existing category.
1787 * @uses wp_delete_term()
1789 * @param int $cat_ID
1790 * @return mixed Returns true if completes delete action; false if term doesn't exist;
1791 * Zero on attempted deletion of default Category; WP_Error object is also a possibility.
1793 function wp_delete_category( $cat_ID ) {
1794 return wp_delete_term( $cat_ID, 'category' );
1798 * Retrieves the terms associated with the given object(s), in the supplied taxonomies.
1800 * The following information has to do the $args parameter and for what can be
1801 * contained in the string or array of that parameter, if it exists.
1803 * The first argument is called, 'orderby' and has the default value of 'name'.
1804 * The other value that is supported is 'count'.
1806 * The second argument is called, 'order' and has the default value of 'ASC'.
1807 * The only other value that will be acceptable is 'DESC'.
1809 * The final argument supported is called, 'fields' and has the default value of
1810 * 'all'. There are multiple other options that can be used instead. Supported
1811 * values are as follows: 'all', 'ids', 'names', and finally
1812 * 'all_with_object_id'.
1814 * The fields argument also decides what will be returned. If 'all' or
1815 * 'all_with_object_id' is chosen or the default kept intact, then all matching
1816 * terms objects will be returned. If either 'ids' or 'names' is used, then an
1817 * array of all matching term ids or term names will be returned respectively.
1819 * @package WordPress
1820 * @subpackage Taxonomy
1824 * @param int|array $object_ids The ID(s) of the object(s) to retrieve.
1825 * @param string|array $taxonomies The taxonomies to retrieve terms from.
1826 * @param array|string $args Change what is returned
1827 * @return array|WP_Error The requested term data or empty array if no terms found. WP_Error if $taxonomy does not exist.
1829 function wp_get_object_terms($object_ids, $taxonomies, $args = array()) {
1832 if ( !is_array($taxonomies) )
1833 $taxonomies = array($taxonomies);
1835 foreach ( (array) $taxonomies as $taxonomy ) {
1836 if ( ! taxonomy_exists($taxonomy) )
1837 return new WP_Error('invalid_taxonomy', __('Invalid Taxonomy'));
1840 if ( !is_array($object_ids) )
1841 $object_ids = array($object_ids);
1842 $object_ids = array_map('intval', $object_ids);
1844 $defaults = array('orderby' => 'name', 'order' => 'ASC', 'fields' => 'all');
1845 $args = wp_parse_args( $args, $defaults );
1848 if ( count($taxonomies) > 1 ) {
1849 foreach ( $taxonomies as $index => $taxonomy ) {
1850 $t = get_taxonomy($taxonomy);
1851 if ( isset($t->args) && is_array($t->args) && $args != array_merge($args, $t->args) ) {
1852 unset($taxonomies[$index]);
1853 $terms = array_merge($terms, wp_get_object_terms($object_ids, $taxonomy, array_merge($args, $t->args)));
1857 $t = get_taxonomy($taxonomies[0]);
1858 if ( isset($t->args) && is_array($t->args) )
1859 $args = array_merge($args, $t->args);
1862 extract($args, EXTR_SKIP);
1864 if ( 'count' == $orderby )
1865 $orderby = 'tt.count';
1866 else if ( 'name' == $orderby )
1867 $orderby = 't.name';
1868 else if ( 'slug' == $orderby )
1869 $orderby = 't.slug';
1870 else if ( 'term_group' == $orderby )
1871 $orderby = 't.term_group';
1872 else if ( 'term_order' == $orderby )
1873 $orderby = 'tr.term_order';
1874 else if ( 'none' == $orderby ) {
1878 $orderby = 't.term_id';
1881 // tt_ids queries can only be none or tr.term_taxonomy_id
1882 if ( ('tt_ids' == $fields) && !empty($orderby) )
1883 $orderby = 'tr.term_taxonomy_id';
1885 if ( !empty($orderby) )
1886 $orderby = "ORDER BY $orderby";
1888 $taxonomies = "'" . implode("', '", $taxonomies) . "'";
1889 $object_ids = implode(', ', $object_ids);
1892 if ( 'all' == $fields )
1893 $select_this = 't.*, tt.*';
1894 else if ( 'ids' == $fields )
1895 $select_this = 't.term_id';
1896 else if ( 'names' == $fields )
1897 $select_this = 't.name';
1898 else if ( 'slugs' == $fields )
1899 $select_this = 't.slug';
1900 else if ( 'all_with_object_id' == $fields )
1901 $select_this = 't.*, tt.*, tr.object_id';
1903 $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";
1905 if ( 'all' == $fields || 'all_with_object_id' == $fields ) {
1906 $terms = array_merge($terms, $wpdb->get_results($query));
1907 update_term_cache($terms);
1908 } else if ( 'ids' == $fields || 'names' == $fields || 'slugs' == $fields ) {
1909 $terms = array_merge($terms, $wpdb->get_col($query));
1910 } else if ( 'tt_ids' == $fields ) {
1911 $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");
1917 return apply_filters('wp_get_object_terms', $terms, $object_ids, $taxonomies, $args);
1921 * Adds a new term to the database. Optionally marks it as an alias of an existing term.
1923 * Error handling is assigned for the nonexistence of the $taxonomy and $term
1924 * parameters before inserting. If both the term id and taxonomy exist
1925 * previously, then an array will be returned that contains the term id and the
1926 * contents of what is returned. The keys of the array are 'term_id' and
1927 * 'term_taxonomy_id' containing numeric values.
1929 * It is assumed that the term does not yet exist or the above will apply. The
1930 * term will be first added to the term table and then related to the taxonomy
1931 * if everything is well. If everything is correct, then several actions will be
1932 * run prior to a filter and then several actions will be run after the filter
1935 * The arguments decide how the term is handled based on the $args parameter.
1936 * The following is a list of the available overrides and the defaults.
1938 * 'alias_of'. There is no default, but if added, expected is the slug that the
1939 * term will be an alias of. Expected to be a string.
1941 * 'description'. There is no default. If exists, will be added to the database
1942 * along with the term. Expected to be a string.
1944 * 'parent'. Expected to be numeric and default is 0 (zero). Will assign value
1945 * of 'parent' to the term.
1947 * 'slug'. Expected to be a string. There is no default.
1949 * If 'slug' argument exists then the slug will be checked to see if it is not
1950 * a valid term. If that check succeeds (it is not a valid term), then it is
1951 * added and the term id is given. If it fails, then a check is made to whether
1952 * the taxonomy is hierarchical and the parent argument is not empty. If the
1953 * second check succeeds, the term will be inserted and the term id will be
1956 * @package WordPress
1957 * @subpackage Taxonomy
1961 * @uses apply_filters() Calls 'pre_insert_term' hook with term and taxonomy as parameters.
1962 * @uses do_action() Calls 'create_term' hook with the term id and taxonomy id as parameters.
1963 * @uses do_action() Calls 'create_$taxonomy' hook with term id and taxonomy id as parameters.
1964 * @uses apply_filters() Calls 'term_id_filter' hook with term id and taxonomy id as parameters.
1965 * @uses do_action() Calls 'created_term' hook with the term id and taxonomy id as parameters.
1966 * @uses do_action() Calls 'created_$taxonomy' hook with term id and taxonomy id as parameters.
1968 * @param string $term The term to add or update.
1969 * @param string $taxonomy The taxonomy to which to add the term
1970 * @param array|string $args Change the values of the inserted term
1971 * @return array|WP_Error The Term ID and Term Taxonomy ID
1973 function wp_insert_term( $term, $taxonomy, $args = array() ) {
1976 if ( ! taxonomy_exists($taxonomy) )
1977 return new WP_Error('invalid_taxonomy', __('Invalid taxonomy'));
1979 $term = apply_filters( 'pre_insert_term', $term, $taxonomy );
1980 if ( is_wp_error( $term ) )
1983 if ( is_int($term) && 0 == $term )
1984 return new WP_Error('invalid_term_id', __('Invalid term ID'));
1986 if ( '' == trim($term) )
1987 return new WP_Error('empty_term_name', __('A name is required for this term'));
1989 $defaults = array( 'alias_of' => '', 'description' => '', 'parent' => 0, 'slug' => '');
1990 $args = wp_parse_args($args, $defaults);
1991 $args['name'] = $term;
1992 $args['taxonomy'] = $taxonomy;
1993 $args = sanitize_term($args, $taxonomy, 'db');
1994 extract($args, EXTR_SKIP);
1996 // expected_slashed ($name)
1997 $name = stripslashes($name);
1998 $description = stripslashes($description);
2001 $slug = sanitize_title($name);
2005 $alias = $wpdb->get_row( $wpdb->prepare( "SELECT term_id, term_group FROM $wpdb->terms WHERE slug = %s", $alias_of) );
2006 if ( $alias->term_group ) {
2007 // The alias we want is already in a group, so let's use that one.
2008 $term_group = $alias->term_group;
2010 // The alias isn't in a group, so let's create a new one and firstly add the alias term to it.
2011 $term_group = $wpdb->get_var("SELECT MAX(term_group) FROM $wpdb->terms") + 1;
2012 do_action( 'edit_terms', $alias->term_id );
2013 $wpdb->update($wpdb->terms, compact('term_group'), array('term_id' => $alias->term_id) );
2014 do_action( 'edited_terms', $alias->term_id );
2018 if ( $term_id = term_exists($slug) ) {
2019 $existing_term = $wpdb->get_row( $wpdb->prepare( "SELECT name FROM $wpdb->terms WHERE term_id = %d", $term_id), ARRAY_A );
2020 // We've got an existing term in the same taxonomy, which matches the name of the new term:
2021 if ( is_taxonomy_hierarchical($taxonomy) && $existing_term['name'] == $name && $exists = term_exists( (int) $term_id, $taxonomy ) ) {
2022 // Hierarchical, and it matches an existing term, Do not allow same "name" in the same level.
2023 $siblings = get_terms($taxonomy, array('fields' => 'names', 'get' => 'all', 'parent' => (int)$parent) );
2024 if ( in_array($name, $siblings) ) {
2025 return new WP_Error('term_exists', __('A term with the name provided already exists with this parent.'), $exists['term_id']);
2027 $slug = wp_unique_term_slug($slug, (object) $args);
2028 if ( false === $wpdb->insert( $wpdb->terms, compact( 'name', 'slug', 'term_group' ) ) )
2029 return new WP_Error('db_insert_error', __('Could not insert term into the database'), $wpdb->last_error);
2030 $term_id = (int) $wpdb->insert_id;
2032 } elseif ( $existing_term['name'] != $name ) {
2033 // We've got an existing term, with a different name, Create the new term.
2034 $slug = wp_unique_term_slug($slug, (object) $args);
2035 if ( false === $wpdb->insert( $wpdb->terms, compact( 'name', 'slug', 'term_group' ) ) )
2036 return new WP_Error('db_insert_error', __('Could not insert term into the database'), $wpdb->last_error);
2037 $term_id = (int) $wpdb->insert_id;
2038 } elseif ( $exists = term_exists( (int) $term_id, $taxonomy ) ) {
2039 // Same name, same slug.
2040 return new WP_Error('term_exists', __('A term with the name provided already exists.'), $exists['term_id']);
2043 // This term does not exist at all in the database, Create it.
2044 $slug = wp_unique_term_slug($slug, (object) $args);
2045 if ( false === $wpdb->insert( $wpdb->terms, compact( 'name', 'slug', 'term_group' ) ) )
2046 return new WP_Error('db_insert_error', __('Could not insert term into the database'), $wpdb->last_error);
2047 $term_id = (int) $wpdb->insert_id;
2050 // Seems unreachable, However, Is used in the case that a term name is provided, which sanitizes to an empty string.
2051 if ( empty($slug) ) {
2052 $slug = sanitize_title($slug, $term_id);
2053 do_action( 'edit_terms', $term_id );
2054 $wpdb->update( $wpdb->terms, compact( 'slug' ), compact( 'term_id' ) );
2055 do_action( 'edited_terms', $term_id );
2058 $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 ) );
2060 if ( !empty($tt_id) )
2061 return array('term_id' => $term_id, 'term_taxonomy_id' => $tt_id);
2063 $wpdb->insert( $wpdb->term_taxonomy, compact( 'term_id', 'taxonomy', 'description', 'parent') + array( 'count' => 0 ) );
2064 $tt_id = (int) $wpdb->insert_id;
2066 do_action("create_term", $term_id, $tt_id, $taxonomy);
2067 do_action("create_$taxonomy", $term_id, $tt_id);
2069 $term_id = apply_filters('term_id_filter', $term_id, $tt_id);
2071 clean_term_cache($term_id, $taxonomy);
2073 do_action("created_term", $term_id, $tt_id, $taxonomy);
2074 do_action("created_$taxonomy", $term_id, $tt_id);
2076 return array('term_id' => $term_id, 'term_taxonomy_id' => $tt_id);
2080 * Create Term and Taxonomy Relationships.
2082 * Relates an object (post, link etc) to a term and taxonomy type. Creates the
2083 * term and taxonomy relationship if it doesn't already exist. Creates a term if
2084 * it doesn't exist (using the slug).
2086 * A relationship means that the term is grouped in or belongs to the taxonomy.
2087 * A term has no meaning until it is given context by defining which taxonomy it
2090 * @package WordPress
2091 * @subpackage Taxonomy
2095 * @param int $object_id The object to relate to.
2096 * @param array|int|string $terms The slug or id of the term, will replace all existing
2097 * related terms in this taxonomy.
2098 * @param array|string $taxonomy The context in which to relate the term to the object.
2099 * @param bool $append If false will delete difference of terms.
2100 * @return array|WP_Error Affected Term IDs
2102 function wp_set_object_terms($object_id, $terms, $taxonomy, $append = false) {
2105 $object_id = (int) $object_id;
2107 if ( ! taxonomy_exists($taxonomy) )
2108 return new WP_Error('invalid_taxonomy', __('Invalid Taxonomy'));
2110 if ( !is_array($terms) )
2111 $terms = array($terms);
2114 $old_tt_ids = wp_get_object_terms($object_id, $taxonomy, array('fields' => 'tt_ids', 'orderby' => 'none'));
2116 $old_tt_ids = array();
2119 $term_ids = array();
2120 $new_tt_ids = array();
2122 foreach ( (array) $terms as $term) {
2123 if ( !strlen(trim($term)) )
2126 if ( !$term_info = term_exists($term, $taxonomy) ) {
2127 // Skip if a non-existent term ID is passed.
2128 if ( is_int($term) )
2130 $term_info = wp_insert_term($term, $taxonomy);
2132 if ( is_wp_error($term_info) )
2134 $term_ids[] = $term_info['term_id'];
2135 $tt_id = $term_info['term_taxonomy_id'];
2138 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 ) ) )
2140 do_action( 'add_term_relationship', $object_id, $tt_id );
2141 $wpdb->insert( $wpdb->term_relationships, array( 'object_id' => $object_id, 'term_taxonomy_id' => $tt_id ) );
2142 do_action( 'added_term_relationship', $object_id, $tt_id );
2143 $new_tt_ids[] = $tt_id;
2147 wp_update_term_count( $new_tt_ids, $taxonomy );
2150 $delete_terms = array_diff($old_tt_ids, $tt_ids);
2151 if ( $delete_terms ) {
2152 $in_delete_terms = "'" . implode("', '", $delete_terms) . "'";
2153 do_action( 'delete_term_relationships', $object_id, $delete_terms );
2154 $wpdb->query( $wpdb->prepare("DELETE FROM $wpdb->term_relationships WHERE object_id = %d AND term_taxonomy_id IN ($in_delete_terms)", $object_id) );
2155 do_action( 'deleted_term_relationships', $object_id, $delete_terms );
2156 wp_update_term_count($delete_terms, $taxonomy);
2160 $t = get_taxonomy($taxonomy);
2161 if ( ! $append && isset($t->sort) && $t->sort ) {
2164 $final_tt_ids = wp_get_object_terms($object_id, $taxonomy, array('fields' => 'tt_ids'));
2165 foreach ( $tt_ids as $tt_id )
2166 if ( in_array($tt_id, $final_tt_ids) )
2167 $values[] = $wpdb->prepare( "(%d, %d, %d)", $object_id, $tt_id, ++$term_order);
2169 $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)");
2172 do_action('set_object_terms', $object_id, $terms, $tt_ids, $taxonomy, $append, $old_tt_ids);
2177 * Will make slug unique, if it isn't already.
2179 * The $slug has to be unique global to every taxonomy, meaning that one
2180 * taxonomy term can't have a matching slug with another taxonomy term. Each
2181 * slug has to be globally unique for every taxonomy.
2183 * The way this works is that if the taxonomy that the term belongs to is
2184 * hierarchical and has a parent, it will append that parent to the $slug.
2186 * If that still doesn't return an unique slug, then it try to append a number
2187 * until it finds a number that is truly unique.
2189 * The only purpose for $term is for appending a parent, if one exists.
2191 * @package WordPress
2192 * @subpackage Taxonomy
2196 * @param string $slug The string that will be tried for a unique slug
2197 * @param object $term The term object that the $slug will belong too
2198 * @return string Will return a true unique slug.
2200 function wp_unique_term_slug($slug, $term) {
2203 if ( ! term_exists( $slug ) )
2206 // If the taxonomy supports hierarchy and the term has a parent, make the slug unique
2207 // by incorporating parent slugs.
2208 if ( is_taxonomy_hierarchical($term->taxonomy) && !empty($term->parent) ) {
2209 $the_parent = $term->parent;
2210 while ( ! empty($the_parent) ) {
2211 $parent_term = get_term($the_parent, $term->taxonomy);
2212 if ( is_wp_error($parent_term) || empty($parent_term) )
2214 $slug .= '-' . $parent_term->slug;
2215 if ( ! term_exists( $slug ) )
2218 if ( empty($parent_term->parent) )
2220 $the_parent = $parent_term->parent;
2224 // If we didn't get a unique slug, try appending a number to make it unique.
2225 if ( !empty($args['term_id']) )
2226 $query = $wpdb->prepare( "SELECT slug FROM $wpdb->terms WHERE slug = %s AND term_id != %d", $slug, $args['term_id'] );
2228 $query = $wpdb->prepare( "SELECT slug FROM $wpdb->terms WHERE slug = %s", $slug );
2230 if ( $wpdb->get_var( $query ) ) {
2233 $alt_slug = $slug . "-$num";
2235 $slug_check = $wpdb->get_var( $wpdb->prepare( "SELECT slug FROM $wpdb->terms WHERE slug = %s", $alt_slug ) );
2236 } while ( $slug_check );
2244 * Update term based on arguments provided.
2246 * The $args will indiscriminately override all values with the same field name.
2247 * Care must be taken to not override important information need to update or
2248 * update will fail (or perhaps create a new term, neither would be acceptable).
2250 * Defaults will set 'alias_of', 'description', 'parent', and 'slug' if not
2251 * defined in $args already.
2253 * 'alias_of' will create a term group, if it doesn't already exist, and update
2256 * If the 'slug' argument in $args is missing, then the 'name' in $args will be
2257 * used. It should also be noted that if you set 'slug' and it isn't unique then
2258 * a WP_Error will be passed back. If you don't pass any slug, then a unique one
2259 * will be created for you.
2261 * For what can be overrode in $args, check the term scheme can contain and stay
2262 * away from the term keys.
2264 * @package WordPress
2265 * @subpackage Taxonomy
2269 * @uses do_action() Will call both 'edit_term' and 'edit_$taxonomy' twice.
2270 * @uses apply_filters() Will call the 'term_id_filter' filter and pass the term
2271 * id and taxonomy id.
2273 * @param int $term_id The ID of the term
2274 * @param string $taxonomy The context in which to relate the term to the object.
2275 * @param array|string $args Overwrite term field values
2276 * @return array|WP_Error Returns Term ID and Taxonomy Term ID
2278 function wp_update_term( $term_id, $taxonomy, $args = array() ) {
2281 if ( ! taxonomy_exists($taxonomy) )
2282 return new WP_Error('invalid_taxonomy', __('Invalid taxonomy'));
2284 $term_id = (int) $term_id;
2286 // First, get all of the original args
2287 $term = get_term ($term_id, $taxonomy, ARRAY_A);
2289 if ( is_wp_error( $term ) )
2292 // Escape data pulled from DB.
2293 $term = add_magic_quotes($term);
2295 // Merge old and new args with new args overwriting old ones.
2296 $args = array_merge($term, $args);
2298 $defaults = array( 'alias_of' => '', 'description' => '', 'parent' => 0, 'slug' => '');
2299 $args = wp_parse_args($args, $defaults);
2300 $args = sanitize_term($args, $taxonomy, 'db');
2301 extract($args, EXTR_SKIP);
2303 // expected_slashed ($name)
2304 $name = stripslashes($name);
2305 $description = stripslashes($description);
2307 if ( '' == trim($name) )
2308 return new WP_Error('empty_term_name', __('A name is required for this term'));
2310 $empty_slug = false;
2311 if ( empty($slug) ) {
2313 $slug = sanitize_title($name);
2317 $alias = $wpdb->get_row( $wpdb->prepare( "SELECT term_id, term_group FROM $wpdb->terms WHERE slug = %s", $alias_of) );
2318 if ( $alias->term_group ) {
2319 // The alias we want is already in a group, so let's use that one.
2320 $term_group = $alias->term_group;
2322 // The alias isn't in a group, so let's create a new one and firstly add the alias term to it.
2323 $term_group = $wpdb->get_var("SELECT MAX(term_group) FROM $wpdb->terms") + 1;
2324 do_action( 'edit_terms', $alias->term_id );
2325 $wpdb->update( $wpdb->terms, compact('term_group'), array( 'term_id' => $alias->term_id ) );
2326 do_action( 'edited_terms', $alias->term_id );
2330 // Check $parent to see if it will cause a hierarchy loop
2331 $parent = apply_filters( 'wp_update_term_parent', $parent, $term_id, $taxonomy, compact( array_keys( $args ) ), $args );
2333 // Check for duplicate slug
2334 $id = $wpdb->get_var( $wpdb->prepare( "SELECT term_id FROM $wpdb->terms WHERE slug = %s", $slug ) );
2335 if ( $id && ($id != $term_id) ) {
2336 // If an empty slug was passed or the parent changed, reset the slug to something unique.
2338 if ( $empty_slug || ( $parent != $term['parent']) )
2339 $slug = wp_unique_term_slug($slug, (object) $args);
2341 return new WP_Error('duplicate_term_slug', sprintf(__('The slug “%s” is already in use by another term'), $slug));
2343 do_action( 'edit_terms', $term_id );
2344 $wpdb->update($wpdb->terms, compact( 'name', 'slug', 'term_group' ), compact( 'term_id' ) );
2345 if ( empty($slug) ) {
2346 $slug = sanitize_title($name, $term_id);
2347 $wpdb->update( $wpdb->terms, compact( 'slug' ), compact( 'term_id' ) );
2349 do_action( 'edited_terms', $term_id );
2351 $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) );
2352 do_action( 'edit_term_taxonomy', $tt_id, $taxonomy );
2353 $wpdb->update( $wpdb->term_taxonomy, compact( 'term_id', 'taxonomy', 'description', 'parent' ), array( 'term_taxonomy_id' => $tt_id ) );
2354 do_action( 'edited_term_taxonomy', $tt_id, $taxonomy );
2356 do_action("edit_term", $term_id, $tt_id, $taxonomy);
2357 do_action("edit_$taxonomy", $term_id, $tt_id);
2359 $term_id = apply_filters('term_id_filter', $term_id, $tt_id);
2361 clean_term_cache($term_id, $taxonomy);
2363 do_action("edited_term", $term_id, $tt_id, $taxonomy);
2364 do_action("edited_$taxonomy", $term_id, $tt_id);
2366 return array('term_id' => $term_id, 'term_taxonomy_id' => $tt_id);
2370 * Enable or disable term counting.
2374 * @param bool $defer Optional. Enable if true, disable if false.
2375 * @return bool Whether term counting is enabled or disabled.
2377 function wp_defer_term_counting($defer=null) {
2378 static $_defer = false;
2380 if ( is_bool($defer) ) {
2382 // flush any deferred counts
2384 wp_update_term_count( null, null, true );
2391 * Updates the amount of terms in taxonomy.
2393 * If there is a taxonomy callback applied, then it will be called for updating
2396 * The default action is to count what the amount of terms have the relationship
2397 * of term ID. Once that is done, then update the database.
2399 * @package WordPress
2400 * @subpackage Taxonomy
2404 * @param int|array $terms The term_taxonomy_id of the terms
2405 * @param string $taxonomy The context of the term.
2406 * @return bool If no terms will return false, and if successful will return true.
2408 function wp_update_term_count( $terms, $taxonomy, $do_deferred=false ) {
2409 static $_deferred = array();
2411 if ( $do_deferred ) {
2412 foreach ( (array) array_keys($_deferred) as $tax ) {
2413 wp_update_term_count_now( $_deferred[$tax], $tax );
2414 unset( $_deferred[$tax] );
2418 if ( empty($terms) )
2421 if ( !is_array($terms) )
2422 $terms = array($terms);
2424 if ( wp_defer_term_counting() ) {
2425 if ( !isset($_deferred[$taxonomy]) )
2426 $_deferred[$taxonomy] = array();
2427 $_deferred[$taxonomy] = array_unique( array_merge($_deferred[$taxonomy], $terms) );
2431 return wp_update_term_count_now( $terms, $taxonomy );
2435 * Perform term count update immediately.
2439 * @param array $terms The term_taxonomy_id of terms to update.
2440 * @param string $taxonomy The context of the term.
2441 * @return bool Always true when complete.
2443 function wp_update_term_count_now( $terms, $taxonomy ) {
2446 $terms = array_map('intval', $terms);
2448 $taxonomy = get_taxonomy($taxonomy);
2449 if ( !empty($taxonomy->update_count_callback) ) {
2450 call_user_func($taxonomy->update_count_callback, $terms, $taxonomy);
2452 $object_types = (array) $taxonomy->object_type;
2453 foreach ( $object_types as &$object_type ) {
2454 if ( 0 === strpos( $object_type, 'attachment:' ) )
2455 list( $object_type ) = explode( ':', $object_type );
2458 if ( $object_types == array_filter( $object_types, 'post_type_exists' ) ) {
2459 // Only post types are attached to this taxonomy
2460 _update_post_term_count( $terms, $taxonomy );
2462 // Default count updater
2463 _update_generic_term_count( $terms, $taxonomy );
2467 clean_term_cache($terms, '', false);
2478 * Removes the taxonomy relationship to terms from the cache.
2480 * Will remove the entire taxonomy relationship containing term $object_id. The
2481 * term IDs have to exist within the taxonomy $object_type for the deletion to
2484 * @package WordPress
2485 * @subpackage Taxonomy
2488 * @see get_object_taxonomies() for more on $object_type
2489 * @uses do_action() Will call action hook named, 'clean_object_term_cache' after completion.
2490 * Passes, function params in same order.
2492 * @param int|array $object_ids Single or list of term object ID(s)
2493 * @param array|string $object_type The taxonomy object type
2495 function clean_object_term_cache($object_ids, $object_type) {
2496 if ( !is_array($object_ids) )
2497 $object_ids = array($object_ids);
2499 foreach ( $object_ids as $id )
2500 foreach ( get_object_taxonomies($object_type) as $taxonomy )
2501 wp_cache_delete($id, "{$taxonomy}_relationships");
2503 do_action('clean_object_term_cache', $object_ids, $object_type);
2508 * Will remove all of the term ids from the cache.
2510 * @package WordPress
2511 * @subpackage Taxonomy
2515 * @param int|array $ids Single or list of Term IDs
2516 * @param string $taxonomy Can be empty and will assume tt_ids, else will use for context.
2517 * @param bool $clean_taxonomy Whether to clean taxonomy wide caches (true), or just individual term object caches (false). Default is true.
2519 function clean_term_cache($ids, $taxonomy = '', $clean_taxonomy = true) {
2521 static $cleaned = array();
2523 if ( !is_array($ids) )
2526 $taxonomies = array();
2527 // If no taxonomy, assume tt_ids.
2528 if ( empty($taxonomy) ) {
2529 $tt_ids = array_map('intval', $ids);
2530 $tt_ids = implode(', ', $tt_ids);
2531 $terms = $wpdb->get_results("SELECT term_id, taxonomy FROM $wpdb->term_taxonomy WHERE term_taxonomy_id IN ($tt_ids)");
2533 foreach ( (array) $terms as $term ) {
2534 $taxonomies[] = $term->taxonomy;
2535 $ids[] = $term->term_id;
2536 wp_cache_delete($term->term_id, $term->taxonomy);
2538 $taxonomies = array_unique($taxonomies);
2540 $taxonomies = array($taxonomy);
2541 foreach ( $taxonomies as $taxonomy ) {
2542 foreach ( $ids as $id ) {
2543 wp_cache_delete($id, $taxonomy);
2548 foreach ( $taxonomies as $taxonomy ) {
2549 if ( isset($cleaned[$taxonomy]) )
2551 $cleaned[$taxonomy] = true;
2553 if ( $clean_taxonomy ) {
2554 wp_cache_delete('all_ids', $taxonomy);
2555 wp_cache_delete('get', $taxonomy);
2556 delete_option("{$taxonomy}_children");
2557 // Regenerate {$taxonomy}_children
2558 _get_term_hierarchy($taxonomy);
2561 do_action('clean_term_cache', $ids, $taxonomy);
2564 wp_cache_set('last_changed', time(), 'terms');
2569 * Retrieves the taxonomy relationship to the term object id.
2571 * @package WordPress
2572 * @subpackage Taxonomy
2575 * @uses wp_cache_get() Retrieves taxonomy relationship from cache
2577 * @param int|array $id Term object ID
2578 * @param string $taxonomy Taxonomy Name
2579 * @return bool|array Empty array if $terms found, but not $taxonomy. False if nothing is in cache for $taxonomy and $id.
2581 function &get_object_term_cache($id, $taxonomy) {
2582 $cache = wp_cache_get($id, "{$taxonomy}_relationships");
2588 * Updates the cache for Term ID(s).
2590 * Will only update the cache for terms not already cached.
2592 * The $object_ids expects that the ids be separated by commas, if it is a
2595 * It should be noted that update_object_term_cache() is very time extensive. It
2596 * is advised that the function is not called very often or at least not for a
2597 * lot of terms that exist in a lot of taxonomies. The amount of time increases
2598 * for each term and it also increases for each taxonomy the term belongs to.
2600 * @package WordPress
2601 * @subpackage Taxonomy
2603 * @uses wp_get_object_terms() Used to get terms from the database to update
2605 * @param string|array $object_ids Single or list of term object ID(s)
2606 * @param array|string $object_type The taxonomy object type
2607 * @return null|bool Null value is given with empty $object_ids. False if
2609 function update_object_term_cache($object_ids, $object_type) {
2610 if ( empty($object_ids) )
2613 if ( !is_array($object_ids) )
2614 $object_ids = explode(',', $object_ids);
2616 $object_ids = array_map('intval', $object_ids);
2618 $taxonomies = get_object_taxonomies($object_type);
2621 foreach ( (array) $object_ids as $id ) {
2622 foreach ( $taxonomies as $taxonomy ) {
2623 if ( false === wp_cache_get($id, "{$taxonomy}_relationships") ) {
2630 if ( empty( $ids ) )
2633 $terms = wp_get_object_terms($ids, $taxonomies, array('fields' => 'all_with_object_id'));
2635 $object_terms = array();
2636 foreach ( (array) $terms as $term )
2637 $object_terms[$term->object_id][$term->taxonomy][$term->term_id] = $term;
2639 foreach ( $ids as $id ) {
2640 foreach ( $taxonomies as $taxonomy ) {
2641 if ( ! isset($object_terms[$id][$taxonomy]) ) {
2642 if ( !isset($object_terms[$id]) )
2643 $object_terms[$id] = array();
2644 $object_terms[$id][$taxonomy] = array();
2649 foreach ( $object_terms as $id => $value ) {
2650 foreach ( $value as $taxonomy => $terms ) {
2651 wp_cache_set($id, $terms, "{$taxonomy}_relationships");
2658 * Updates Terms to Taxonomy in cache.
2660 * @package WordPress
2661 * @subpackage Taxonomy
2664 * @param array $terms List of Term objects to change
2665 * @param string $taxonomy Optional. Update Term to this taxonomy in cache
2667 function update_term_cache($terms, $taxonomy = '') {
2668 foreach ( (array) $terms as $term ) {
2669 $term_taxonomy = $taxonomy;
2670 if ( empty($term_taxonomy) )
2671 $term_taxonomy = $term->taxonomy;
2673 wp_cache_add($term->term_id, $term, $term_taxonomy);
2683 * Retrieves children of taxonomy as Term IDs.
2685 * @package WordPress
2686 * @subpackage Taxonomy
2690 * @uses update_option() Stores all of the children in "$taxonomy_children"
2691 * option. That is the name of the taxonomy, immediately followed by '_children'.
2693 * @param string $taxonomy Taxonomy Name
2694 * @return array Empty if $taxonomy isn't hierarchical or returns children as Term IDs.
2696 function _get_term_hierarchy($taxonomy) {
2697 if ( !is_taxonomy_hierarchical($taxonomy) )
2699 $children = get_option("{$taxonomy}_children");
2701 if ( is_array($children) )
2703 $children = array();
2704 $terms = get_terms($taxonomy, array('get' => 'all', 'orderby' => 'id', 'fields' => 'id=>parent'));
2705 foreach ( $terms as $term_id => $parent ) {
2707 $children[$parent][] = $term_id;
2709 update_option("{$taxonomy}_children", $children);
2716 * Get the subset of $terms that are descendants of $term_id.
2718 * If $terms is an array of objects, then _get_term_children returns an array of objects.
2719 * If $terms is an array of IDs, then _get_term_children returns an array of IDs.
2721 * @package WordPress
2722 * @subpackage Taxonomy
2726 * @param int $term_id The ancestor term: all returned terms should be descendants of $term_id.
2727 * @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.
2728 * @param string $taxonomy The taxonomy which determines the hierarchy of the terms.
2729 * @return array The subset of $terms that are descendants of $term_id.
2731 function &_get_term_children($term_id, $terms, $taxonomy) {
2732 $empty_array = array();
2733 if ( empty($terms) )
2734 return $empty_array;
2736 $term_list = array();
2737 $has_children = _get_term_hierarchy($taxonomy);
2739 if ( ( 0 != $term_id ) && ! isset($has_children[$term_id]) )
2740 return $empty_array;
2742 foreach ( (array) $terms as $term ) {
2744 if ( !is_object($term) ) {
2745 $term = get_term($term, $taxonomy);
2746 if ( is_wp_error( $term ) )
2751 if ( $term->term_id == $term_id )
2754 if ( $term->parent == $term_id ) {
2756 $term_list[] = $term->term_id;
2758 $term_list[] = $term;
2760 if ( !isset($has_children[$term->term_id]) )
2763 if ( $children = _get_term_children($term->term_id, $terms, $taxonomy) )
2764 $term_list = array_merge($term_list, $children);
2773 * Add count of children to parent count.
2775 * Recalculates term counts by including items from child terms. Assumes all
2776 * relevant children are already in the $terms argument.
2778 * @package WordPress
2779 * @subpackage Taxonomy
2784 * @param array $terms List of Term IDs
2785 * @param string $taxonomy Term Context
2786 * @return null Will break from function if conditions are not met.
2788 function _pad_term_counts(&$terms, $taxonomy) {
2791 // This function only works for hierarchical taxonomies like post categories.
2792 if ( !is_taxonomy_hierarchical( $taxonomy ) )
2795 $term_hier = _get_term_hierarchy($taxonomy);
2797 if ( empty($term_hier) )
2800 $term_items = array();
2802 foreach ( (array) $terms as $key => $term ) {
2803 $terms_by_id[$term->term_id] = & $terms[$key];
2804 $term_ids[$term->term_taxonomy_id] = $term->term_id;
2807 // Get the object and term ids and stick them in a lookup table
2808 $tax_obj = get_taxonomy($taxonomy);
2809 $object_types = esc_sql($tax_obj->object_type);
2810 $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'");
2811 foreach ( $results as $row ) {
2812 $id = $term_ids[$row->term_taxonomy_id];
2813 $term_items[$id][$row->object_id] = isset($term_items[$id][$row->object_id]) ? ++$term_items[$id][$row->object_id] : 1;
2816 // Touch every ancestor's lookup row for each post in each term
2817 foreach ( $term_ids as $term_id ) {
2819 while ( !empty( $terms_by_id[$child] ) && $parent = $terms_by_id[$child]->parent ) {
2820 if ( !empty( $term_items[$term_id] ) )
2821 foreach ( $term_items[$term_id] as $item_id => $touches ) {
2822 $term_items[$parent][$item_id] = isset($term_items[$parent][$item_id]) ? ++$term_items[$parent][$item_id]: 1;
2828 // Transfer the touched cells
2829 foreach ( (array) $term_items as $id => $items )
2830 if ( isset($terms_by_id[$id]) )
2831 $terms_by_id[$id]->count = count($items);
2835 // Default callbacks
2839 * Will update term count based on object types of the current taxonomy.
2841 * Private function for the default callback for post_tag and category
2844 * @package WordPress
2845 * @subpackage Taxonomy
2850 * @param array $terms List of Term taxonomy IDs
2851 * @param object $taxonomy Current taxonomy object of terms
2853 function _update_post_term_count( $terms, $taxonomy ) {
2856 $object_types = (array) $taxonomy->object_type;
2858 foreach ( $object_types as &$object_type )
2859 list( $object_type ) = explode( ':', $object_type );
2861 $object_types = array_unique( $object_types );
2863 if ( false !== ( $check_attachments = array_search( 'attachment', $object_types ) ) ) {
2864 unset( $object_types[ $check_attachments ] );
2865 $check_attachments = true;
2868 if ( $object_types )
2869 $object_types = esc_sql( array_filter( $object_types, 'post_type_exists' ) );
2871 foreach ( (array) $terms as $term ) {
2874 // Attachments can be 'inherit' status, we need to base count off the parent's status if so
2875 if ( $check_attachments )
2876 $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 ) );
2878 if ( $object_types )
2879 $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 ) );
2882 do_action( 'edit_term_taxonomy', $term, $taxonomy );
2883 $wpdb->update( $wpdb->term_taxonomy, compact( 'count' ), array( 'term_taxonomy_id' => $term ) );
2884 do_action( 'edited_term_taxonomy', $term, $taxonomy );
2889 * Will update term count based on number of objects.
2891 * Default callback for the link_category taxonomy.
2893 * @package WordPress
2894 * @subpackage Taxonomy
2898 * @param array $terms List of Term taxonomy IDs
2899 * @param object $taxonomy Current taxonomy object of terms
2901 function _update_generic_term_count( $terms, $taxonomy ) {
2904 foreach ( (array) $terms as $term ) {
2905 $count = $wpdb->get_var( $wpdb->prepare( "SELECT COUNT(*) FROM $wpdb->term_relationships WHERE term_taxonomy_id = %d", $term ) );
2907 do_action( 'edit_term_taxonomy', $term, $taxonomy );
2908 $wpdb->update( $wpdb->term_taxonomy, compact( 'count' ), array( 'term_taxonomy_id' => $term ) );
2909 do_action( 'edited_term_taxonomy', $term, $taxonomy );
2914 * Generates a permalink for a taxonomy term archive.
2918 * @uses apply_filters() Calls 'term_link' with term link and term object, and taxonomy parameters.
2919 * @uses apply_filters() For the post_tag Taxonomy, Calls 'tag_link' with tag link and tag ID as parameters.
2920 * @uses apply_filters() For the category Taxonomy, Calls 'category_link' filter on category link and category ID.
2922 * @param object|int|string $term
2923 * @param string $taxonomy (optional if $term is object)
2924 * @return string|WP_Error HTML link to taxonomy term archive on success, WP_Error if term does not exist.
2926 function get_term_link( $term, $taxonomy = '') {
2929 if ( !is_object($term) ) {
2930 if ( is_int($term) ) {
2931 $term = &get_term($term, $taxonomy);
2933 $term = &get_term_by('slug', $term, $taxonomy);
2937 if ( !is_object($term) )
2938 $term = new WP_Error('invalid_term', __('Empty Term'));
2940 if ( is_wp_error( $term ) )
2943 $taxonomy = $term->taxonomy;
2945 $termlink = $wp_rewrite->get_extra_permastruct($taxonomy);
2947 $slug = $term->slug;
2948 $t = get_taxonomy($taxonomy);
2950 if ( empty($termlink) ) {
2951 if ( 'category' == $taxonomy )
2952 $termlink = '?cat=' . $term->term_id;
2953 elseif ( $t->query_var )
2954 $termlink = "?$t->query_var=$slug";
2956 $termlink = "?taxonomy=$taxonomy&term=$slug";
2957 $termlink = home_url($termlink);
2959 if ( $t->rewrite['hierarchical'] ) {
2960 $hierarchical_slugs = array();
2961 $ancestors = get_ancestors($term->term_id, $taxonomy);
2962 foreach ( (array)$ancestors as $ancestor ) {
2963 $ancestor_term = get_term($ancestor, $taxonomy);
2964 $hierarchical_slugs[] = $ancestor_term->slug;
2966 $hierarchical_slugs = array_reverse($hierarchical_slugs);
2967 $hierarchical_slugs[] = $slug;
2968 $termlink = str_replace("%$taxonomy%", implode('/', $hierarchical_slugs), $termlink);
2970 $termlink = str_replace("%$taxonomy%", $slug, $termlink);
2972 $termlink = home_url( user_trailingslashit($termlink, 'category') );
2974 // Back Compat filters.
2975 if ( 'post_tag' == $taxonomy )
2976 $termlink = apply_filters( 'tag_link', $termlink, $term->term_id );
2977 elseif ( 'category' == $taxonomy )
2978 $termlink = apply_filters( 'category_link', $termlink, $term->term_id );
2980 return apply_filters('term_link', $termlink, $term, $taxonomy);
2984 * Display the taxonomies of a post with available options.
2986 * This function can be used within the loop to display the taxonomies for a
2987 * post without specifying the Post ID. You can also use it outside the Loop to
2988 * display the taxonomies for a specific post.
2990 * The available defaults are:
2991 * 'post' : default is 0. The post ID to get taxonomies of.
2992 * 'before' : default is empty string. Display before taxonomies list.
2993 * 'sep' : default is empty string. Separate every taxonomy with value in this.
2994 * 'after' : default is empty string. Display this after the taxonomies list.
2995 * 'template' : The template to use for displaying the taxonomy terms.
2998 * @uses get_the_taxonomies()
3000 * @param array $args Override the defaults.
3002 function the_taxonomies($args = array()) {
3008 'template' => '%s: %l.'
3011 $r = wp_parse_args( $args, $defaults );
3012 extract( $r, EXTR_SKIP );
3014 echo $before . join($sep, get_the_taxonomies($post, $r)) . $after;
3018 * Retrieve all taxonomies associated with a post.
3020 * This function can be used within the loop. It will also return an array of
3021 * the taxonomies with links to the taxonomy and name.
3025 * @param int $post Optional. Post ID or will use Global Post ID (in loop).
3026 * @param array $args Override the defaults.
3029 function get_the_taxonomies($post = 0, $args = array() ) {
3030 if ( is_int($post) )
3031 $post =& get_post($post);
3032 elseif ( !is_object($post) )
3033 $post =& $GLOBALS['post'];
3035 $args = wp_parse_args( $args, array(
3036 'template' => '%s: %l.',
3038 extract( $args, EXTR_SKIP );
3040 $taxonomies = array();
3045 foreach ( get_object_taxonomies($post) as $taxonomy ) {
3046 $t = (array) get_taxonomy($taxonomy);
3047 if ( empty($t['label']) )
3048 $t['label'] = $taxonomy;
3049 if ( empty($t['args']) )
3050 $t['args'] = array();
3051 if ( empty($t['template']) )
3052 $t['template'] = $template;
3054 $terms = get_object_term_cache($post->ID, $taxonomy);
3055 if ( empty($terms) )
3056 $terms = wp_get_object_terms($post->ID, $taxonomy, $t['args']);
3060 foreach ( $terms as $term )
3061 $links[] = "<a href='" . esc_attr( get_term_link($term) ) . "'>$term->name</a>";
3064 $taxonomies[$taxonomy] = wp_sprintf($t['template'], $t['label'], $links, $terms);
3070 * Retrieve all taxonomies of a post with just the names.
3073 * @uses get_object_taxonomies()
3075 * @param int $post Optional. Post ID
3078 function get_post_taxonomies($post = 0) {
3079 $post =& get_post($post);
3081 return get_object_taxonomies($post);
3085 * Determine if the given object is associated with any of the given terms.
3087 * The given terms are checked against the object's terms' term_ids, names and slugs.
3088 * Terms given as integers will only be checked against the object's terms' term_ids.
3089 * If no terms are given, determines if object is associated with any terms in the given taxonomy.
3092 * @uses get_object_term_cache()
3093 * @uses wp_get_object_terms()
3095 * @param int $object_id ID of the object (post ID, link ID, ...)
3096 * @param string $taxonomy Single taxonomy name
3097 * @param int|string|array $terms Optional. Term term_id, name, slug or array of said
3098 * @return bool|WP_Error. WP_Error on input error.
3100 function is_object_in_term( $object_id, $taxonomy, $terms = null ) {
3101 if ( !$object_id = (int) $object_id )
3102 return new WP_Error( 'invalid_object', __( 'Invalid object ID' ) );
3104 $object_terms = get_object_term_cache( $object_id, $taxonomy );
3105 if ( empty( $object_terms ) )
3106 $object_terms = wp_get_object_terms( $object_id, $taxonomy );
3108 if ( is_wp_error( $object_terms ) )
3109 return $object_terms;
3110 if ( empty( $object_terms ) )
3112 if ( empty( $terms ) )
3113 return ( !empty( $object_terms ) );
3115 $terms = (array) $terms;
3117 if ( $ints = array_filter( $terms, 'is_int' ) )
3118 $strs = array_diff( $terms, $ints );
3122 foreach ( $object_terms as $object_term ) {
3123 if ( $ints && in_array( $object_term->term_id, $ints ) ) return true; // If int, check against term_id
3125 if ( in_array( $object_term->term_id, $strs ) ) return true;
3126 if ( in_array( $object_term->name, $strs ) ) return true;
3127 if ( in_array( $object_term->slug, $strs ) ) return true;
3135 * Determine if the given object type is associated with the given taxonomy.
3138 * @uses get_object_taxonomies()
3140 * @param string $object_type Object type string
3141 * @param string $taxonomy Single taxonomy name
3142 * @return bool True if object is associated with the taxonomy, otherwise false.
3144 function is_object_in_taxonomy($object_type, $taxonomy) {
3145 $taxonomies = get_object_taxonomies($object_type);
3147 if ( empty($taxonomies) )
3150 if ( in_array($taxonomy, $taxonomies) )
3157 * Get an array of ancestor IDs for a given object.
3159 * @param int $object_id The ID of the object
3160 * @param string $object_type The type of object for which we'll be retrieving ancestors.
3161 * @return array of ancestors from lowest to highest in the hierarchy.
3163 function get_ancestors($object_id = 0, $object_type = '') {
3164 $object_id = (int) $object_id;
3166 $ancestors = array();
3168 if ( empty( $object_id ) ) {
3169 return apply_filters('get_ancestors', $ancestors, $object_id, $object_type);
3172 if ( is_taxonomy_hierarchical( $object_type ) ) {
3173 $term = get_term($object_id, $object_type);
3174 while ( ! is_wp_error($term) && ! empty( $term->parent ) && ! in_array( $term->parent, $ancestors ) ) {
3175 $ancestors[] = (int) $term->parent;
3176 $term = get_term($term->parent, $object_type);
3178 } elseif ( null !== get_post_type_object( $object_type ) ) {
3179 $object = get_post($object_id);
3180 if ( ! is_wp_error( $object ) && isset( $object->ancestors ) && is_array( $object->ancestors ) )
3181 $ancestors = $object->ancestors;
3183 while ( ! is_wp_error($object) && ! empty( $object->post_parent ) && ! in_array( $object->post_parent, $ancestors ) ) {
3184 $ancestors[] = (int) $object->post_parent;
3185 $object = get_post($object->post_parent);
3190 return apply_filters('get_ancestors', $ancestors, $object_id, $object_type);
3194 * Returns the term's parent's term_ID
3198 * @param int $term_id
3199 * @param string $taxonomy
3201 * @return int|bool false on error
3203 function wp_get_term_taxonomy_parent_id( $term_id, $taxonomy ) {
3204 $term = get_term( $term_id, $taxonomy );
3205 if ( !$term || is_wp_error( $term ) )
3207 return (int) $term->parent;
3211 * Checks the given subset of the term hierarchy for hierarchy loops.
3212 * Prevents loops from forming and breaks those that it finds.
3214 * Attached to the wp_update_term_parent filter.
3217 * @uses wp_find_hierarchy_loop()
3219 * @param int $parent term_id of the parent for the term we're checking.
3220 * @param int $term_id The term we're checking.
3221 * @param string $taxonomy The taxonomy of the term we're checking.
3223 * @return int The new parent for the term.
3225 function wp_check_term_hierarchy_for_loops( $parent, $term_id, $taxonomy ) {
3226 // Nothing fancy here - bail
3230 // Can't be its own parent
3231 if ( $parent == $term_id )
3234 // Now look for larger loops
3236 if ( !$loop = wp_find_hierarchy_loop( 'wp_get_term_taxonomy_parent_id', $term_id, $parent, array( $taxonomy ) ) )
3237 return $parent; // No loop
3239 // Setting $parent to the given value causes a loop
3240 if ( isset( $loop[$term_id] ) )
3243 // There's a loop, but it doesn't contain $term_id. Break the loop.
3244 foreach ( array_keys( $loop ) as $loop_member )
3245 wp_update_term( $loop_member, $taxonomy, array( 'parent' => 0 ) );