11 // Taxonomy Registration
15 * Creates the initial taxonomies.
17 * This function fires twice: in wp-settings.php before plugins are loaded (for
18 * backwards compatibility reasons), and again on the 'init' action. We must avoid
19 * registering rewrite rules before the 'init' action.
21 function create_initial_taxonomies() {
24 if ( ! did_action( 'init' ) ) {
25 $rewrite = array( 'category' => false, 'post_tag' => false, 'post_format' => false );
29 * Filter the post formats rewrite base.
33 * @param string $context Context of the rewrite base. Default 'type'.
35 $post_format_base = apply_filters( 'post_format_rewrite_base', 'type' );
38 'hierarchical' => true,
39 'slug' => get_option('category_base') ? get_option('category_base') : 'category',
40 'with_front' => ! get_option('category_base') || $wp_rewrite->using_index_permalinks(),
41 'ep_mask' => EP_CATEGORIES,
44 'slug' => get_option('tag_base') ? get_option('tag_base') : 'tag',
45 'with_front' => ! get_option('tag_base') || $wp_rewrite->using_index_permalinks(),
48 'post_format' => $post_format_base ? array( 'slug' => $post_format_base ) : false,
52 register_taxonomy( 'category', 'post', array(
53 'hierarchical' => true,
54 'query_var' => 'category_name',
55 'rewrite' => $rewrite['category'],
58 'show_admin_column' => true,
62 register_taxonomy( 'post_tag', 'post', array(
63 'hierarchical' => false,
65 'rewrite' => $rewrite['post_tag'],
68 'show_admin_column' => true,
72 register_taxonomy( 'nav_menu', 'nav_menu_item', array(
74 'hierarchical' => false,
76 'name' => __( 'Navigation Menus' ),
77 'singular_name' => __( 'Navigation Menu' ),
83 'show_in_nav_menus' => false,
86 register_taxonomy( 'link_category', 'link', array(
87 'hierarchical' => false,
89 'name' => __( 'Link Categories' ),
90 'singular_name' => __( 'Link Category' ),
91 'search_items' => __( 'Search Link Categories' ),
92 'popular_items' => null,
93 'all_items' => __( 'All Link Categories' ),
94 'edit_item' => __( 'Edit Link Category' ),
95 'update_item' => __( 'Update Link Category' ),
96 'add_new_item' => __( 'Add New Link Category' ),
97 'new_item_name' => __( 'New Link Category Name' ),
98 'separate_items_with_commas' => null,
99 'add_or_remove_items' => null,
100 'choose_from_most_used' => null,
102 'capabilities' => array(
103 'manage_terms' => 'manage_links',
104 'edit_terms' => 'manage_links',
105 'delete_terms' => 'manage_links',
106 'assign_terms' => 'manage_links',
108 'query_var' => false,
115 register_taxonomy( 'post_format', 'post', array(
117 'hierarchical' => false,
119 'name' => _x( 'Format', 'post format' ),
120 'singular_name' => _x( 'Format', 'post format' ),
123 'rewrite' => $rewrite['post_format'],
126 'show_in_nav_menus' => current_theme_supports( 'post-formats' ),
129 add_action( 'init', 'create_initial_taxonomies', 0 ); // highest priority
132 * Get a list of registered taxonomy objects.
135 * @uses $wp_taxonomies
136 * @see register_taxonomy
138 * @param array $args An array of key => value arguments to match against the taxonomy objects.
139 * @param string $output The type of output to return, either taxonomy 'names' or 'objects'. 'names' is the default.
140 * @param string $operator The logical operation to perform. 'or' means only one element
141 * from the array needs to match; 'and' means all elements must match. The default is 'and'.
142 * @return array A list of taxonomy names or objects
144 function get_taxonomies( $args = array(), $output = 'names', $operator = 'and' ) {
145 global $wp_taxonomies;
147 $field = ('names' == $output) ? 'name' : false;
149 return wp_filter_object_list($wp_taxonomies, $args, $operator, $field);
153 * Return all of the taxonomy names that are of $object_type.
155 * It appears that this function can be used to find all of the names inside of
156 * $wp_taxonomies global variable.
158 * <code><?php $taxonomies = get_object_taxonomies('post'); ?></code> Should
159 * result in <code>Array('category', 'post_tag')</code>
163 * @uses $wp_taxonomies
165 * @param array|string|object $object Name of the type of taxonomy object, or an object (row from posts)
166 * @param string $output The type of output to return, either taxonomy 'names' or 'objects'. 'names' is the default.
167 * @return array The names of all taxonomy of $object_type.
169 function get_object_taxonomies($object, $output = 'names') {
170 global $wp_taxonomies;
172 if ( is_object($object) ) {
173 if ( $object->post_type == 'attachment' )
174 return get_attachment_taxonomies($object);
175 $object = $object->post_type;
178 $object = (array) $object;
180 $taxonomies = array();
181 foreach ( (array) $wp_taxonomies as $tax_name => $tax_obj ) {
182 if ( array_intersect($object, (array) $tax_obj->object_type) ) {
183 if ( 'names' == $output )
184 $taxonomies[] = $tax_name;
186 $taxonomies[ $tax_name ] = $tax_obj;
194 * Retrieves the taxonomy object of $taxonomy.
196 * The get_taxonomy function will first check that the parameter string given
197 * is a taxonomy object and if it is, it will return it.
201 * @uses $wp_taxonomies
202 * @uses taxonomy_exists() Checks whether taxonomy exists
204 * @param string $taxonomy Name of taxonomy object to return
205 * @return object|bool The Taxonomy Object or false if $taxonomy doesn't exist
207 function get_taxonomy( $taxonomy ) {
208 global $wp_taxonomies;
210 if ( ! taxonomy_exists( $taxonomy ) )
213 return $wp_taxonomies[$taxonomy];
217 * Checks that the taxonomy name exists.
219 * Formerly is_taxonomy(), introduced in 2.3.0.
223 * @uses $wp_taxonomies
225 * @param string $taxonomy Name of taxonomy object
226 * @return bool Whether the taxonomy exists.
228 function taxonomy_exists( $taxonomy ) {
229 global $wp_taxonomies;
231 return isset( $wp_taxonomies[$taxonomy] );
235 * Whether the taxonomy object is hierarchical.
237 * Checks to make sure that the taxonomy is an object first. Then Gets the
238 * object, and finally returns the hierarchical value in the object.
240 * A false return value might also mean that the taxonomy does not exist.
244 * @uses taxonomy_exists() Checks whether taxonomy exists
245 * @uses get_taxonomy() Used to get the taxonomy object
247 * @param string $taxonomy Name of taxonomy object
248 * @return bool Whether the taxonomy is hierarchical
250 function is_taxonomy_hierarchical($taxonomy) {
251 if ( ! taxonomy_exists($taxonomy) )
254 $taxonomy = get_taxonomy($taxonomy);
255 return $taxonomy->hierarchical;
259 * Create or modify a taxonomy object. Do not use before init.
261 * A simple function for creating or modifying a taxonomy object based on the
262 * parameters given. The function will accept an array (third optional
263 * parameter), along with strings for the taxonomy name and another string for
266 * Nothing is returned, so expect error maybe or use taxonomy_exists() to check
267 * whether taxonomy exists.
269 * Optional $args contents:
271 * - label - Name of the taxonomy shown in the menu. Usually plural. If not set, labels['name'] will be used.
272 * - labels - An array of labels for this taxonomy.
273 * * By default tag labels are used for non-hierarchical types and category labels for hierarchical ones.
274 * * You can see accepted values in {@link get_taxonomy_labels()}.
275 * - description - A short descriptive summary of what the taxonomy is for. Defaults to blank.
276 * - public - If the taxonomy should be publicly queryable; //@TODO not implemented.
277 * * Defaults to true.
278 * - hierarchical - Whether the taxonomy is hierarchical (e.g. category). Defaults to false.
279 * - show_ui -Whether to generate a default UI for managing this taxonomy in the admin.
280 * * If not set, the default is inherited from public.
281 * - show_in_menu - Where to show the taxonomy in the admin menu.
282 * * If true, the taxonomy is shown as a submenu of the object type menu.
283 * * If false, no menu is shown.
284 * * show_ui must be true.
285 * * If not set, the default is inherited from show_ui.
286 * - show_in_nav_menus - Makes this taxonomy available for selection in navigation menus.
287 * * If not set, the default is inherited from public.
288 * - show_tagcloud - Whether to list the taxonomy in the Tag Cloud Widget.
289 * * If not set, the default is inherited from show_ui.
290 * - show_admin_column - Whether to display a column for the taxonomy on its post type listing screens.
291 * * Defaults to false.
292 * - meta_box_cb - Provide a callback function for the meta box display.
293 * * If not set, defaults to post_categories_meta_box for hierarchical taxonomies
294 * and post_tags_meta_box for non-hierarchical.
295 * * If false, no meta box is shown.
296 * - capabilities - Array of capabilities for this taxonomy.
297 * * You can see accepted values in this function.
298 * - rewrite - Triggers the handling of rewrites for this taxonomy. Defaults to true, using $taxonomy as slug.
299 * * To prevent rewrite, set to false.
300 * * To specify rewrite rules, an array can be passed with any of these keys
301 * * 'slug' => string Customize the permastruct slug. Defaults to $taxonomy key
302 * * 'with_front' => bool Should the permastruct be prepended with WP_Rewrite::$front. Defaults to true.
303 * * 'hierarchical' => bool Either hierarchical rewrite tag or not. Defaults to false.
304 * * 'ep_mask' => const Assign an endpoint mask.
305 * * If not specified, defaults to EP_NONE.
306 * - query_var - Sets the query_var key for this taxonomy. Defaults to $taxonomy key
307 * * If false, a taxonomy cannot be loaded at ?{query_var}={term_slug}
308 * * If specified as a string, the query ?{query_var_string}={term_slug} will be valid.
309 * - update_count_callback - Works much like a hook, in that it will be called when the count is updated.
310 * * Defaults to _update_post_term_count() for taxonomies attached to post types, which then confirms
311 * that the objects are published before counting them.
312 * * Defaults to _update_generic_term_count() for taxonomies attached to other object types, such as links.
313 * - _builtin - true if this taxonomy is a native or "built-in" taxonomy. THIS IS FOR INTERNAL USE ONLY!
316 * @uses $wp_taxonomies Inserts new taxonomy object into the list
317 * @uses $wp Adds query vars
319 * @param string $taxonomy Taxonomy key, must not exceed 32 characters.
320 * @param array|string $object_type Name of the object type for the taxonomy object.
321 * @param array|string $args See optional args description above.
322 * @return null|WP_Error WP_Error if errors, otherwise null.
324 function register_taxonomy( $taxonomy, $object_type, $args = array() ) {
325 global $wp_taxonomies, $wp;
327 if ( ! is_array( $wp_taxonomies ) )
328 $wp_taxonomies = array();
334 'hierarchical' => false,
336 'show_in_menu' => null,
337 'show_in_nav_menus' => null,
338 'show_tagcloud' => null,
339 'show_admin_column' => false,
340 'meta_box_cb' => null,
341 'capabilities' => array(),
343 'query_var' => $taxonomy,
344 'update_count_callback' => '',
347 $args = wp_parse_args( $args, $defaults );
349 if ( strlen( $taxonomy ) > 32 )
350 return new WP_Error( 'taxonomy_too_long', __( 'Taxonomies cannot exceed 32 characters in length' ) );
352 if ( false !== $args['query_var'] && ! empty( $wp ) ) {
353 if ( true === $args['query_var'] )
354 $args['query_var'] = $taxonomy;
356 $args['query_var'] = sanitize_title_with_dashes( $args['query_var'] );
357 $wp->add_query_var( $args['query_var'] );
360 if ( false !== $args['rewrite'] && ( is_admin() || '' != get_option( 'permalink_structure' ) ) ) {
361 $args['rewrite'] = wp_parse_args( $args['rewrite'], array(
362 'with_front' => true,
363 'hierarchical' => false,
364 'ep_mask' => EP_NONE,
367 if ( empty( $args['rewrite']['slug'] ) )
368 $args['rewrite']['slug'] = sanitize_title_with_dashes( $taxonomy );
370 if ( $args['hierarchical'] && $args['rewrite']['hierarchical'] )
375 add_rewrite_tag( "%$taxonomy%", $tag, $args['query_var'] ? "{$args['query_var']}=" : "taxonomy=$taxonomy&term=" );
376 add_permastruct( $taxonomy, "{$args['rewrite']['slug']}/%$taxonomy%", $args['rewrite'] );
379 // If not set, default to the setting for public.
380 if ( null === $args['show_ui'] )
381 $args['show_ui'] = $args['public'];
383 // If not set, default to the setting for show_ui.
384 if ( null === $args['show_in_menu' ] || ! $args['show_ui'] )
385 $args['show_in_menu' ] = $args['show_ui'];
387 // If not set, default to the setting for public.
388 if ( null === $args['show_in_nav_menus'] )
389 $args['show_in_nav_menus'] = $args['public'];
391 // If not set, default to the setting for show_ui.
392 if ( null === $args['show_tagcloud'] )
393 $args['show_tagcloud'] = $args['show_ui'];
395 $default_caps = array(
396 'manage_terms' => 'manage_categories',
397 'edit_terms' => 'manage_categories',
398 'delete_terms' => 'manage_categories',
399 'assign_terms' => 'edit_posts',
401 $args['cap'] = (object) array_merge( $default_caps, $args['capabilities'] );
402 unset( $args['capabilities'] );
404 $args['name'] = $taxonomy;
405 $args['object_type'] = array_unique( (array) $object_type );
407 $args['labels'] = get_taxonomy_labels( (object) $args );
408 $args['label'] = $args['labels']->name;
410 // If not set, use the default meta box
411 if ( null === $args['meta_box_cb'] ) {
412 if ( $args['hierarchical'] )
413 $args['meta_box_cb'] = 'post_categories_meta_box';
415 $args['meta_box_cb'] = 'post_tags_meta_box';
418 $wp_taxonomies[ $taxonomy ] = (object) $args;
420 // register callback handling for metabox
421 add_filter( 'wp_ajax_add-' . $taxonomy, '_wp_ajax_add_hierarchical_term' );
424 * Fires after a taxonomy is registered.
428 * @param string $taxonomy Taxonomy slug.
429 * @param array|string $object_type Object type or array of object types.
430 * @param array|string $args Array or string of taxonomy registration arguments.
432 do_action( 'registered_taxonomy', $taxonomy, $object_type, $args );
436 * Builds an object with all taxonomy labels out of a taxonomy object
438 * Accepted keys of the label array in the taxonomy object:
439 * - name - general name for the taxonomy, usually plural. The same as and overridden by $tax->label. Default is Tags/Categories
440 * - singular_name - name for one object of this taxonomy. Default is Tag/Category
441 * - search_items - Default is Search Tags/Search Categories
442 * - popular_items - This string isn't used on hierarchical taxonomies. Default is Popular Tags
443 * - all_items - Default is All Tags/All Categories
444 * - parent_item - This string isn't used on non-hierarchical taxonomies. In hierarchical ones the default is Parent Category
445 * - parent_item_colon - The same as <code>parent_item</code>, but with colon <code>:</code> in the end
446 * - edit_item - Default is Edit Tag/Edit Category
447 * - view_item - Default is View Tag/View Category
448 * - update_item - Default is Update Tag/Update Category
449 * - add_new_item - Default is Add New Tag/Add New Category
450 * - new_item_name - Default is New Tag Name/New Category Name
451 * - separate_items_with_commas - This string isn't used on hierarchical taxonomies. Default is "Separate tags with commas", used in the meta box.
452 * - 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.
453 * - 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.
454 * - not_found - This string isn't used on hierarchical taxonomies. Default is "No tags found", used in the meta box.
456 * Above, the first default value is for non-hierarchical taxonomies (like tags) and the second one is for hierarchical taxonomies (like categories).
459 * @param object $tax Taxonomy object
460 * @return object object with all the labels as member variables
463 function get_taxonomy_labels( $tax ) {
464 $tax->labels = (array) $tax->labels;
466 if ( isset( $tax->helps ) && empty( $tax->labels['separate_items_with_commas'] ) )
467 $tax->labels['separate_items_with_commas'] = $tax->helps;
469 if ( isset( $tax->no_tagcloud ) && empty( $tax->labels['not_found'] ) )
470 $tax->labels['not_found'] = $tax->no_tagcloud;
472 $nohier_vs_hier_defaults = array(
473 'name' => array( _x( 'Tags', 'taxonomy general name' ), _x( 'Categories', 'taxonomy general name' ) ),
474 'singular_name' => array( _x( 'Tag', 'taxonomy singular name' ), _x( 'Category', 'taxonomy singular name' ) ),
475 'search_items' => array( __( 'Search Tags' ), __( 'Search Categories' ) ),
476 'popular_items' => array( __( 'Popular Tags' ), null ),
477 'all_items' => array( __( 'All Tags' ), __( 'All Categories' ) ),
478 'parent_item' => array( null, __( 'Parent Category' ) ),
479 'parent_item_colon' => array( null, __( 'Parent Category:' ) ),
480 'edit_item' => array( __( 'Edit Tag' ), __( 'Edit Category' ) ),
481 'view_item' => array( __( 'View Tag' ), __( 'View Category' ) ),
482 'update_item' => array( __( 'Update Tag' ), __( 'Update Category' ) ),
483 'add_new_item' => array( __( 'Add New Tag' ), __( 'Add New Category' ) ),
484 'new_item_name' => array( __( 'New Tag Name' ), __( 'New Category Name' ) ),
485 'separate_items_with_commas' => array( __( 'Separate tags with commas' ), null ),
486 'add_or_remove_items' => array( __( 'Add or remove tags' ), null ),
487 'choose_from_most_used' => array( __( 'Choose from the most used tags' ), null ),
488 'not_found' => array( __( 'No tags found.' ), null ),
490 $nohier_vs_hier_defaults['menu_name'] = $nohier_vs_hier_defaults['name'];
492 return _get_custom_object_labels( $tax, $nohier_vs_hier_defaults );
496 * Add an already registered taxonomy to an object type.
499 * @uses $wp_taxonomies Modifies taxonomy object
501 * @param string $taxonomy Name of taxonomy object
502 * @param string $object_type Name of the object type
503 * @return bool True if successful, false if not
505 function register_taxonomy_for_object_type( $taxonomy, $object_type) {
506 global $wp_taxonomies;
508 if ( !isset($wp_taxonomies[$taxonomy]) )
511 if ( ! get_post_type_object($object_type) )
514 if ( ! in_array( $object_type, $wp_taxonomies[$taxonomy]->object_type ) )
515 $wp_taxonomies[$taxonomy]->object_type[] = $object_type;
521 * Remove an already registered taxonomy from an object type.
525 * @param string $taxonomy Name of taxonomy object.
526 * @param string $object_type Name of the object type.
527 * @return bool True if successful, false if not.
529 function unregister_taxonomy_for_object_type( $taxonomy, $object_type ) {
530 global $wp_taxonomies;
532 if ( ! isset( $wp_taxonomies[ $taxonomy ] ) )
535 if ( ! get_post_type_object( $object_type ) )
538 $key = array_search( $object_type, $wp_taxonomies[ $taxonomy ]->object_type, true );
539 if ( false === $key )
542 unset( $wp_taxonomies[ $taxonomy ]->object_type[ $key ] );
551 * Retrieve object_ids of valid taxonomy and term.
553 * The strings of $taxonomies must exist before this function will continue. On
554 * failure of finding a valid taxonomy, it will return an WP_Error class, kind
555 * of like Exceptions in PHP 5, except you can't catch them. Even so, you can
556 * still test for the WP_Error class and get the error message.
558 * The $terms aren't checked the same as $taxonomies, but still need to exist
559 * for $object_ids to be returned.
561 * It is possible to change the order that object_ids is returned by either
562 * using PHP sort family functions or using the database by using $args with
563 * either ASC or DESC array. The value should be in the key named 'order'.
568 * @uses wp_parse_args() Creates an array from string $args.
570 * @param int|array $term_ids Term id or array of term ids of terms that will be used
571 * @param string|array $taxonomies String of taxonomy name or Array of string values of taxonomy names
572 * @param array|string $args Change the order of the object_ids, either ASC or DESC
573 * @return WP_Error|array If the taxonomy does not exist, then WP_Error will be returned. On success
574 * the array can be empty meaning that there are no $object_ids found or it will return the $object_ids found.
576 function get_objects_in_term( $term_ids, $taxonomies, $args = array() ) {
579 if ( ! is_array( $term_ids ) )
580 $term_ids = array( $term_ids );
582 if ( ! is_array( $taxonomies ) )
583 $taxonomies = array( $taxonomies );
585 foreach ( (array) $taxonomies as $taxonomy ) {
586 if ( ! taxonomy_exists( $taxonomy ) )
587 return new WP_Error( 'invalid_taxonomy', __( 'Invalid taxonomy' ) );
590 $defaults = array( 'order' => 'ASC' );
591 $args = wp_parse_args( $args, $defaults );
592 extract( $args, EXTR_SKIP );
594 $order = ( 'desc' == strtolower( $order ) ) ? 'DESC' : 'ASC';
596 $term_ids = array_map('intval', $term_ids );
598 $taxonomies = "'" . implode( "', '", $taxonomies ) . "'";
599 $term_ids = "'" . implode( "', '", $term_ids ) . "'";
601 $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");
610 * Given a taxonomy query, generates SQL to be appended to a main query.
616 * @param array $tax_query A compact tax query
617 * @param string $primary_table
618 * @param string $primary_id_column
621 function get_tax_sql( $tax_query, $primary_table, $primary_id_column ) {
622 $tax_query_obj = new WP_Tax_Query( $tax_query );
623 return $tax_query_obj->get_sql( $primary_table, $primary_id_column );
627 * Container class for a multiple taxonomy query.
634 * List of taxonomy queries. A single taxonomy query is an associative array:
635 * - 'taxonomy' string The taxonomy being queried
636 * - 'terms' string|array The list of terms
637 * - 'field' string (optional) Which term field is being used.
638 * Possible values: 'term_id', 'slug' or 'name'
640 * - 'operator' string (optional)
641 * Possible values: 'AND', 'IN' or 'NOT IN'.
643 * - 'include_children' bool (optional) Whether to include child terms.
650 public $queries = array();
653 * The relation between the queries. Can be one of 'AND' or 'OR'.
662 * Standard response when the query should not return any rows.
668 private static $no_results = array( 'join' => '', 'where' => ' AND 0 = 1' );
673 * Parses a compact tax query and sets defaults.
678 * @param array $tax_query A compact tax query:
680 * 'relation' => 'OR',
682 * 'taxonomy' => 'tax1',
683 * 'terms' => array( 'term1', 'term2' ),
687 * 'taxonomy' => 'tax2',
688 * 'terms' => array( 'term-a', 'term-b' ),
693 public function __construct( $tax_query ) {
694 if ( isset( $tax_query['relation'] ) && strtoupper( $tax_query['relation'] ) == 'OR' ) {
695 $this->relation = 'OR';
697 $this->relation = 'AND';
703 'include_children' => true,
704 'field' => 'term_id',
708 foreach ( $tax_query as $query ) {
709 if ( ! is_array( $query ) )
712 $query = array_merge( $defaults, $query );
714 $query['terms'] = (array) $query['terms'];
716 $this->queries[] = $query;
721 * Generates SQL clauses to be appended to a main query.
726 * @param string $primary_table
727 * @param string $primary_id_column
730 public function get_sql( $primary_table, $primary_id_column ) {
736 $count = count( $this->queries );
738 foreach ( $this->queries as $index => $query ) {
739 $this->clean_query( $query );
741 if ( is_wp_error( $query ) )
742 return self::$no_results;
746 if ( 'IN' == $operator ) {
748 if ( empty( $terms ) ) {
749 if ( 'OR' == $this->relation ) {
750 if ( ( $index + 1 === $count ) && empty( $where ) )
751 return self::$no_results;
754 return self::$no_results;
758 $terms = implode( ',', $terms );
760 $alias = $i ? 'tt' . $i : $wpdb->term_relationships;
762 $join .= " INNER JOIN $wpdb->term_relationships";
763 $join .= $i ? " AS $alias" : '';
764 $join .= " ON ($primary_table.$primary_id_column = $alias.object_id)";
766 $where[] = "$alias.term_taxonomy_id $operator ($terms)";
767 } elseif ( 'NOT IN' == $operator ) {
769 if ( empty( $terms ) )
772 $terms = implode( ',', $terms );
774 $where[] = "$primary_table.$primary_id_column NOT IN (
776 FROM $wpdb->term_relationships
777 WHERE term_taxonomy_id IN ($terms)
779 } elseif ( 'AND' == $operator ) {
781 if ( empty( $terms ) )
784 $num_terms = count( $terms );
786 $terms = implode( ',', $terms );
790 FROM $wpdb->term_relationships
791 WHERE term_taxonomy_id IN ($terms)
792 AND object_id = $primary_table.$primary_id_column
799 if ( ! empty( $where ) )
800 $where = ' AND ( ' . implode( " $this->relation ", $where ) . ' )';
804 return compact( 'join', 'where' );
808 * Validates a single query.
813 * @param array &$query The single query
815 private function clean_query( &$query ) {
816 if ( ! taxonomy_exists( $query['taxonomy'] ) ) {
817 $query = new WP_Error( 'Invalid taxonomy' );
821 $query['terms'] = array_unique( (array) $query['terms'] );
823 if ( is_taxonomy_hierarchical( $query['taxonomy'] ) && $query['include_children'] ) {
824 $this->transform_query( $query, 'term_id' );
826 if ( is_wp_error( $query ) )
830 foreach ( $query['terms'] as $term ) {
831 $children = array_merge( $children, get_term_children( $term, $query['taxonomy'] ) );
834 $query['terms'] = $children;
837 $this->transform_query( $query, 'term_taxonomy_id' );
841 * Transforms a single query, from one field to another.
845 * @param array &$query The single query
846 * @param string $resulting_field The resulting field
848 public function transform_query( &$query, $resulting_field ) {
851 if ( empty( $query['terms'] ) )
854 if ( $query['field'] == $resulting_field )
857 $resulting_field = sanitize_key( $resulting_field );
859 switch ( $query['field'] ) {
862 $terms = "'" . implode( "','", array_map( 'sanitize_title_for_query', $query['terms'] ) ) . "'";
863 $terms = $wpdb->get_col( "
864 SELECT $wpdb->term_taxonomy.$resulting_field
865 FROM $wpdb->term_taxonomy
866 INNER JOIN $wpdb->terms USING (term_id)
867 WHERE taxonomy = '{$query['taxonomy']}'
868 AND $wpdb->terms.{$query['field']} IN ($terms)
871 case 'term_taxonomy_id':
872 $terms = implode( ',', array_map( 'intval', $query['terms'] ) );
873 $terms = $wpdb->get_col( "
874 SELECT $resulting_field
875 FROM $wpdb->term_taxonomy
876 WHERE term_taxonomy_id IN ($terms)
880 $terms = implode( ',', array_map( 'intval', $query['terms'] ) );
881 $terms = $wpdb->get_col( "
882 SELECT $resulting_field
883 FROM $wpdb->term_taxonomy
884 WHERE taxonomy = '{$query['taxonomy']}'
885 AND term_id IN ($terms)
889 if ( 'AND' == $query['operator'] && count( $terms ) < count( $query['terms'] ) ) {
890 $query = new WP_Error( 'Inexistent terms' );
894 $query['terms'] = $terms;
895 $query['field'] = $resulting_field;
900 * Get all Term data from database by Term ID.
902 * The usage of the get_term function is to apply filters to a term object. It
903 * is possible to get a term object from the database before applying the
906 * $term ID must be part of $taxonomy, to get from the database. Failure, might
907 * be able to be captured by the hooks. Failure would be the same value as $wpdb
908 * returns for the get_row method.
910 * There are two hooks, one is specifically for each term, named 'get_term', and
911 * the second is for the taxonomy name, 'term_$taxonomy'. Both hooks gets the
912 * term object, and the taxonomy name as parameters. Both hooks are expected to
913 * return a Term object.
915 * 'get_term' hook - Takes two parameters the term Object and the taxonomy name.
916 * Must return term object. Used in get_term() as a catch-all filter for every
919 * 'get_$taxonomy' hook - Takes two parameters the term Object and the taxonomy
920 * name. Must return term object. $taxonomy will be the taxonomy name, so for
921 * example, if 'category', it would be 'get_category' as the filter name. Useful
922 * for custom taxonomies or plugging into default taxonomies.
927 * @uses sanitize_term() Cleanses the term based on $filter context before returning.
928 * @see sanitize_term_field() The $context param lists the available values for get_term_by() $filter param.
930 * @param int|object $term If integer, will get from database. If object will apply filters and return $term.
931 * @param string $taxonomy Taxonomy name that $term is part of.
932 * @param string $output Constant OBJECT, ARRAY_A, or ARRAY_N
933 * @param string $filter Optional, default is raw or no WordPress defined filter will applied.
934 * @return mixed|null|WP_Error Term Row from database. Will return null if $term is empty. If taxonomy does not
935 * exist then WP_Error will be returned.
937 function get_term($term, $taxonomy, $output = OBJECT, $filter = 'raw') {
940 if ( empty($term) ) {
941 $error = new WP_Error('invalid_term', __('Empty Term'));
945 if ( ! taxonomy_exists($taxonomy) ) {
946 $error = new WP_Error('invalid_taxonomy', __('Invalid taxonomy'));
950 if ( is_object($term) && empty($term->filter) ) {
951 wp_cache_add($term->term_id, $term, $taxonomy);
954 if ( is_object($term) )
955 $term = $term->term_id;
956 if ( !$term = (int) $term )
958 if ( ! $_term = wp_cache_get($term, $taxonomy) ) {
959 $_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) );
962 wp_cache_add($term, $_term, $taxonomy);
971 * @param int|object $_term Term object or ID.
972 * @param string $taxonomy The taxonomy slug.
974 $_term = apply_filters( 'get_term', $_term, $taxonomy );
979 * The dynamic portion of the filter name, $taxonomy, refers
980 * to the taxonomy slug.
984 * @param int|object $_term Term object or ID.
985 * @param string $taxonomy The taxonomy slug.
987 $_term = apply_filters( "get_$taxonomy", $_term, $taxonomy );
988 $_term = sanitize_term($_term, $taxonomy, $filter);
990 if ( $output == OBJECT ) {
992 } elseif ( $output == ARRAY_A ) {
993 $__term = get_object_vars($_term);
995 } elseif ( $output == ARRAY_N ) {
996 $__term = array_values(get_object_vars($_term));
1004 * Get all Term data from database by Term field and data.
1006 * Warning: $value is not escaped for 'name' $field. You must do it yourself, if
1009 * The default $field is 'id', therefore it is possible to also use null for
1010 * field, but not recommended that you do so.
1012 * If $value does not exist, the return value will be false. If $taxonomy exists
1013 * and $field and $value combinations exist, the Term will be returned.
1018 * @uses sanitize_term() Cleanses the term based on $filter context before returning.
1019 * @see sanitize_term_field() The $context param lists the available values for get_term_by() $filter param.
1021 * @param string $field Either 'slug', 'name', 'id' (term_id), or 'term_taxonomy_id'
1022 * @param string|int $value Search for this term value
1023 * @param string $taxonomy Taxonomy Name
1024 * @param string $output Constant OBJECT, ARRAY_A, or ARRAY_N
1025 * @param string $filter Optional, default is raw or no WordPress defined filter will applied.
1026 * @return mixed Term Row from database. Will return false if $taxonomy does not exist or $term was not found.
1028 function get_term_by($field, $value, $taxonomy, $output = OBJECT, $filter = 'raw') {
1031 if ( ! taxonomy_exists($taxonomy) )
1034 if ( 'slug' == $field ) {
1036 $value = sanitize_title($value);
1037 if ( empty($value) )
1039 } else if ( 'name' == $field ) {
1040 // Assume already escaped
1041 $value = wp_unslash($value);
1043 } else if ( 'term_taxonomy_id' == $field ) {
1044 $value = (int) $value;
1045 $field = 'tt.term_taxonomy_id';
1047 $term = get_term( (int) $value, $taxonomy, $output, $filter);
1048 if ( is_wp_error( $term ) )
1053 $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) );
1057 wp_cache_add($term->term_id, $term, $taxonomy);
1059 /** This filter is documented in wp-includes/taxonomy.php */
1060 $term = apply_filters( 'get_term', $term, $taxonomy );
1062 /** This filter is documented in wp-includes/taxonomy.php */
1063 $term = apply_filters( "get_$taxonomy", $term, $taxonomy );
1065 $term = sanitize_term($term, $taxonomy, $filter);
1067 if ( $output == OBJECT ) {
1069 } elseif ( $output == ARRAY_A ) {
1070 return get_object_vars($term);
1071 } elseif ( $output == ARRAY_N ) {
1072 return array_values(get_object_vars($term));
1079 * Merge all term children into a single array of their IDs.
1081 * This recursive function will merge all of the children of $term into the same
1082 * array of term IDs. Only useful for taxonomies which are hierarchical.
1084 * Will return an empty array if $term does not exist in $taxonomy.
1089 * @uses _get_term_hierarchy()
1090 * @uses get_term_children() Used to get the children of both $taxonomy and the parent $term
1092 * @param string $term_id ID of Term to get children
1093 * @param string $taxonomy Taxonomy Name
1094 * @return array|WP_Error List of Term IDs. WP_Error returned if $taxonomy does not exist
1096 function get_term_children( $term_id, $taxonomy ) {
1097 if ( ! taxonomy_exists($taxonomy) )
1098 return new WP_Error('invalid_taxonomy', __('Invalid taxonomy'));
1100 $term_id = intval( $term_id );
1102 $terms = _get_term_hierarchy($taxonomy);
1104 if ( ! isset($terms[$term_id]) )
1107 $children = $terms[$term_id];
1109 foreach ( (array) $terms[$term_id] as $child ) {
1110 if ( $term_id == $child ) {
1114 if ( isset($terms[$child]) )
1115 $children = array_merge($children, get_term_children($child, $taxonomy));
1122 * Get sanitized Term field.
1124 * Does checks for $term, based on the $taxonomy. The function is for contextual
1125 * reasons and for simplicity of usage. See sanitize_term_field() for more
1130 * @uses sanitize_term_field() Passes the return value in sanitize_term_field on success.
1132 * @param string $field Term field to fetch
1133 * @param int $term Term ID
1134 * @param string $taxonomy Taxonomy Name
1135 * @param string $context Optional, default is display. Look at sanitize_term_field() for available options.
1136 * @return mixed Will return an empty string if $term is not an object or if $field is not set in $term.
1138 function get_term_field( $field, $term, $taxonomy, $context = 'display' ) {
1139 $term = (int) $term;
1140 $term = get_term( $term, $taxonomy );
1141 if ( is_wp_error($term) )
1144 if ( !is_object($term) )
1147 if ( !isset($term->$field) )
1150 return sanitize_term_field($field, $term->$field, $term->term_id, $taxonomy, $context);
1154 * Sanitizes Term for editing.
1156 * Return value is sanitize_term() and usage is for sanitizing the term for
1157 * editing. Function is for contextual and simplicity.
1161 * @uses sanitize_term() Passes the return value on success
1163 * @param int|object $id Term ID or Object
1164 * @param string $taxonomy Taxonomy Name
1165 * @return mixed|null|WP_Error Will return empty string if $term is not an object.
1167 function get_term_to_edit( $id, $taxonomy ) {
1168 $term = get_term( $id, $taxonomy );
1170 if ( is_wp_error($term) )
1173 if ( !is_object($term) )
1176 return sanitize_term($term, $taxonomy, 'edit');
1180 * Retrieve the terms in a given taxonomy or list of taxonomies.
1182 * You can fully inject any customizations to the query before it is sent, as
1183 * well as control the output with a filter.
1185 * The 'get_terms' filter will be called when the cache has the term and will
1186 * pass the found term along with the array of $taxonomies and array of $args.
1187 * This filter is also called before the array of terms is passed and will pass
1188 * the array of terms, along with the $taxonomies and $args.
1190 * The 'list_terms_exclusions' filter passes the compiled exclusions along with
1193 * The 'get_terms_orderby' filter passes the ORDER BY clause for the query
1194 * along with the $args array.
1196 * The 'get_terms_fields' filter passes the fields for the SELECT query
1197 * along with the $args array.
1199 * The list of arguments that $args can contain, which will overwrite the defaults:
1201 * orderby - Default is 'name'. Can be name, count, term_group, slug or nothing
1202 * (will use term_id), Passing a custom value other than these will cause it to
1203 * order based on the custom value.
1205 * order - Default is ASC. Can use DESC.
1207 * hide_empty - Default is true. Will not return empty terms, which means
1208 * terms whose count is 0 according to the given taxonomy.
1210 * exclude - Default is an empty array. An array, comma- or space-delimited string
1211 * of term ids to exclude from the return array. If 'include' is non-empty,
1212 * 'exclude' is ignored.
1214 * exclude_tree - Default is an empty array. An array, comma- or space-delimited
1215 * string of term ids to exclude from the return array, along with all of their
1216 * descendant terms according to the primary taxonomy. If 'include' is non-empty,
1217 * 'exclude_tree' is ignored.
1219 * include - Default is an empty array. An array, comma- or space-delimited string
1220 * of term ids to include in the return array.
1222 * number - The maximum number of terms to return. Default is to return them all.
1224 * offset - The number by which to offset the terms query.
1226 * fields - Default is 'all', which returns an array of term objects.
1227 * If 'fields' is 'ids' or 'names', returns an array of
1228 * integers or strings, respectively.
1230 * slug - Returns terms whose "slug" matches this value. Default is empty string.
1232 * hierarchical - Whether to include terms that have non-empty descendants
1233 * (even if 'hide_empty' is set to true).
1235 * search - Returned terms' names will contain the value of 'search',
1236 * case-insensitive. Default is an empty string.
1238 * name__like - Returned terms' names will contain the value of 'name__like',
1239 * case-insensitive. Default is empty string.
1241 * description__like - Returned terms' descriptions will contain the value of
1242 * 'description__like', case-insensitive. Default is empty string.
1244 * The argument 'pad_counts', if set to true will include the quantity of a term's
1245 * children in the quantity of each term's "count" object variable.
1247 * The 'get' argument, if set to 'all' instead of its default empty string,
1248 * returns terms regardless of ancestry or whether the terms are empty.
1250 * The 'child_of' argument, when used, should be set to the integer of a term ID. Its default
1251 * is 0. If set to a non-zero value, all returned terms will be descendants
1252 * of that term according to the given taxonomy. Hence 'child_of' is set to 0
1253 * if more than one taxonomy is passed in $taxonomies, because multiple taxonomies
1254 * make term ancestry ambiguous.
1256 * The 'parent' argument, when used, should be set to the integer of a term ID. Its default is
1257 * the empty string '', which has a different meaning from the integer 0.
1258 * If set to an integer value, all returned terms will have as an immediate
1259 * ancestor the term whose ID is specified by that integer according to the given taxonomy.
1260 * The 'parent' argument is different from 'child_of' in that a term X is considered a 'parent'
1261 * of term Y only if term X is the father of term Y, not its grandfather or great-grandfather, etc.
1263 * The 'cache_domain' argument enables a unique cache key to be produced when this query is stored
1264 * in object cache. For instance, if you are using one of this function's filters to modify the
1265 * query (such as 'terms_clauses'), setting 'cache_domain' to a unique value will not overwrite
1266 * the cache for similar queries. Default value is 'core'.
1271 * @uses wp_parse_args() Merges the defaults with those defined by $args and allows for strings.
1273 * @param string|array $taxonomies Taxonomy name or list of Taxonomy names
1274 * @param string|array $args The values of what to search for when returning terms
1275 * @return array|WP_Error List of Term Objects and their children. Will return WP_Error, if any of $taxonomies do not exist.
1277 function get_terms($taxonomies, $args = '') {
1279 $empty_array = array();
1281 $single_taxonomy = ! is_array( $taxonomies ) || 1 === count( $taxonomies );
1282 if ( ! is_array( $taxonomies ) )
1283 $taxonomies = array( $taxonomies );
1285 foreach ( $taxonomies as $taxonomy ) {
1286 if ( ! taxonomy_exists($taxonomy) ) {
1287 $error = new WP_Error('invalid_taxonomy', __('Invalid taxonomy'));
1292 $defaults = array('orderby' => 'name', 'order' => 'ASC',
1293 'hide_empty' => true, 'exclude' => array(), 'exclude_tree' => array(), 'include' => array(),
1294 'number' => '', 'fields' => 'all', 'slug' => '', 'parent' => '',
1295 'hierarchical' => true, 'child_of' => 0, 'get' => '', 'name__like' => '', 'description__like' => '',
1296 'pad_counts' => false, 'offset' => '', 'search' => '', 'cache_domain' => 'core' );
1297 $args = wp_parse_args( $args, $defaults );
1298 $args['number'] = absint( $args['number'] );
1299 $args['offset'] = absint( $args['offset'] );
1300 if ( !$single_taxonomy || ! is_taxonomy_hierarchical( reset( $taxonomies ) ) ||
1301 ( '' !== $args['parent'] && 0 !== $args['parent'] ) ) {
1302 $args['child_of'] = 0;
1303 $args['hierarchical'] = false;
1304 $args['pad_counts'] = false;
1307 if ( 'all' == $args['get'] ) {
1308 $args['child_of'] = 0;
1309 $args['hide_empty'] = 0;
1310 $args['hierarchical'] = false;
1311 $args['pad_counts'] = false;
1315 * Filter the terms query arguments.
1319 * @param array $args An array of arguments.
1320 * @param string|array $taxonomies A taxonomy or array of taxonomies.
1322 $args = apply_filters( 'get_terms_args', $args, $taxonomies );
1324 extract($args, EXTR_SKIP);
1327 $hierarchy = _get_term_hierarchy( reset( $taxonomies ) );
1328 if ( ! isset( $hierarchy[ $child_of ] ) )
1329 return $empty_array;
1333 $hierarchy = _get_term_hierarchy( reset( $taxonomies ) );
1334 if ( ! isset( $hierarchy[ $parent ] ) )
1335 return $empty_array;
1338 // $args can be whatever, only use the args defined in defaults to compute the key
1339 $filter_key = ( has_filter('list_terms_exclusions') ) ? serialize($GLOBALS['wp_filter']['list_terms_exclusions']) : '';
1340 $key = md5( serialize( compact(array_keys($defaults)) ) . serialize( $taxonomies ) . $filter_key );
1341 $last_changed = wp_cache_get( 'last_changed', 'terms' );
1342 if ( ! $last_changed ) {
1343 $last_changed = microtime();
1344 wp_cache_set( 'last_changed', $last_changed, 'terms' );
1346 $cache_key = "get_terms:$key:$last_changed";
1347 $cache = wp_cache_get( $cache_key, 'terms' );
1348 if ( false !== $cache ) {
1351 * Filter the given taxonomy's terms cache.
1355 * @param array $cache Cached array of terms for the given taxonomy.
1356 * @param string|array $taxonomies A taxonomy or array of taxonomies.
1357 * @param array $args An array of arguments to get terms.
1359 $cache = apply_filters( 'get_terms', $cache, $taxonomies, $args );
1363 $_orderby = strtolower($orderby);
1364 if ( 'count' == $_orderby )
1365 $orderby = 'tt.count';
1366 else if ( 'name' == $_orderby )
1367 $orderby = 't.name';
1368 else if ( 'slug' == $_orderby )
1369 $orderby = 't.slug';
1370 else if ( 'term_group' == $_orderby )
1371 $orderby = 't.term_group';
1372 else if ( 'none' == $_orderby )
1374 elseif ( empty($_orderby) || 'id' == $_orderby )
1375 $orderby = 't.term_id';
1377 $orderby = 't.name';
1380 * Filter the ORDERBY clause of the terms query.
1384 * @param string $orderby ORDERBY clause of the terms query.
1385 * @param array $args An array of terms query arguments.
1386 * @param string|array $taxonomies A taxonomy or array of taxonomies.
1388 $orderby = apply_filters( 'get_terms_orderby', $orderby, $args, $taxonomies );
1390 if ( !empty($orderby) )
1391 $orderby = "ORDER BY $orderby";
1395 $order = strtoupper( $order );
1396 if ( '' !== $order && !in_array( $order, array( 'ASC', 'DESC' ) ) )
1399 $where = "tt.taxonomy IN ('" . implode("', '", $taxonomies) . "')";
1401 if ( ! empty( $include ) ) {
1404 $inclusions = implode( ',', wp_parse_id_list( $include ) );
1407 if ( ! empty( $inclusions ) ) {
1408 $inclusions = ' AND t.term_id IN ( ' . $inclusions . ' )';
1409 $where .= $inclusions;
1413 if ( ! empty( $exclude_tree ) ) {
1414 $exclude_tree = wp_parse_id_list( $exclude_tree );
1415 $excluded_children = $exclude_tree;
1416 foreach ( $exclude_tree as $extrunk ) {
1417 $excluded_children = array_merge(
1419 (array) get_terms( $taxonomies[0], array( 'child_of' => intval( $extrunk ), 'fields' => 'ids', 'hide_empty' => 0 ) )
1422 $exclusions = implode( ',', array_map( 'intval', $excluded_children ) );
1425 if ( ! empty( $exclude ) ) {
1426 $exterms = wp_parse_id_list( $exclude );
1427 if ( empty( $exclusions ) )
1428 $exclusions = implode( ',', $exterms );
1430 $exclusions .= ', ' . implode( ',', $exterms );
1433 if ( ! empty( $exclusions ) )
1434 $exclusions = ' AND t.term_id NOT IN (' . $exclusions . ')';
1437 * Filter the terms to exclude from the terms query.
1441 * @param string $exclusions NOT IN clause of the terms query.
1442 * @param array $args An array of terms query arguments.
1443 * @param string|array $taxonomies A taxonomy or array of taxonomies.
1445 $exclusions = apply_filters( 'list_terms_exclusions', $exclusions, $args, $taxonomies );
1447 if ( ! empty( $exclusions ) )
1448 $where .= $exclusions;
1450 if ( !empty($slug) ) {
1451 $slug = sanitize_title($slug);
1452 $where .= " AND t.slug = '$slug'";
1455 if ( !empty($name__like) ) {
1456 $name__like = like_escape( $name__like );
1457 $where .= $wpdb->prepare( " AND t.name LIKE %s", '%' . $name__like . '%' );
1460 if ( ! empty( $description__like ) ) {
1461 $description__like = like_escape( $description__like );
1462 $where .= $wpdb->prepare( " AND tt.description LIKE %s", '%' . $description__like . '%' );
1465 if ( '' !== $parent ) {
1466 $parent = (int) $parent;
1467 $where .= " AND tt.parent = '$parent'";
1470 if ( 'count' == $fields )
1471 $hierarchical = false;
1473 if ( $hide_empty && !$hierarchical )
1474 $where .= ' AND tt.count > 0';
1476 // don't limit the query results when we have to descend the family tree
1477 if ( $number && ! $hierarchical && ! $child_of && '' === $parent ) {
1479 $limits = 'LIMIT ' . $offset . ',' . $number;
1481 $limits = 'LIMIT ' . $number;
1486 if ( ! empty( $search ) ) {
1487 $search = like_escape( $search );
1488 $where .= $wpdb->prepare( ' AND ((t.name LIKE %s) OR (t.slug LIKE %s))', '%' . $search . '%', '%' . $search . '%' );
1492 switch ( $fields ) {
1494 $selects = array( 't.*', 'tt.*' );
1498 $selects = array( 't.term_id', 'tt.parent', 'tt.count' );
1501 $selects = array( 't.term_id', 'tt.parent', 'tt.count', 't.name' );
1506 $selects = array( 'COUNT(*)' );
1509 $selects = array( 't.term_id', 't.name' );
1512 $selects = array( 't.term_id', 't.slug' );
1519 * Filter the fields to select in the terms query.
1523 * @param array $selects An array of fields to select for the terms query.
1524 * @param array $args An array of term query arguments.
1525 * @param string|array $taxonomies A taxonomy or array of taxonomies.
1527 $fields = implode( ', ', apply_filters( 'get_terms_fields', $selects, $args, $taxonomies ) );
1529 $join = "INNER JOIN $wpdb->term_taxonomy AS tt ON t.term_id = tt.term_id";
1531 $pieces = array( 'fields', 'join', 'where', 'orderby', 'order', 'limits' );
1534 * Filter the terms query SQL clauses.
1538 * @param array $pieces Terms query SQL clauses.
1539 * @param string|array $taxonomies A taxonomy or array of taxonomies.
1540 * @param array $args An array of terms query arguments.
1542 $clauses = apply_filters( 'terms_clauses', compact( $pieces ), $taxonomies, $args );
1543 foreach ( $pieces as $piece )
1544 $$piece = isset( $clauses[ $piece ] ) ? $clauses[ $piece ] : '';
1546 $query = "SELECT $fields FROM $wpdb->terms AS t $join WHERE $where $orderby $order $limits";
1550 if ( 'count' == $fields ) {
1551 $term_count = $wpdb->get_var($query);
1555 $terms = $wpdb->get_results($query);
1556 if ( 'all' == $fields ) {
1557 update_term_cache($terms);
1560 if ( empty($terms) ) {
1561 wp_cache_add( $cache_key, array(), 'terms', DAY_IN_SECONDS );
1563 /** This filter is documented in wp-includes/taxonomy.php */
1564 $terms = apply_filters( 'get_terms', array(), $taxonomies, $args );
1569 $children = _get_term_hierarchy( reset( $taxonomies ) );
1570 if ( ! empty( $children ) )
1571 $terms = _get_term_children( $child_of, $terms, reset( $taxonomies ) );
1574 // Update term counts to include children.
1575 if ( $pad_counts && 'all' == $fields )
1576 _pad_term_counts( $terms, reset( $taxonomies ) );
1578 // Make sure we show empty categories that have children.
1579 if ( $hierarchical && $hide_empty && is_array( $terms ) ) {
1580 foreach ( $terms as $k => $term ) {
1581 if ( ! $term->count ) {
1582 $children = get_term_children( $term->term_id, reset( $taxonomies ) );
1583 if ( is_array( $children ) ) {
1584 foreach ( $children as $child_id ) {
1585 $child = get_term( $child_id, reset( $taxonomies ) );
1586 if ( $child->count ) {
1592 // It really is empty
1600 if ( 'id=>parent' == $fields ) {
1601 while ( $term = array_shift( $terms ) )
1602 $_terms[$term->term_id] = $term->parent;
1603 } elseif ( 'ids' == $fields ) {
1604 while ( $term = array_shift( $terms ) )
1605 $_terms[] = $term->term_id;
1606 } elseif ( 'names' == $fields ) {
1607 while ( $term = array_shift( $terms ) )
1608 $_terms[] = $term->name;
1609 } elseif ( 'id=>name' == $fields ) {
1610 while ( $term = array_shift( $terms ) )
1611 $_terms[$term->term_id] = $term->name;
1612 } elseif ( 'id=>slug' == $fields ) {
1613 while ( $term = array_shift( $terms ) )
1614 $_terms[$term->term_id] = $term->slug;
1617 if ( ! empty( $_terms ) )
1620 if ( $number && is_array( $terms ) && count( $terms ) > $number )
1621 $terms = array_slice( $terms, $offset, $number );
1623 wp_cache_add( $cache_key, $terms, 'terms', DAY_IN_SECONDS );
1625 /** This filter is documented in wp-includes/taxonomy */
1626 $terms = apply_filters( 'get_terms', $terms, $taxonomies, $args );
1631 * Check if Term exists.
1633 * Formerly is_term(), introduced in 2.3.0.
1639 * @param int|string $term The term to check
1640 * @param string $taxonomy The taxonomy name to use
1641 * @param int $parent ID of parent term under which to confine the exists search.
1642 * @return mixed Returns 0 if the term does not exist. Returns the term ID if no taxonomy is specified
1643 * and the term ID exists. Returns an array of the term ID and the taxonomy if the pairing exists.
1645 function term_exists($term, $taxonomy = '', $parent = 0) {
1648 $select = "SELECT term_id FROM $wpdb->terms as t WHERE ";
1649 $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 ";
1651 if ( is_int($term) ) {
1654 $where = 't.term_id = %d';
1655 if ( !empty($taxonomy) )
1656 return $wpdb->get_row( $wpdb->prepare( $tax_select . $where . " AND tt.taxonomy = %s", $term, $taxonomy ), ARRAY_A );
1658 return $wpdb->get_var( $wpdb->prepare( $select . $where, $term ) );
1661 $term = trim( wp_unslash( $term ) );
1663 if ( '' === $slug = sanitize_title($term) )
1666 $where = 't.slug = %s';
1667 $else_where = 't.name = %s';
1668 $where_fields = array($slug);
1669 $else_where_fields = array($term);
1670 if ( !empty($taxonomy) ) {
1671 $parent = (int) $parent;
1672 if ( $parent > 0 ) {
1673 $where_fields[] = $parent;
1674 $else_where_fields[] = $parent;
1675 $where .= ' AND tt.parent = %d';
1676 $else_where .= ' AND tt.parent = %d';
1679 $where_fields[] = $taxonomy;
1680 $else_where_fields[] = $taxonomy;
1682 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) )
1685 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);
1688 if ( $result = $wpdb->get_var( $wpdb->prepare("SELECT term_id FROM $wpdb->terms as t WHERE $where", $where_fields) ) )
1691 return $wpdb->get_var( $wpdb->prepare("SELECT term_id FROM $wpdb->terms as t WHERE $else_where", $else_where_fields) );
1695 * Check if a term is an ancestor of another term.
1697 * You can use either an id or the term object for both parameters.
1701 * @param int|object $term1 ID or object to check if this is the parent term.
1702 * @param int|object $term2 The child term.
1703 * @param string $taxonomy Taxonomy name that $term1 and $term2 belong to.
1704 * @return bool Whether $term2 is child of $term1
1706 function term_is_ancestor_of( $term1, $term2, $taxonomy ) {
1707 if ( ! isset( $term1->term_id ) )
1708 $term1 = get_term( $term1, $taxonomy );
1709 if ( ! isset( $term2->parent ) )
1710 $term2 = get_term( $term2, $taxonomy );
1712 if ( empty( $term1->term_id ) || empty( $term2->parent ) )
1714 if ( $term2->parent == $term1->term_id )
1717 return term_is_ancestor_of( $term1, get_term( $term2->parent, $taxonomy ), $taxonomy );
1721 * Sanitize Term all fields.
1723 * Relies on sanitize_term_field() to sanitize the term. The difference is that
1724 * this function will sanitize <strong>all</strong> fields. The context is based
1725 * on sanitize_term_field().
1727 * The $term is expected to be either an array or an object.
1731 * @uses sanitize_term_field Used to sanitize all fields in a term
1733 * @param array|object $term The term to check
1734 * @param string $taxonomy The taxonomy name to use
1735 * @param string $context Default is 'display'.
1736 * @return array|object Term with all fields sanitized
1738 function sanitize_term($term, $taxonomy, $context = 'display') {
1740 $fields = array( 'term_id', 'name', 'description', 'slug', 'count', 'parent', 'term_group', 'term_taxonomy_id', 'object_id' );
1742 $do_object = is_object( $term );
1744 $term_id = $do_object ? $term->term_id : (isset($term['term_id']) ? $term['term_id'] : 0);
1746 foreach ( (array) $fields as $field ) {
1748 if ( isset($term->$field) )
1749 $term->$field = sanitize_term_field($field, $term->$field, $term_id, $taxonomy, $context);
1751 if ( isset($term[$field]) )
1752 $term[$field] = sanitize_term_field($field, $term[$field], $term_id, $taxonomy, $context);
1757 $term->filter = $context;
1759 $term['filter'] = $context;
1765 * Cleanse the field value in the term based on the context.
1767 * Passing a term field value through the function should be assumed to have
1768 * cleansed the value for whatever context the term field is going to be used.
1770 * If no context or an unsupported context is given, then default filters will
1773 * There are enough filters for each context to support a custom filtering
1774 * without creating your own filter function. Simply create a function that
1775 * hooks into the filter you need.
1781 * @param string $field Term field to sanitize
1782 * @param string $value Search for this term value
1783 * @param int $term_id Term ID
1784 * @param string $taxonomy Taxonomy Name
1785 * @param string $context Either edit, db, display, attribute, or js.
1786 * @return mixed sanitized field
1788 function sanitize_term_field($field, $value, $term_id, $taxonomy, $context) {
1789 $int_fields = array( 'parent', 'term_id', 'count', 'term_group', 'term_taxonomy_id', 'object_id' );
1790 if ( in_array( $field, $int_fields ) ) {
1791 $value = (int) $value;
1796 if ( 'raw' == $context )
1799 if ( 'edit' == $context ) {
1802 * Filter a term field to edit before it is sanitized.
1804 * The dynamic portion of the filter name, $field, refers to the term field.
1808 * @param mixed $value Value of the term field.
1809 * @param int $term_id Term ID.
1810 * @param string $taxonomy Taxonomy slug.
1812 $value = apply_filters( "edit_term_{$field}", $value, $term_id, $taxonomy );
1815 * Filter the taxonomy field to edit before it is sanitized.
1817 * The dynamic portions of the filter name, $taxonomy, and $field, refer
1818 * to the taxonomy slug and taxonomy field, respectively.
1822 * @param mixed $value Value of the taxonomy field to edit.
1823 * @param int $term_id Term ID.
1825 $value = apply_filters( "edit_{$taxonomy}_{$field}", $value, $term_id );
1826 if ( 'description' == $field )
1827 $value = esc_html($value); // textarea_escaped
1829 $value = esc_attr($value);
1830 } else if ( 'db' == $context ) {
1833 * Filter a term field value before it is sanitized.
1835 * The dynamic portion of the filter name, $field, refers to the term field.
1839 * @param mixed $value Value of the term field.
1840 * @param string $taxonomy Taxonomy slug.
1842 $value = apply_filters( "pre_term_{$field}", $value, $taxonomy );
1845 * Filter a taxonomy field before it is sanitized.
1847 * The dynamic portions of the filter name, $taxonomy, and $field, refer
1848 * to the taxonomy slug and field name, respectively.
1852 * @param mixed $value Value of the taxonomy field.
1854 $value = apply_filters( "pre_{$taxonomy}_{$field}", $value );
1855 // Back compat filters
1856 if ( 'slug' == $field ) {
1858 * Filter the category nicename before it is sanitized.
1860 * Use the pre_{$taxonomy}_{$field} hook instead.
1864 * @param string $value The category nicename.
1866 $value = apply_filters( 'pre_category_nicename', $value );
1869 } else if ( 'rss' == $context ) {
1872 * Filter the term field for use in RSS.
1874 * The dynamic portion of the filter name, $field, refers to the term field.
1878 * @param mixed $value Value of the term field.
1879 * @param string $taxonomy Taxonomy slug.
1881 $value = apply_filters( "term_{$field}_rss", $value, $taxonomy );
1884 * Filter the taxonomy field for use in RSS.
1886 * The dynamic portions of the hook name, $taxonomy, and $field, refer
1887 * to the taxonomy slug and field name, respectively.
1891 * @param mixed $value Value of the taxonomy field.
1893 $value = apply_filters( "{$taxonomy}_{$field}_rss", $value );
1895 // Use display filters by default.
1898 * Filter the term field sanitized for display.
1900 * The dynamic portion of the filter name, $field, refers to the term field name.
1904 * @param mixed $value Value of the term field.
1905 * @param int $term_id Term ID.
1906 * @param string $taxonomy Taxonomy slug.
1907 * @param string $context Context to retrieve the term field value.
1909 $value = apply_filters( "term_{$field}", $value, $term_id, $taxonomy, $context );
1912 * Filter the taxonomy field sanitized for display.
1914 * The dynamic portions of the filter name, $taxonomy, and $field, refer
1915 * to the taxonomy slug and taxonomy field, respectively.
1919 * @param mixed $value Value of the taxonomy field.
1920 * @param int $term_id Term ID.
1921 * @param string $context Context to retrieve the taxonomy field value.
1923 $value = apply_filters( "{$taxonomy}_{$field}", $value, $term_id, $context );
1926 if ( 'attribute' == $context )
1927 $value = esc_attr($value);
1928 else if ( 'js' == $context )
1929 $value = esc_js($value);
1935 * Count how many terms are in Taxonomy.
1937 * Default $args is 'hide_empty' which can be 'hide_empty=true' or array('hide_empty' => true).
1942 * @uses wp_parse_args() Turns strings into arrays and merges defaults into an array.
1944 * @param string $taxonomy Taxonomy name
1945 * @param array|string $args Overwrite defaults. See get_terms()
1946 * @return int|WP_Error How many terms are in $taxonomy. WP_Error if $taxonomy does not exist.
1948 function wp_count_terms( $taxonomy, $args = array() ) {
1949 $defaults = array('hide_empty' => false);
1950 $args = wp_parse_args($args, $defaults);
1952 // backwards compatibility
1953 if ( isset($args['ignore_empty']) ) {
1954 $args['hide_empty'] = $args['ignore_empty'];
1955 unset($args['ignore_empty']);
1958 $args['fields'] = 'count';
1960 return get_terms($taxonomy, $args);
1964 * Will unlink the object from the taxonomy or taxonomies.
1966 * Will remove all relationships between the object and any terms in
1967 * a particular taxonomy or taxonomies. Does not remove the term or
1971 * @uses wp_remove_object_terms()
1973 * @param int $object_id The term Object Id that refers to the term
1974 * @param string|array $taxonomies List of Taxonomy Names or single Taxonomy name.
1976 function wp_delete_object_term_relationships( $object_id, $taxonomies ) {
1977 $object_id = (int) $object_id;
1979 if ( !is_array($taxonomies) )
1980 $taxonomies = array($taxonomies);
1982 foreach ( (array) $taxonomies as $taxonomy ) {
1983 $term_ids = wp_get_object_terms( $object_id, $taxonomy, array( 'fields' => 'ids' ) );
1984 $term_ids = array_map( 'intval', $term_ids );
1985 wp_remove_object_terms( $object_id, $term_ids, $taxonomy );
1990 * Removes a term from the database.
1992 * If the term is a parent of other terms, then the children will be updated to
1993 * that term's parent.
1995 * The $args 'default' will only override the terms found, if there is only one
1996 * term found. Any other and the found terms are used.
1998 * The $args 'force_default' will force the term supplied as default to be
1999 * assigned even if the object was not going to be termless
2005 * @param int $term Term ID
2006 * @param string $taxonomy Taxonomy Name
2007 * @param array|string $args Optional. Change 'default' term id and override found term ids.
2008 * @return bool|WP_Error Returns false if not term; true if completes delete action.
2010 function wp_delete_term( $term, $taxonomy, $args = array() ) {
2013 $term = (int) $term;
2015 if ( ! $ids = term_exists($term, $taxonomy) )
2017 if ( is_wp_error( $ids ) )
2020 $tt_id = $ids['term_taxonomy_id'];
2022 $defaults = array();
2024 if ( 'category' == $taxonomy ) {
2025 $defaults['default'] = get_option( 'default_category' );
2026 if ( $defaults['default'] == $term )
2027 return 0; // Don't delete the default category
2030 $args = wp_parse_args($args, $defaults);
2031 extract($args, EXTR_SKIP);
2033 if ( isset( $default ) ) {
2034 $default = (int) $default;
2035 if ( ! term_exists($default, $taxonomy) )
2039 // Update children to point to new parent
2040 if ( is_taxonomy_hierarchical($taxonomy) ) {
2041 $term_obj = get_term($term, $taxonomy);
2042 if ( is_wp_error( $term_obj ) )
2044 $parent = $term_obj->parent;
2046 $edit_tt_ids = $wpdb->get_col( "SELECT `term_taxonomy_id` FROM $wpdb->term_taxonomy WHERE `parent` = " . (int)$term_obj->term_id );
2049 * Fires immediately before a term to delete's children are reassigned a parent.
2053 * @param array $edit_tt_ids An array of term taxonomy IDs for the given term.
2055 do_action( 'edit_term_taxonomies', $edit_tt_ids );
2056 $wpdb->update( $wpdb->term_taxonomy, compact( 'parent' ), array( 'parent' => $term_obj->term_id) + compact( 'taxonomy' ) );
2059 * Fires immediately after a term to delete's children are reassigned a parent.
2063 * @param array $edit_tt_ids An array of term taxonomy IDs for the given term.
2065 do_action( 'edited_term_taxonomies', $edit_tt_ids );
2068 $objects = $wpdb->get_col( $wpdb->prepare( "SELECT object_id FROM $wpdb->term_relationships WHERE term_taxonomy_id = %d", $tt_id ) );
2070 foreach ( (array) $objects as $object ) {
2071 $terms = wp_get_object_terms($object, $taxonomy, array('fields' => 'ids', 'orderby' => 'none'));
2072 if ( 1 == count($terms) && isset($default) ) {
2073 $terms = array($default);
2075 $terms = array_diff($terms, array($term));
2076 if (isset($default) && isset($force_default) && $force_default)
2077 $terms = array_merge($terms, array($default));
2079 $terms = array_map('intval', $terms);
2080 wp_set_object_terms($object, $terms, $taxonomy);
2083 // Clean the relationship caches for all object types using this term
2084 $tax_object = get_taxonomy( $taxonomy );
2085 foreach ( $tax_object->object_type as $object_type )
2086 clean_object_term_cache( $objects, $object_type );
2088 // Get the object before deletion so we can pass to actions below
2089 $deleted_term = get_term( $term, $taxonomy );
2092 * Fires immediately before a term taxonomy ID is deleted.
2096 * @param int $tt_id Term taxonomy ID.
2098 do_action( 'delete_term_taxonomy', $tt_id );
2099 $wpdb->delete( $wpdb->term_taxonomy, array( 'term_taxonomy_id' => $tt_id ) );
2102 * Fires immediately after a term taxonomy ID is deleted.
2106 * @param int $tt_id Term taxonomy ID.
2108 do_action( 'deleted_term_taxonomy', $tt_id );
2110 // Delete the term if no taxonomies use it.
2111 if ( !$wpdb->get_var( $wpdb->prepare( "SELECT COUNT(*) FROM $wpdb->term_taxonomy WHERE term_id = %d", $term) ) )
2112 $wpdb->delete( $wpdb->terms, array( 'term_id' => $term ) );
2114 clean_term_cache($term, $taxonomy);
2117 * Fires after a term is deleted from the database and the cache is cleaned.
2121 * @param int $term Term ID.
2122 * @param int $tt_id Term taxonomy ID.
2123 * @param string $taxonomy Taxonomy slug.
2124 * @param mixed $deleted_term Copy of the already-deleted term, in the form specified
2125 * by the parent function. WP_Error otherwise.
2127 do_action( 'delete_term', $term, $tt_id, $taxonomy, $deleted_term );
2130 * Fires after a term in a specific taxonomy is deleted.
2132 * The dynamic portion of the hook name, $taxonomy, refers to the specific
2133 * taxonomy the term belonged to.
2137 * @param int $term Term ID.
2138 * @param int $tt_id Term taxonomy ID.
2139 * @param mixed $deleted_term Copy of the already-deleted term, in the form specified
2140 * by the parent function. WP_Error otherwise.
2142 do_action( "delete_$taxonomy", $term, $tt_id, $deleted_term );
2148 * Deletes one existing category.
2151 * @uses wp_delete_term()
2153 * @param int $cat_ID
2154 * @return mixed Returns true if completes delete action; false if term doesn't exist;
2155 * Zero on attempted deletion of default Category; WP_Error object is also a possibility.
2157 function wp_delete_category( $cat_ID ) {
2158 return wp_delete_term( $cat_ID, 'category' );
2162 * Retrieves the terms associated with the given object(s), in the supplied taxonomies.
2164 * The following information has to do the $args parameter and for what can be
2165 * contained in the string or array of that parameter, if it exists.
2167 * The first argument is called, 'orderby' and has the default value of 'name'.
2168 * The other value that is supported is 'count'.
2170 * The second argument is called, 'order' and has the default value of 'ASC'.
2171 * The only other value that will be acceptable is 'DESC'.
2173 * The final argument supported is called, 'fields' and has the default value of
2174 * 'all'. There are multiple other options that can be used instead. Supported
2175 * values are as follows: 'all', 'ids', 'names', and finally
2176 * 'all_with_object_id'.
2178 * The fields argument also decides what will be returned. If 'all' or
2179 * 'all_with_object_id' is chosen or the default kept intact, then all matching
2180 * terms objects will be returned. If either 'ids' or 'names' is used, then an
2181 * array of all matching term ids or term names will be returned respectively.
2186 * @param int|array $object_ids The ID(s) of the object(s) to retrieve.
2187 * @param string|array $taxonomies The taxonomies to retrieve terms from.
2188 * @param array|string $args Change what is returned
2189 * @return array|WP_Error The requested term data or empty array if no terms found. WP_Error if any of the $taxonomies don't exist.
2191 function wp_get_object_terms($object_ids, $taxonomies, $args = array()) {
2194 if ( empty( $object_ids ) || empty( $taxonomies ) )
2197 if ( !is_array($taxonomies) )
2198 $taxonomies = array($taxonomies);
2200 foreach ( $taxonomies as $taxonomy ) {
2201 if ( ! taxonomy_exists($taxonomy) )
2202 return new WP_Error('invalid_taxonomy', __('Invalid taxonomy'));
2205 if ( !is_array($object_ids) )
2206 $object_ids = array($object_ids);
2207 $object_ids = array_map('intval', $object_ids);
2209 $defaults = array('orderby' => 'name', 'order' => 'ASC', 'fields' => 'all');
2210 $args = wp_parse_args( $args, $defaults );
2213 if ( count($taxonomies) > 1 ) {
2214 foreach ( $taxonomies as $index => $taxonomy ) {
2215 $t = get_taxonomy($taxonomy);
2216 if ( isset($t->args) && is_array($t->args) && $args != array_merge($args, $t->args) ) {
2217 unset($taxonomies[$index]);
2218 $terms = array_merge($terms, wp_get_object_terms($object_ids, $taxonomy, array_merge($args, $t->args)));
2222 $t = get_taxonomy($taxonomies[0]);
2223 if ( isset($t->args) && is_array($t->args) )
2224 $args = array_merge($args, $t->args);
2227 extract($args, EXTR_SKIP);
2229 if ( 'count' == $orderby )
2230 $orderby = 'tt.count';
2231 else if ( 'name' == $orderby )
2232 $orderby = 't.name';
2233 else if ( 'slug' == $orderby )
2234 $orderby = 't.slug';
2235 else if ( 'term_group' == $orderby )
2236 $orderby = 't.term_group';
2237 else if ( 'term_order' == $orderby )
2238 $orderby = 'tr.term_order';
2239 else if ( 'none' == $orderby ) {
2243 $orderby = 't.term_id';
2246 // tt_ids queries can only be none or tr.term_taxonomy_id
2247 if ( ('tt_ids' == $fields) && !empty($orderby) )
2248 $orderby = 'tr.term_taxonomy_id';
2250 if ( !empty($orderby) )
2251 $orderby = "ORDER BY $orderby";
2253 $order = strtoupper( $order );
2254 if ( '' !== $order && ! in_array( $order, array( 'ASC', 'DESC' ) ) )
2257 $taxonomies = "'" . implode("', '", $taxonomies) . "'";
2258 $object_ids = implode(', ', $object_ids);
2261 if ( 'all' == $fields )
2262 $select_this = 't.*, tt.*';
2263 else if ( 'ids' == $fields )
2264 $select_this = 't.term_id';
2265 else if ( 'names' == $fields )
2266 $select_this = 't.name';
2267 else if ( 'slugs' == $fields )
2268 $select_this = 't.slug';
2269 else if ( 'all_with_object_id' == $fields )
2270 $select_this = 't.*, tt.*, tr.object_id';
2272 $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";
2274 if ( 'all' == $fields || 'all_with_object_id' == $fields ) {
2275 $_terms = $wpdb->get_results( $query );
2276 foreach ( $_terms as $key => $term ) {
2277 $_terms[$key] = sanitize_term( $term, $taxonomy, 'raw' );
2279 $terms = array_merge( $terms, $_terms );
2280 update_term_cache( $terms );
2281 } else if ( 'ids' == $fields || 'names' == $fields || 'slugs' == $fields ) {
2282 $_terms = $wpdb->get_col( $query );
2283 $_field = ( 'ids' == $fields ) ? 'term_id' : 'name';
2284 foreach ( $_terms as $key => $term ) {
2285 $_terms[$key] = sanitize_term_field( $_field, $term, $term, $taxonomy, 'raw' );
2287 $terms = array_merge( $terms, $_terms );
2288 } else if ( 'tt_ids' == $fields ) {
2289 $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");
2290 foreach ( $terms as $key => $tt_id ) {
2291 $terms[$key] = sanitize_term_field( 'term_taxonomy_id', $tt_id, 0, $taxonomy, 'raw' ); // 0 should be the term id, however is not needed when using raw context.
2299 * Filter the terms for a given object or objects.
2303 * @param array $terms An array of terms for the given object or objects.
2304 * @param array|int $object_ids Object ID or array of IDs.
2305 * @param array|string $taxonomies A taxonomy or array of taxonomies.
2306 * @param array $args An array of arguments for retrieving terms for
2307 * the given object(s).
2309 return apply_filters( 'wp_get_object_terms', $terms, $object_ids, $taxonomies, $args );
2313 * Add a new term to the database.
2315 * A non-existent term is inserted in the following sequence:
2316 * 1. The term is added to the term table, then related to the taxonomy.
2317 * 2. If everything is correct, several actions are fired.
2318 * 3. The 'term_id_filter' is evaluated.
2319 * 4. The term cache is cleaned.
2320 * 5. Several more actions are fired.
2321 * 6. An array is returned containing the term_id and term_taxonomy_id.
2323 * If the 'slug' argument is not empty, then it is checked to see if the term
2324 * is invalid. If it is not a valid, existing term, it is added and the term_id
2327 * If the taxonomy is hierarchical, and the 'parent' argument is not empty,
2328 * the term is inserted and the term_id will be given.
2331 * If $taxonomy does not exist or $term is empty,
2332 * a WP_Error object will be returned.
2334 * If the term already exists on the same hierarchical level,
2335 * or the term slug and name are not unique, a WP_Error object will be returned.
2337 * @global wpdb $wpdb The WordPress database object.
2341 * @param string $term The term to add or update.
2342 * @param string $taxonomy The taxonomy to which to add the term
2343 * @param array|string $args {
2344 * Arguments to change values of the inserted term.
2346 * @type string 'alias_of' Slug of the term to make this term an alias of.
2347 * Default empty string. Accepts a term slug.
2348 * @type string 'description' The term description.
2349 * Default empty string.
2350 * @type int 'parent' The id of the parent term.
2352 * @type string 'slug' The term slug to use.
2353 * Default empty string.
2355 * @return array|WP_Error An array containing the term_id and term_taxonomy_id, WP_Error otherwise.
2357 function wp_insert_term( $term, $taxonomy, $args = array() ) {
2360 if ( ! taxonomy_exists($taxonomy) )
2361 return new WP_Error('invalid_taxonomy', __('Invalid taxonomy'));
2364 * Filter a term before it is sanitized and inserted into the database.
2368 * @param string $term The term to add or update.
2369 * @param string $taxonomy Taxonomy slug.
2371 $term = apply_filters( 'pre_insert_term', $term, $taxonomy );
2372 if ( is_wp_error( $term ) )
2375 if ( is_int($term) && 0 == $term )
2376 return new WP_Error('invalid_term_id', __('Invalid term ID'));
2378 if ( '' == trim($term) )
2379 return new WP_Error('empty_term_name', __('A name is required for this term'));
2381 $defaults = array( 'alias_of' => '', 'description' => '', 'parent' => 0, 'slug' => '');
2382 $args = wp_parse_args($args, $defaults);
2383 $args['name'] = $term;
2384 $args['taxonomy'] = $taxonomy;
2385 $args = sanitize_term($args, $taxonomy, 'db');
2386 extract($args, EXTR_SKIP);
2388 // expected_slashed ($name)
2389 $name = wp_unslash($name);
2390 $description = wp_unslash($description);
2392 $slug_provided = ! empty( $slug );
2393 if ( ! $slug_provided ) {
2394 $slug = sanitize_title($name);
2399 $alias = $wpdb->get_row( $wpdb->prepare( "SELECT term_id, term_group FROM $wpdb->terms WHERE slug = %s", $alias_of) );
2400 if ( $alias->term_group ) {
2401 // The alias we want is already in a group, so let's use that one.
2402 $term_group = $alias->term_group;
2404 // The alias isn't in a group, so let's create a new one and firstly add the alias term to it.
2405 $term_group = $wpdb->get_var("SELECT MAX(term_group) FROM $wpdb->terms") + 1;
2408 * Fires immediately before the given terms are edited.
2412 * @param int $term_id Term ID.
2413 * @param string $taxonomy Taxonomy slug.
2415 do_action( 'edit_terms', $alias->term_id, $taxonomy );
2416 $wpdb->update($wpdb->terms, compact('term_group'), array('term_id' => $alias->term_id) );
2419 * Fires immediately after the given terms are edited.
2423 * @param int $term_id Term ID
2424 * @param string $taxonomy Taxonomy slug.
2426 do_action( 'edited_terms', $alias->term_id, $taxonomy );
2430 if ( $term_id = term_exists($slug) ) {
2431 $existing_term = $wpdb->get_row( $wpdb->prepare( "SELECT name FROM $wpdb->terms WHERE term_id = %d", $term_id), ARRAY_A );
2432 // We've got an existing term in the same taxonomy, which matches the name of the new term:
2433 if ( is_taxonomy_hierarchical($taxonomy) && $existing_term['name'] == $name && $exists = term_exists( (int) $term_id, $taxonomy ) ) {
2434 // Hierarchical, and it matches an existing term, Do not allow same "name" in the same level.
2435 $siblings = get_terms($taxonomy, array('fields' => 'names', 'get' => 'all', 'parent' => (int)$parent) );
2436 if ( in_array($name, $siblings) ) {
2437 if ( $slug_provided ) {
2438 return new WP_Error( 'term_exists', __( 'A term with the name and slug provided already exists with this parent.' ), $exists['term_id'] );
2440 return new WP_Error( 'term_exists', __( 'A term with the name provided already exists with this parent.' ), $exists['term_id'] );
2443 $slug = wp_unique_term_slug($slug, (object) $args);
2444 if ( false === $wpdb->insert( $wpdb->terms, compact( 'name', 'slug', 'term_group' ) ) )
2445 return new WP_Error('db_insert_error', __('Could not insert term into the database'), $wpdb->last_error);
2446 $term_id = (int) $wpdb->insert_id;
2448 } elseif ( $existing_term['name'] != $name ) {
2449 // We've got an existing term, with a different name, Create the new term.
2450 $slug = wp_unique_term_slug($slug, (object) $args);
2451 if ( false === $wpdb->insert( $wpdb->terms, compact( 'name', 'slug', 'term_group' ) ) )
2452 return new WP_Error('db_insert_error', __('Could not insert term into the database'), $wpdb->last_error);
2453 $term_id = (int) $wpdb->insert_id;
2454 } elseif ( $exists = term_exists( (int) $term_id, $taxonomy ) ) {
2455 // Same name, same slug.
2456 return new WP_Error( 'term_exists', __( 'A term with the name and slug provided already exists.' ), $exists['term_id'] );
2459 // This term does not exist at all in the database, Create it.
2460 $slug = wp_unique_term_slug($slug, (object) $args);
2461 if ( false === $wpdb->insert( $wpdb->terms, compact( 'name', 'slug', 'term_group' ) ) )
2462 return new WP_Error('db_insert_error', __('Could not insert term into the database'), $wpdb->last_error);
2463 $term_id = (int) $wpdb->insert_id;
2466 // Seems unreachable, However, Is used in the case that a term name is provided, which sanitizes to an empty string.
2467 if ( empty($slug) ) {
2468 $slug = sanitize_title($slug, $term_id);
2470 /** This action is documented in wp-includes/taxonomy.php */
2471 do_action( 'edit_terms', $term_id, $taxonomy );
2472 $wpdb->update( $wpdb->terms, compact( 'slug' ), compact( 'term_id' ) );
2474 /** This action is documented in wp-includes/taxonomy.php */
2475 do_action( 'edited_terms', $term_id, $taxonomy );
2478 $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 ) );
2480 if ( !empty($tt_id) )
2481 return array('term_id' => $term_id, 'term_taxonomy_id' => $tt_id);
2483 $wpdb->insert( $wpdb->term_taxonomy, compact( 'term_id', 'taxonomy', 'description', 'parent') + array( 'count' => 0 ) );
2484 $tt_id = (int) $wpdb->insert_id;
2487 * Fires immediately after a new term is created, before the term cache is cleaned.
2491 * @param int $term_id Term ID.
2492 * @param int $tt_id Term taxonomy ID.
2493 * @param string $taxonomy Taxonomy slug.
2495 do_action( "create_term", $term_id, $tt_id, $taxonomy );
2498 * Fires after a new term is created for a specific taxonomy.
2500 * The dynamic portion of the hook name, $taxonomy, refers
2501 * to the slug of the taxonomy the term was created for.
2505 * @param int $term_id Term ID.
2506 * @param int $tt_id Term taxonomy ID.
2508 do_action( "create_$taxonomy", $term_id, $tt_id );
2511 * Filter the term ID after a new term is created.
2515 * @param int $term_id Term ID.
2516 * @param int $tt_id Taxonomy term ID.
2518 $term_id = apply_filters( 'term_id_filter', $term_id, $tt_id );
2520 clean_term_cache($term_id, $taxonomy);
2523 * Fires after a new term is created, and after the term cache has been cleaned.
2527 do_action( "created_term", $term_id, $tt_id, $taxonomy );
2530 * Fires after a new term in a specific taxonomy is created, and after the term
2531 * cache has been cleaned.
2535 * @param int $term_id Term ID.
2536 * @param int $tt_id Term taxonomy ID.
2538 do_action( "created_$taxonomy", $term_id, $tt_id );
2540 return array('term_id' => $term_id, 'term_taxonomy_id' => $tt_id);
2544 * Create Term and Taxonomy Relationships.
2546 * Relates an object (post, link etc) to a term and taxonomy type. Creates the
2547 * term and taxonomy relationship if it doesn't already exist. Creates a term if
2548 * it doesn't exist (using the slug).
2550 * A relationship means that the term is grouped in or belongs to the taxonomy.
2551 * A term has no meaning until it is given context by defining which taxonomy it
2555 * @uses wp_remove_object_terms()
2557 * @param int $object_id The object to relate to.
2558 * @param array|int|string $terms The slug or id of the term, will replace all existing
2559 * related terms in this taxonomy.
2560 * @param array|string $taxonomy The context in which to relate the term to the object.
2561 * @param bool $append If false will delete difference of terms.
2562 * @return array|WP_Error Affected Term IDs
2564 function wp_set_object_terms($object_id, $terms, $taxonomy, $append = false) {
2567 $object_id = (int) $object_id;
2569 if ( ! taxonomy_exists($taxonomy) )
2570 return new WP_Error('invalid_taxonomy', __('Invalid taxonomy'));
2572 if ( !is_array($terms) )
2573 $terms = array($terms);
2576 $old_tt_ids = wp_get_object_terms($object_id, $taxonomy, array('fields' => 'tt_ids', 'orderby' => 'none'));
2578 $old_tt_ids = array();
2581 $term_ids = array();
2582 $new_tt_ids = array();
2584 foreach ( (array) $terms as $term) {
2585 if ( !strlen(trim($term)) )
2588 if ( !$term_info = term_exists($term, $taxonomy) ) {
2589 // Skip if a non-existent term ID is passed.
2590 if ( is_int($term) )
2592 $term_info = wp_insert_term($term, $taxonomy);
2594 if ( is_wp_error($term_info) )
2596 $term_ids[] = $term_info['term_id'];
2597 $tt_id = $term_info['term_taxonomy_id'];
2600 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 ) ) )
2604 * Fires immediately before an object-term relationship is added.
2608 * @param int $object_id Object ID.
2609 * @param int $tt_id Term taxonomy ID.
2611 do_action( 'add_term_relationship', $object_id, $tt_id );
2612 $wpdb->insert( $wpdb->term_relationships, array( 'object_id' => $object_id, 'term_taxonomy_id' => $tt_id ) );
2615 * Fires immediately after an object-term relationship is added.
2619 * @param int $object_id Object ID.
2620 * @param int $tt_id Term taxonomy ID.
2622 do_action( 'added_term_relationship', $object_id, $tt_id );
2623 $new_tt_ids[] = $tt_id;
2627 wp_update_term_count( $new_tt_ids, $taxonomy );
2630 $delete_tt_ids = array_diff( $old_tt_ids, $tt_ids );
2632 if ( $delete_tt_ids ) {
2633 $in_delete_tt_ids = "'" . implode( "', '", $delete_tt_ids ) . "'";
2634 $delete_term_ids = $wpdb->get_col( $wpdb->prepare( "SELECT tt.term_id FROM $wpdb->term_taxonomy AS tt WHERE tt.taxonomy = %s AND tt.term_taxonomy_id IN ($in_delete_tt_ids)", $taxonomy ) );
2635 $delete_term_ids = array_map( 'intval', $delete_term_ids );
2637 $remove = wp_remove_object_terms( $object_id, $delete_term_ids, $taxonomy );
2638 if ( is_wp_error( $remove ) ) {
2644 $t = get_taxonomy($taxonomy);
2645 if ( ! $append && isset($t->sort) && $t->sort ) {
2648 $final_tt_ids = wp_get_object_terms($object_id, $taxonomy, array('fields' => 'tt_ids'));
2649 foreach ( $tt_ids as $tt_id )
2650 if ( in_array($tt_id, $final_tt_ids) )
2651 $values[] = $wpdb->prepare( "(%d, %d, %d)", $object_id, $tt_id, ++$term_order);
2653 if ( false === $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)" ) )
2654 return new WP_Error( 'db_insert_error', __( 'Could not insert term relationship into the database' ), $wpdb->last_error );
2657 wp_cache_delete( $object_id, $taxonomy . '_relationships' );
2660 * Fires after an object's terms have been set.
2664 * @param int $object_id Object ID.
2665 * @param array $terms An array of object terms.
2666 * @param array $tt_ids An array of term taxonomy IDs.
2667 * @param string $taxonomy Taxonomy slug.
2668 * @param bool $append Whether to append new terms to the old terms.
2669 * @param array $old_tt_ids Old array of term taxonomy IDs.
2671 do_action( 'set_object_terms', $object_id, $terms, $tt_ids, $taxonomy, $append, $old_tt_ids );
2676 * Add term(s) associated with a given object.
2679 * @uses wp_set_object_terms()
2681 * @param int $object_id The ID of the object to which the terms will be added.
2682 * @param array|int|string $terms The slug(s) or ID(s) of the term(s) to add.
2683 * @param array|string $taxonomy Taxonomy name.
2684 * @return array|WP_Error Affected Term IDs
2686 function wp_add_object_terms( $object_id, $terms, $taxonomy ) {
2687 return wp_set_object_terms( $object_id, $terms, $taxonomy, true );
2691 * Remove term(s) associated with a given object.
2696 * @param int $object_id The ID of the object from which the terms will be removed.
2697 * @param array|int|string $terms The slug(s) or ID(s) of the term(s) to remove.
2698 * @param array|string $taxonomy Taxonomy name.
2699 * @return bool|WP_Error True on success, false or WP_Error on failure.
2701 function wp_remove_object_terms( $object_id, $terms, $taxonomy ) {
2704 $object_id = (int) $object_id;
2706 if ( ! taxonomy_exists( $taxonomy ) ) {
2707 return new WP_Error( 'invalid_taxonomy', __( 'Invalid Taxonomy' ) );
2710 if ( ! is_array( $terms ) ) {
2711 $terms = array( $terms );
2716 foreach ( (array) $terms as $term ) {
2717 if ( ! strlen( trim( $term ) ) ) {
2721 if ( ! $term_info = term_exists( $term, $taxonomy ) ) {
2722 // Skip if a non-existent term ID is passed.
2723 if ( is_int( $term ) ) {
2728 if ( is_wp_error( $term_info ) ) {
2732 $tt_ids[] = $term_info['term_taxonomy_id'];
2736 $in_tt_ids = "'" . implode( "', '", $tt_ids ) . "'";
2739 * Fires immediately before an object-term relationship is deleted.
2743 * @param int $object_id Object ID.
2744 * @param array $tt_ids An array of term taxonomy IDs.
2746 do_action( 'delete_term_relationships', $object_id, $tt_ids );
2747 $deleted = $wpdb->query( $wpdb->prepare( "DELETE FROM $wpdb->term_relationships WHERE object_id = %d AND term_taxonomy_id IN ($in_tt_ids)", $object_id ) );
2750 * Fires immediately after an object-term relationship is deleted.
2754 * @param int $object_id Object ID.
2755 * @param array $tt_ids An array of term taxonomy IDs.
2757 do_action( 'deleted_term_relationships', $object_id, $tt_ids );
2758 wp_update_term_count( $tt_ids, $taxonomy );
2760 return (bool) $deleted;
2767 * Will make slug unique, if it isn't already.
2769 * The $slug has to be unique global to every taxonomy, meaning that one
2770 * taxonomy term can't have a matching slug with another taxonomy term. Each
2771 * slug has to be globally unique for every taxonomy.
2773 * The way this works is that if the taxonomy that the term belongs to is
2774 * hierarchical and has a parent, it will append that parent to the $slug.
2776 * If that still doesn't return an unique slug, then it try to append a number
2777 * until it finds a number that is truly unique.
2779 * The only purpose for $term is for appending a parent, if one exists.
2784 * @param string $slug The string that will be tried for a unique slug
2785 * @param object $term The term object that the $slug will belong too
2786 * @return string Will return a true unique slug.
2788 function wp_unique_term_slug($slug, $term) {
2791 if ( ! term_exists( $slug ) )
2794 // If the taxonomy supports hierarchy and the term has a parent, make the slug unique
2795 // by incorporating parent slugs.
2796 if ( is_taxonomy_hierarchical($term->taxonomy) && !empty($term->parent) ) {
2797 $the_parent = $term->parent;
2798 while ( ! empty($the_parent) ) {
2799 $parent_term = get_term($the_parent, $term->taxonomy);
2800 if ( is_wp_error($parent_term) || empty($parent_term) )
2802 $slug .= '-' . $parent_term->slug;
2803 if ( ! term_exists( $slug ) )
2806 if ( empty($parent_term->parent) )
2808 $the_parent = $parent_term->parent;
2812 // If we didn't get a unique slug, try appending a number to make it unique.
2813 if ( ! empty( $term->term_id ) )
2814 $query = $wpdb->prepare( "SELECT slug FROM $wpdb->terms WHERE slug = %s AND term_id != %d", $slug, $term->term_id );
2816 $query = $wpdb->prepare( "SELECT slug FROM $wpdb->terms WHERE slug = %s", $slug );
2818 if ( $wpdb->get_var( $query ) ) {
2821 $alt_slug = $slug . "-$num";
2823 $slug_check = $wpdb->get_var( $wpdb->prepare( "SELECT slug FROM $wpdb->terms WHERE slug = %s", $alt_slug ) );
2824 } while ( $slug_check );
2832 * Update term based on arguments provided.
2834 * The $args will indiscriminately override all values with the same field name.
2835 * Care must be taken to not override important information need to update or
2836 * update will fail (or perhaps create a new term, neither would be acceptable).
2838 * Defaults will set 'alias_of', 'description', 'parent', and 'slug' if not
2839 * defined in $args already.
2841 * 'alias_of' will create a term group, if it doesn't already exist, and update
2844 * If the 'slug' argument in $args is missing, then the 'name' in $args will be
2845 * used. It should also be noted that if you set 'slug' and it isn't unique then
2846 * a WP_Error will be passed back. If you don't pass any slug, then a unique one
2847 * will be created for you.
2849 * For what can be overrode in $args, check the term scheme can contain and stay
2850 * away from the term keys.
2856 * @param int $term_id The ID of the term
2857 * @param string $taxonomy The context in which to relate the term to the object.
2858 * @param array|string $args Overwrite term field values
2859 * @return array|WP_Error Returns Term ID and Taxonomy Term ID
2861 function wp_update_term( $term_id, $taxonomy, $args = array() ) {
2864 if ( ! taxonomy_exists($taxonomy) )
2865 return new WP_Error('invalid_taxonomy', __('Invalid taxonomy'));
2867 $term_id = (int) $term_id;
2869 // First, get all of the original args
2870 $term = get_term ($term_id, $taxonomy, ARRAY_A);
2872 if ( is_wp_error( $term ) )
2875 // Escape data pulled from DB.
2876 $term = wp_slash($term);
2878 // Merge old and new args with new args overwriting old ones.
2879 $args = array_merge($term, $args);
2881 $defaults = array( 'alias_of' => '', 'description' => '', 'parent' => 0, 'slug' => '');
2882 $args = wp_parse_args($args, $defaults);
2883 $args = sanitize_term($args, $taxonomy, 'db');
2884 extract($args, EXTR_SKIP);
2886 // expected_slashed ($name)
2887 $name = wp_unslash($name);
2888 $description = wp_unslash($description);
2890 if ( '' == trim($name) )
2891 return new WP_Error('empty_term_name', __('A name is required for this term'));
2893 $empty_slug = false;
2894 if ( empty($slug) ) {
2896 $slug = sanitize_title($name);
2900 $alias = $wpdb->get_row( $wpdb->prepare( "SELECT term_id, term_group FROM $wpdb->terms WHERE slug = %s", $alias_of) );
2901 if ( $alias->term_group ) {
2902 // The alias we want is already in a group, so let's use that one.
2903 $term_group = $alias->term_group;
2905 // The alias isn't in a group, so let's create a new one and firstly add the alias term to it.
2906 $term_group = $wpdb->get_var("SELECT MAX(term_group) FROM $wpdb->terms") + 1;
2908 /** This action is documented in wp-includes/taxonomy.php */
2909 do_action( 'edit_terms', $alias->term_id, $taxonomy );
2910 $wpdb->update( $wpdb->terms, compact('term_group'), array( 'term_id' => $alias->term_id ) );
2912 /** This action is documented in wp-includes/taxonomy.php */
2913 do_action( 'edited_terms', $alias->term_id, $taxonomy );
2918 * Filter the term parent.
2920 * Hook to this filter to see if it will cause a hierarchy loop.
2924 * @param int $parent ID of the parent term.
2925 * @param int $term_id Term ID.
2926 * @param string $taxonomy Taxonomy slug.
2927 * @param array $args Compacted array of update arguments for the given term.
2928 * @param array $args An array of update arguments for the given term.
2930 $parent = apply_filters( 'wp_update_term_parent', $parent, $term_id, $taxonomy, compact( array_keys( $args ) ), $args );
2932 // Check for duplicate slug
2933 $id = $wpdb->get_var( $wpdb->prepare( "SELECT term_id FROM $wpdb->terms WHERE slug = %s", $slug ) );
2934 if ( $id && ($id != $term_id) ) {
2935 // If an empty slug was passed or the parent changed, reset the slug to something unique.
2937 if ( $empty_slug || ( $parent != $term['parent']) )
2938 $slug = wp_unique_term_slug($slug, (object) $args);
2940 return new WP_Error('duplicate_term_slug', sprintf(__('The slug “%s” is already in use by another term'), $slug));
2943 /** This action is documented in wp-includes/taxonomy.php */
2944 do_action( 'edit_terms', $term_id, $taxonomy );
2945 $wpdb->update($wpdb->terms, compact( 'name', 'slug', 'term_group' ), compact( 'term_id' ) );
2946 if ( empty($slug) ) {
2947 $slug = sanitize_title($name, $term_id);
2948 $wpdb->update( $wpdb->terms, compact( 'slug' ), compact( 'term_id' ) );
2951 /** This action is documented in wp-includes/taxonomy.php */
2952 do_action( 'edited_terms', $term_id, $taxonomy );
2954 $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) );
2957 * Fires immediate before a term-taxonomy relationship is updated.
2961 * @param int $tt_id Term taxonomy ID.
2962 * @param string $taxonomy Taxonomy slug.
2964 do_action( 'edit_term_taxonomy', $tt_id, $taxonomy );
2965 $wpdb->update( $wpdb->term_taxonomy, compact( 'term_id', 'taxonomy', 'description', 'parent' ), array( 'term_taxonomy_id' => $tt_id ) );
2968 * Fires immediately after a term-taxonomy relationship is updated.
2972 * @param int $tt_id Term taxonomy ID.
2973 * @param string $taxonomy Taxonomy slug.
2975 do_action( 'edited_term_taxonomy', $tt_id, $taxonomy );
2977 // Clean the relationship caches for all object types using this term
2978 $objects = $wpdb->get_col( $wpdb->prepare( "SELECT object_id FROM $wpdb->term_relationships WHERE term_taxonomy_id = %d", $tt_id ) );
2979 $tax_object = get_taxonomy( $taxonomy );
2980 foreach ( $tax_object->object_type as $object_type ) {
2981 clean_object_term_cache( $objects, $object_type );
2985 * Fires after a term has been updated, but before the term cache has been cleaned.
2989 * @param int $term_id Term ID.
2990 * @param int $tt_id Term taxonomy ID.
2991 * @param string $taxonomy Taxonomy slug.
2993 do_action( "edit_term", $term_id, $tt_id, $taxonomy );
2996 * Fires after a term in a specific taxonomy has been updated, but before the term
2997 * cache has been cleaned.
2999 * The dynamic portion of the hook name, $taxonomy, refers to the taxonomy slug.
3003 * @param int $term_id Term ID.
3004 * @param int $tt_id Term taxonomy ID.
3006 do_action( "edit_$taxonomy", $term_id, $tt_id );
3008 /** This filter is documented in wp-includes/taxonomy.php */
3009 $term_id = apply_filters( 'term_id_filter', $term_id, $tt_id );
3011 clean_term_cache($term_id, $taxonomy);
3014 * Fires after a term has been updated, and the term cache has been cleaned.
3018 * @param int $term_id Term ID.
3019 * @param int $tt_id Term taxonomy ID.
3020 * @param string $taxonomy Taxonomy slug.
3022 do_action( "edited_term", $term_id, $tt_id, $taxonomy );
3025 * Fires after a term for a specific taxonomy has been updated, and the term
3026 * cache has been cleaned.
3028 * The dynamic portion of the hook name, $taxonomy, refers to the taxonomy slug.
3032 * @param int $term_id Term ID.
3033 * @param int $tt_id Term taxonomy ID.
3035 do_action( "edited_$taxonomy", $term_id, $tt_id );
3037 return array('term_id' => $term_id, 'term_taxonomy_id' => $tt_id);
3041 * Enable or disable term counting.
3045 * @param bool $defer Optional. Enable if true, disable if false.
3046 * @return bool Whether term counting is enabled or disabled.
3048 function wp_defer_term_counting($defer=null) {
3049 static $_defer = false;
3051 if ( is_bool($defer) ) {
3053 // flush any deferred counts
3055 wp_update_term_count( null, null, true );
3062 * Updates the amount of terms in taxonomy.
3064 * If there is a taxonomy callback applied, then it will be called for updating
3067 * The default action is to count what the amount of terms have the relationship
3068 * of term ID. Once that is done, then update the database.
3073 * @param int|array $terms The term_taxonomy_id of the terms
3074 * @param string $taxonomy The context of the term.
3075 * @return bool If no terms will return false, and if successful will return true.
3077 function wp_update_term_count( $terms, $taxonomy, $do_deferred=false ) {
3078 static $_deferred = array();
3080 if ( $do_deferred ) {
3081 foreach ( (array) array_keys($_deferred) as $tax ) {
3082 wp_update_term_count_now( $_deferred[$tax], $tax );
3083 unset( $_deferred[$tax] );
3087 if ( empty($terms) )
3090 if ( !is_array($terms) )
3091 $terms = array($terms);
3093 if ( wp_defer_term_counting() ) {
3094 if ( !isset($_deferred[$taxonomy]) )
3095 $_deferred[$taxonomy] = array();
3096 $_deferred[$taxonomy] = array_unique( array_merge($_deferred[$taxonomy], $terms) );
3100 return wp_update_term_count_now( $terms, $taxonomy );
3104 * Perform term count update immediately.
3108 * @param array $terms The term_taxonomy_id of terms to update.
3109 * @param string $taxonomy The context of the term.
3110 * @return bool Always true when complete.
3112 function wp_update_term_count_now( $terms, $taxonomy ) {
3115 $terms = array_map('intval', $terms);
3117 $taxonomy = get_taxonomy($taxonomy);
3118 if ( !empty($taxonomy->update_count_callback) ) {
3119 call_user_func($taxonomy->update_count_callback, $terms, $taxonomy);
3121 $object_types = (array) $taxonomy->object_type;
3122 foreach ( $object_types as &$object_type ) {
3123 if ( 0 === strpos( $object_type, 'attachment:' ) )
3124 list( $object_type ) = explode( ':', $object_type );
3127 if ( $object_types == array_filter( $object_types, 'post_type_exists' ) ) {
3128 // Only post types are attached to this taxonomy
3129 _update_post_term_count( $terms, $taxonomy );
3131 // Default count updater
3132 _update_generic_term_count( $terms, $taxonomy );
3136 clean_term_cache($terms, '', false);
3146 * Removes the taxonomy relationship to terms from the cache.
3148 * Will remove the entire taxonomy relationship containing term $object_id. The
3149 * term IDs have to exist within the taxonomy $object_type for the deletion to
3154 * @see get_object_taxonomies() for more on $object_type
3156 * @param int|array $object_ids Single or list of term object ID(s)
3157 * @param array|string $object_type The taxonomy object type
3159 function clean_object_term_cache($object_ids, $object_type) {
3160 if ( !is_array($object_ids) )
3161 $object_ids = array($object_ids);
3163 $taxonomies = get_object_taxonomies( $object_type );
3165 foreach ( $object_ids as $id ) {
3166 foreach ( $taxonomies as $taxonomy ) {
3167 wp_cache_delete($id, "{$taxonomy}_relationships");
3172 * Fires after the object term cache has been cleaned.
3176 * @param array $object_ids An array of object IDs.
3177 * @param string $objet_type Object type.
3179 do_action( 'clean_object_term_cache', $object_ids, $object_type );
3183 * Will remove all of the term ids from the cache.
3188 * @param int|array $ids Single or list of Term IDs
3189 * @param string $taxonomy Can be empty and will assume tt_ids, else will use for context.
3190 * @param bool $clean_taxonomy Whether to clean taxonomy wide caches (true), or just individual term object caches (false). Default is true.
3192 function clean_term_cache($ids, $taxonomy = '', $clean_taxonomy = true) {
3195 if ( !is_array($ids) )
3198 $taxonomies = array();
3199 // If no taxonomy, assume tt_ids.
3200 if ( empty($taxonomy) ) {
3201 $tt_ids = array_map('intval', $ids);
3202 $tt_ids = implode(', ', $tt_ids);
3203 $terms = $wpdb->get_results("SELECT term_id, taxonomy FROM $wpdb->term_taxonomy WHERE term_taxonomy_id IN ($tt_ids)");
3205 foreach ( (array) $terms as $term ) {
3206 $taxonomies[] = $term->taxonomy;
3207 $ids[] = $term->term_id;
3208 wp_cache_delete($term->term_id, $term->taxonomy);
3210 $taxonomies = array_unique($taxonomies);
3212 $taxonomies = array($taxonomy);
3213 foreach ( $taxonomies as $taxonomy ) {
3214 foreach ( $ids as $id ) {
3215 wp_cache_delete($id, $taxonomy);
3220 foreach ( $taxonomies as $taxonomy ) {
3221 if ( $clean_taxonomy ) {
3222 wp_cache_delete('all_ids', $taxonomy);
3223 wp_cache_delete('get', $taxonomy);
3224 delete_option("{$taxonomy}_children");
3225 // Regenerate {$taxonomy}_children
3226 _get_term_hierarchy($taxonomy);
3230 * Fires once after each taxonomy's term cache has been cleaned.
3234 * @param array $ids An array of term IDs.
3235 * @param string $taxonomy Taxonomy slug.
3237 do_action( 'clean_term_cache', $ids, $taxonomy );
3240 wp_cache_set( 'last_changed', microtime(), 'terms' );
3244 * Retrieves the taxonomy relationship to the term object id.
3248 * @uses wp_cache_get() Retrieves taxonomy relationship from cache
3250 * @param int|array $id Term object ID
3251 * @param string $taxonomy Taxonomy Name
3252 * @return bool|array Empty array if $terms found, but not $taxonomy. False if nothing is in cache for $taxonomy and $id.
3254 function get_object_term_cache($id, $taxonomy) {
3255 $cache = wp_cache_get($id, "{$taxonomy}_relationships");
3260 * Updates the cache for Term ID(s).
3262 * Will only update the cache for terms not already cached.
3264 * The $object_ids expects that the ids be separated by commas, if it is a
3267 * It should be noted that update_object_term_cache() is very time extensive. It
3268 * is advised that the function is not called very often or at least not for a
3269 * lot of terms that exist in a lot of taxonomies. The amount of time increases
3270 * for each term and it also increases for each taxonomy the term belongs to.
3273 * @uses wp_get_object_terms() Used to get terms from the database to update
3275 * @param string|array $object_ids Single or list of term object ID(s)
3276 * @param array|string $object_type The taxonomy object type
3277 * @return null|bool Null value is given with empty $object_ids. False if
3279 function update_object_term_cache($object_ids, $object_type) {
3280 if ( empty($object_ids) )
3283 if ( !is_array($object_ids) )
3284 $object_ids = explode(',', $object_ids);
3286 $object_ids = array_map('intval', $object_ids);
3288 $taxonomies = get_object_taxonomies($object_type);
3291 foreach ( (array) $object_ids as $id ) {
3292 foreach ( $taxonomies as $taxonomy ) {
3293 if ( false === wp_cache_get($id, "{$taxonomy}_relationships") ) {
3300 if ( empty( $ids ) )
3303 $terms = wp_get_object_terms($ids, $taxonomies, array('fields' => 'all_with_object_id'));
3305 $object_terms = array();
3306 foreach ( (array) $terms as $term )
3307 $object_terms[$term->object_id][$term->taxonomy][$term->term_id] = $term;
3309 foreach ( $ids as $id ) {
3310 foreach ( $taxonomies as $taxonomy ) {
3311 if ( ! isset($object_terms[$id][$taxonomy]) ) {
3312 if ( !isset($object_terms[$id]) )
3313 $object_terms[$id] = array();
3314 $object_terms[$id][$taxonomy] = array();
3319 foreach ( $object_terms as $id => $value ) {
3320 foreach ( $value as $taxonomy => $terms ) {
3321 wp_cache_add( $id, $terms, "{$taxonomy}_relationships" );
3327 * Updates Terms to Taxonomy in cache.
3331 * @param array $terms List of Term objects to change
3332 * @param string $taxonomy Optional. Update Term to this taxonomy in cache
3334 function update_term_cache($terms, $taxonomy = '') {
3335 foreach ( (array) $terms as $term ) {
3336 $term_taxonomy = $taxonomy;
3337 if ( empty($term_taxonomy) )
3338 $term_taxonomy = $term->taxonomy;
3340 wp_cache_add($term->term_id, $term, $term_taxonomy);
3349 * Retrieves children of taxonomy as Term IDs.
3354 * @uses update_option() Stores all of the children in "$taxonomy_children"
3355 * option. That is the name of the taxonomy, immediately followed by '_children'.
3357 * @param string $taxonomy Taxonomy Name
3358 * @return array Empty if $taxonomy isn't hierarchical or returns children as Term IDs.
3360 function _get_term_hierarchy($taxonomy) {
3361 if ( !is_taxonomy_hierarchical($taxonomy) )
3363 $children = get_option("{$taxonomy}_children");
3365 if ( is_array($children) )
3367 $children = array();
3368 $terms = get_terms($taxonomy, array('get' => 'all', 'orderby' => 'id', 'fields' => 'id=>parent'));
3369 foreach ( $terms as $term_id => $parent ) {
3371 $children[$parent][] = $term_id;
3373 update_option("{$taxonomy}_children", $children);
3379 * Get the subset of $terms that are descendants of $term_id.
3381 * If $terms is an array of objects, then _get_term_children returns an array of objects.
3382 * If $terms is an array of IDs, then _get_term_children returns an array of IDs.
3387 * @param int $term_id The ancestor term: all returned terms should be descendants of $term_id.
3388 * @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.
3389 * @param string $taxonomy The taxonomy which determines the hierarchy of the terms.
3390 * @return array The subset of $terms that are descendants of $term_id.
3392 function _get_term_children($term_id, $terms, $taxonomy) {
3393 $empty_array = array();
3394 if ( empty($terms) )
3395 return $empty_array;
3397 $term_list = array();
3398 $has_children = _get_term_hierarchy($taxonomy);
3400 if ( ( 0 != $term_id ) && ! isset($has_children[$term_id]) )
3401 return $empty_array;
3403 foreach ( (array) $terms as $term ) {
3405 if ( !is_object($term) ) {
3406 $term = get_term($term, $taxonomy);
3407 if ( is_wp_error( $term ) )
3412 if ( $term->term_id == $term_id ) {
3416 if ( $term->parent == $term_id ) {
3418 $term_list[] = $term->term_id;
3420 $term_list[] = $term;
3422 if ( !isset($has_children[$term->term_id]) )
3425 if ( $children = _get_term_children($term->term_id, $terms, $taxonomy) )
3426 $term_list = array_merge($term_list, $children);
3434 * Add count of children to parent count.
3436 * Recalculates term counts by including items from child terms. Assumes all
3437 * relevant children are already in the $terms argument.
3443 * @param array $terms List of Term IDs
3444 * @param string $taxonomy Term Context
3445 * @return null Will break from function if conditions are not met.
3447 function _pad_term_counts(&$terms, $taxonomy) {
3450 // This function only works for hierarchical taxonomies like post categories.
3451 if ( !is_taxonomy_hierarchical( $taxonomy ) )
3454 $term_hier = _get_term_hierarchy($taxonomy);
3456 if ( empty($term_hier) )
3459 $term_items = array();
3461 foreach ( (array) $terms as $key => $term ) {
3462 $terms_by_id[$term->term_id] = & $terms[$key];
3463 $term_ids[$term->term_taxonomy_id] = $term->term_id;
3466 // Get the object and term ids and stick them in a lookup table
3467 $tax_obj = get_taxonomy($taxonomy);
3468 $object_types = esc_sql($tax_obj->object_type);
3469 $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'");
3470 foreach ( $results as $row ) {
3471 $id = $term_ids[$row->term_taxonomy_id];
3472 $term_items[$id][$row->object_id] = isset($term_items[$id][$row->object_id]) ? ++$term_items[$id][$row->object_id] : 1;
3475 // Touch every ancestor's lookup row for each post in each term
3476 foreach ( $term_ids as $term_id ) {
3478 while ( !empty( $terms_by_id[$child] ) && $parent = $terms_by_id[$child]->parent ) {
3479 if ( !empty( $term_items[$term_id] ) )
3480 foreach ( $term_items[$term_id] as $item_id => $touches ) {
3481 $term_items[$parent][$item_id] = isset($term_items[$parent][$item_id]) ? ++$term_items[$parent][$item_id]: 1;
3487 // Transfer the touched cells
3488 foreach ( (array) $term_items as $id => $items )
3489 if ( isset($terms_by_id[$id]) )
3490 $terms_by_id[$id]->count = count($items);
3494 // Default callbacks
3498 * Will update term count based on object types of the current taxonomy.
3500 * Private function for the default callback for post_tag and category
3507 * @param array $terms List of Term taxonomy IDs
3508 * @param object $taxonomy Current taxonomy object of terms
3510 function _update_post_term_count( $terms, $taxonomy ) {
3513 $object_types = (array) $taxonomy->object_type;
3515 foreach ( $object_types as &$object_type )
3516 list( $object_type ) = explode( ':', $object_type );
3518 $object_types = array_unique( $object_types );
3520 if ( false !== ( $check_attachments = array_search( 'attachment', $object_types ) ) ) {
3521 unset( $object_types[ $check_attachments ] );
3522 $check_attachments = true;
3525 if ( $object_types )
3526 $object_types = esc_sql( array_filter( $object_types, 'post_type_exists' ) );
3528 foreach ( (array) $terms as $term ) {
3531 // Attachments can be 'inherit' status, we need to base count off the parent's status if so
3532 if ( $check_attachments )
3533 $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 ) );
3535 if ( $object_types )
3536 $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 ) );
3538 /** This action is documented in wp-includes/taxonomy.php */
3539 do_action( 'edit_term_taxonomy', $term, $taxonomy );
3540 $wpdb->update( $wpdb->term_taxonomy, compact( 'count' ), array( 'term_taxonomy_id' => $term ) );
3542 /** This action is documented in wp-includes/taxonomy.php */
3543 do_action( 'edited_term_taxonomy', $term, $taxonomy );
3548 * Will update term count based on number of objects.
3550 * Default callback for the link_category taxonomy.
3555 * @param array $terms List of Term taxonomy IDs
3556 * @param object $taxonomy Current taxonomy object of terms
3558 function _update_generic_term_count( $terms, $taxonomy ) {
3561 foreach ( (array) $terms as $term ) {
3562 $count = $wpdb->get_var( $wpdb->prepare( "SELECT COUNT(*) FROM $wpdb->term_relationships WHERE term_taxonomy_id = %d", $term ) );
3564 /** This action is documented in wp-includes/taxonomy.php */
3565 do_action( 'edit_term_taxonomy', $term, $taxonomy );
3566 $wpdb->update( $wpdb->term_taxonomy, compact( 'count' ), array( 'term_taxonomy_id' => $term ) );
3568 /** This action is documented in wp-includes/taxonomy.php */
3569 do_action( 'edited_term_taxonomy', $term, $taxonomy );
3574 * Generates a permalink for a taxonomy term archive.
3578 * @param object|int|string $term
3579 * @param string $taxonomy (optional if $term is object)
3580 * @return string|WP_Error HTML link to taxonomy term archive on success, WP_Error if term does not exist.
3582 function get_term_link( $term, $taxonomy = '') {
3585 if ( !is_object($term) ) {
3586 if ( is_int($term) ) {
3587 $term = get_term($term, $taxonomy);
3589 $term = get_term_by('slug', $term, $taxonomy);
3593 if ( !is_object($term) )
3594 $term = new WP_Error('invalid_term', __('Empty Term'));
3596 if ( is_wp_error( $term ) )
3599 $taxonomy = $term->taxonomy;
3601 $termlink = $wp_rewrite->get_extra_permastruct($taxonomy);
3603 $slug = $term->slug;
3604 $t = get_taxonomy($taxonomy);
3606 if ( empty($termlink) ) {
3607 if ( 'category' == $taxonomy )
3608 $termlink = '?cat=' . $term->term_id;
3609 elseif ( $t->query_var )
3610 $termlink = "?$t->query_var=$slug";
3612 $termlink = "?taxonomy=$taxonomy&term=$slug";
3613 $termlink = home_url($termlink);
3615 if ( $t->rewrite['hierarchical'] ) {
3616 $hierarchical_slugs = array();
3617 $ancestors = get_ancestors($term->term_id, $taxonomy);
3618 foreach ( (array)$ancestors as $ancestor ) {
3619 $ancestor_term = get_term($ancestor, $taxonomy);
3620 $hierarchical_slugs[] = $ancestor_term->slug;
3622 $hierarchical_slugs = array_reverse($hierarchical_slugs);
3623 $hierarchical_slugs[] = $slug;
3624 $termlink = str_replace("%$taxonomy%", implode('/', $hierarchical_slugs), $termlink);
3626 $termlink = str_replace("%$taxonomy%", $slug, $termlink);
3628 $termlink = home_url( user_trailingslashit($termlink, 'category') );
3630 // Back Compat filters.
3631 if ( 'post_tag' == $taxonomy ) {
3634 * Filter the tag link.
3637 * @deprecated 2.5.0 Use 'term_link' instead.
3639 * @param string $termlink Tag link URL.
3640 * @param int $term_id Term ID.
3642 $termlink = apply_filters( 'tag_link', $termlink, $term->term_id );
3643 } elseif ( 'category' == $taxonomy ) {
3646 * Filter the category link.
3649 * @deprecated 2.5.0 Use 'term_link' instead.
3651 * @param string $termlink Category link URL.
3652 * @param int $term_id Term ID.
3654 $termlink = apply_filters( 'category_link', $termlink, $term->term_id );
3658 * Filter the term link.
3662 * @param string $termlink Term link URL.
3663 * @param object $term Term object.
3664 * @param string $taxonomy Taxonomy slug.
3666 return apply_filters( 'term_link', $termlink, $term, $taxonomy );
3670 * Display the taxonomies of a post with available options.
3672 * This function can be used within the loop to display the taxonomies for a
3673 * post without specifying the Post ID. You can also use it outside the Loop to
3674 * display the taxonomies for a specific post.
3676 * The available defaults are:
3677 * 'post' : default is 0. The post ID to get taxonomies of.
3678 * 'before' : default is empty string. Display before taxonomies list.
3679 * 'sep' : default is empty string. Separate every taxonomy with value in this.
3680 * 'after' : default is empty string. Display this after the taxonomies list.
3681 * 'template' : The template to use for displaying the taxonomy terms.
3684 * @uses get_the_taxonomies()
3686 * @param array $args Override the defaults.
3688 function the_taxonomies($args = array()) {
3694 'template' => '%s: %l.'
3697 $r = wp_parse_args( $args, $defaults );
3698 extract( $r, EXTR_SKIP );
3700 echo $before . join($sep, get_the_taxonomies($post, $r)) . $after;
3704 * Retrieve all taxonomies associated with a post.
3706 * This function can be used within the loop. It will also return an array of
3707 * the taxonomies with links to the taxonomy and name.
3711 * @param int|WP_Post $post Optional. Post ID or post object.
3712 * @param array $args Override the defaults.
3715 function get_the_taxonomies($post = 0, $args = array() ) {
3716 $post = get_post( $post );
3718 $args = wp_parse_args( $args, array(
3719 'template' => '%s: %l.',
3721 extract( $args, EXTR_SKIP );
3723 $taxonomies = array();
3728 foreach ( get_object_taxonomies($post) as $taxonomy ) {
3729 $t = (array) get_taxonomy($taxonomy);
3730 if ( empty($t['label']) )
3731 $t['label'] = $taxonomy;
3732 if ( empty($t['args']) )
3733 $t['args'] = array();
3734 if ( empty($t['template']) )
3735 $t['template'] = $template;
3737 $terms = get_object_term_cache($post->ID, $taxonomy);
3738 if ( false === $terms )
3739 $terms = wp_get_object_terms($post->ID, $taxonomy, $t['args']);
3743 foreach ( $terms as $term )
3744 $links[] = "<a href='" . esc_attr( get_term_link($term) ) . "'>$term->name</a>";
3747 $taxonomies[$taxonomy] = wp_sprintf($t['template'], $t['label'], $links, $terms);
3753 * Retrieve all taxonomies of a post with just the names.
3756 * @uses get_object_taxonomies()
3758 * @param int|WP_Post $post Optional. Post ID or post object.
3761 function get_post_taxonomies($post = 0) {
3762 $post = get_post( $post );
3764 return get_object_taxonomies($post);
3768 * Determine if the given object is associated with any of the given terms.
3770 * The given terms are checked against the object's terms' term_ids, names and slugs.
3771 * Terms given as integers will only be checked against the object's terms' term_ids.
3772 * If no terms are given, determines if object is associated with any terms in the given taxonomy.
3775 * @uses get_object_term_cache()
3776 * @uses wp_get_object_terms()
3778 * @param int $object_id ID of the object (post ID, link ID, ...)
3779 * @param string $taxonomy Single taxonomy name
3780 * @param int|string|array $terms Optional. Term term_id, name, slug or array of said
3781 * @return bool|WP_Error. WP_Error on input error.
3783 function is_object_in_term( $object_id, $taxonomy, $terms = null ) {
3784 if ( !$object_id = (int) $object_id )
3785 return new WP_Error( 'invalid_object', __( 'Invalid object ID' ) );
3787 $object_terms = get_object_term_cache( $object_id, $taxonomy );
3788 if ( false === $object_terms )
3789 $object_terms = wp_get_object_terms( $object_id, $taxonomy );
3791 if ( is_wp_error( $object_terms ) )
3792 return $object_terms;
3793 if ( empty( $object_terms ) )
3795 if ( empty( $terms ) )
3796 return ( !empty( $object_terms ) );
3798 $terms = (array) $terms;
3800 if ( $ints = array_filter( $terms, 'is_int' ) )
3801 $strs = array_diff( $terms, $ints );
3805 foreach ( $object_terms as $object_term ) {
3806 if ( $ints && in_array( $object_term->term_id, $ints ) ) return true; // If int, check against term_id
3808 if ( in_array( $object_term->term_id, $strs ) ) return true;
3809 if ( in_array( $object_term->name, $strs ) ) return true;
3810 if ( in_array( $object_term->slug, $strs ) ) return true;
3818 * Determine if the given object type is associated with the given taxonomy.
3821 * @uses get_object_taxonomies()
3823 * @param string $object_type Object type string
3824 * @param string $taxonomy Single taxonomy name
3825 * @return bool True if object is associated with the taxonomy, otherwise false.
3827 function is_object_in_taxonomy($object_type, $taxonomy) {
3828 $taxonomies = get_object_taxonomies($object_type);
3830 if ( empty($taxonomies) )
3833 if ( in_array($taxonomy, $taxonomies) )
3840 * Get an array of ancestor IDs for a given object.
3842 * @param int $object_id The ID of the object
3843 * @param string $object_type The type of object for which we'll be retrieving ancestors.
3844 * @return array of ancestors from lowest to highest in the hierarchy.
3846 function get_ancestors($object_id = 0, $object_type = '') {
3847 $object_id = (int) $object_id;
3849 $ancestors = array();
3851 if ( empty( $object_id ) ) {
3853 /** This filter is documented in wp-includes/taxonomy.php */
3854 return apply_filters( 'get_ancestors', $ancestors, $object_id, $object_type );
3857 if ( is_taxonomy_hierarchical( $object_type ) ) {
3858 $term = get_term($object_id, $object_type);
3859 while ( ! is_wp_error($term) && ! empty( $term->parent ) && ! in_array( $term->parent, $ancestors ) ) {
3860 $ancestors[] = (int) $term->parent;
3861 $term = get_term($term->parent, $object_type);
3863 } elseif ( post_type_exists( $object_type ) ) {
3864 $ancestors = get_post_ancestors($object_id);
3868 * Filter a given object's ancestors.
3872 * @param array $ancestors An array of object ancestors.
3873 * @param int $object_id Object ID.
3874 * @param string $object_type Type of object.
3876 return apply_filters( 'get_ancestors', $ancestors, $object_id, $object_type );
3880 * Returns the term's parent's term_ID
3884 * @param int $term_id
3885 * @param string $taxonomy
3887 * @return int|bool false on error
3889 function wp_get_term_taxonomy_parent_id( $term_id, $taxonomy ) {
3890 $term = get_term( $term_id, $taxonomy );
3891 if ( !$term || is_wp_error( $term ) )
3893 return (int) $term->parent;
3897 * Checks the given subset of the term hierarchy for hierarchy loops.
3898 * Prevents loops from forming and breaks those that it finds.
3900 * Attached to the wp_update_term_parent filter.
3903 * @uses wp_find_hierarchy_loop()
3905 * @param int $parent term_id of the parent for the term we're checking.
3906 * @param int $term_id The term we're checking.
3907 * @param string $taxonomy The taxonomy of the term we're checking.
3909 * @return int The new parent for the term.
3911 function wp_check_term_hierarchy_for_loops( $parent, $term_id, $taxonomy ) {
3912 // Nothing fancy here - bail
3916 // Can't be its own parent
3917 if ( $parent == $term_id )
3920 // Now look for larger loops
3922 if ( !$loop = wp_find_hierarchy_loop( 'wp_get_term_taxonomy_parent_id', $term_id, $parent, array( $taxonomy ) ) )
3923 return $parent; // No loop
3925 // Setting $parent to the given value causes a loop
3926 if ( isset( $loop[$term_id] ) )
3929 // There's a loop, but it doesn't contain $term_id. Break the loop.
3930 foreach ( array_keys( $loop ) as $loop_member )
3931 wp_update_term( $loop_member, $taxonomy, array( 'parent' => 0 ) );