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 'hierarchical' => false,
45 'slug' => get_option('tag_base') ? get_option('tag_base') : 'tag',
46 'with_front' => ! get_option('tag_base') || $wp_rewrite->using_index_permalinks(),
49 'post_format' => $post_format_base ? array( 'slug' => $post_format_base ) : false,
53 register_taxonomy( 'category', 'post', array(
54 'hierarchical' => true,
55 'query_var' => 'category_name',
56 'rewrite' => $rewrite['category'],
59 'show_admin_column' => true,
63 register_taxonomy( 'post_tag', 'post', array(
64 'hierarchical' => false,
66 'rewrite' => $rewrite['post_tag'],
69 'show_admin_column' => true,
73 register_taxonomy( 'nav_menu', 'nav_menu_item', array(
75 'hierarchical' => false,
77 'name' => __( 'Navigation Menus' ),
78 'singular_name' => __( 'Navigation Menu' ),
84 'show_in_nav_menus' => false,
87 register_taxonomy( 'link_category', 'link', array(
88 'hierarchical' => false,
90 'name' => __( 'Link Categories' ),
91 'singular_name' => __( 'Link Category' ),
92 'search_items' => __( 'Search Link Categories' ),
93 'popular_items' => null,
94 'all_items' => __( 'All Link Categories' ),
95 'edit_item' => __( 'Edit Link Category' ),
96 'update_item' => __( 'Update Link Category' ),
97 'add_new_item' => __( 'Add New Link Category' ),
98 'new_item_name' => __( 'New Link Category Name' ),
99 'separate_items_with_commas' => null,
100 'add_or_remove_items' => null,
101 'choose_from_most_used' => null,
103 'capabilities' => array(
104 'manage_terms' => 'manage_links',
105 'edit_terms' => 'manage_links',
106 'delete_terms' => 'manage_links',
107 'assign_terms' => 'manage_links',
109 'query_var' => false,
116 register_taxonomy( 'post_format', 'post', array(
118 'hierarchical' => false,
120 'name' => _x( 'Format', 'post format' ),
121 'singular_name' => _x( 'Format', 'post format' ),
124 'rewrite' => $rewrite['post_format'],
127 'show_in_nav_menus' => current_theme_supports( 'post-formats' ),
130 add_action( 'init', 'create_initial_taxonomies', 0 ); // highest priority
133 * Get a list of registered taxonomy objects.
136 * @uses $wp_taxonomies
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 * `<?php $taxonomies = get_object_taxonomies('post'); ?>` Should
159 * result in `Array( 'category', 'post_tag' )`
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
203 * @param string $taxonomy Name of taxonomy object to return
204 * @return object|bool The Taxonomy Object or false if $taxonomy doesn't exist
206 function get_taxonomy( $taxonomy ) {
207 global $wp_taxonomies;
209 if ( ! taxonomy_exists( $taxonomy ) )
212 return $wp_taxonomies[$taxonomy];
216 * Checks that the taxonomy name exists.
218 * Formerly is_taxonomy(), introduced in 2.3.0.
222 * @uses $wp_taxonomies
224 * @param string $taxonomy Name of taxonomy object
225 * @return bool Whether the taxonomy exists.
227 function taxonomy_exists( $taxonomy ) {
228 global $wp_taxonomies;
230 return isset( $wp_taxonomies[$taxonomy] );
234 * Whether the taxonomy object is hierarchical.
236 * Checks to make sure that the taxonomy is an object first. Then Gets the
237 * object, and finally returns the hierarchical value in the object.
239 * A false return value might also mean that the taxonomy does not exist.
243 * @param string $taxonomy Name of taxonomy object
244 * @return bool Whether the taxonomy is hierarchical
246 function is_taxonomy_hierarchical($taxonomy) {
247 if ( ! taxonomy_exists($taxonomy) )
250 $taxonomy = get_taxonomy($taxonomy);
251 return $taxonomy->hierarchical;
255 * Create or modify a taxonomy object. Do not use before init.
257 * A simple function for creating or modifying a taxonomy object based on the
258 * parameters given. The function will accept an array (third optional
259 * parameter), along with strings for the taxonomy name and another string for
262 * Nothing is returned, so expect error maybe or use taxonomy_exists() to check
263 * whether taxonomy exists.
265 * Optional $args contents:
267 * - label - Name of the taxonomy shown in the menu. Usually plural. If not set, labels['name'] will be used.
268 * - labels - An array of labels for this taxonomy.
269 * * By default tag labels are used for non-hierarchical types and category labels for hierarchical ones.
270 * * You can see accepted values in {@link get_taxonomy_labels()}.
271 * - description - A short descriptive summary of what the taxonomy is for. Defaults to blank.
272 * - public - If the taxonomy should be publicly queryable; //@TODO not implemented.
273 * * Defaults to true.
274 * - hierarchical - Whether the taxonomy is hierarchical (e.g. category). Defaults to false.
275 * - show_ui - Whether to generate a default UI for managing this taxonomy in the admin.
276 * * If not set, the default is inherited from public.
277 * - show_in_menu - Whether to show the taxonomy in the admin menu.
278 * * If true, the taxonomy is shown as a submenu of the object type menu.
279 * * If false, no menu is shown.
280 * * show_ui must be true.
281 * * If not set, the default is inherited from show_ui.
282 * - show_in_nav_menus - Makes this taxonomy available for selection in navigation menus.
283 * * If not set, the default is inherited from public.
284 * - show_tagcloud - Whether to list the taxonomy in the Tag Cloud Widget.
285 * * If not set, the default is inherited from show_ui.
286 * - show_admin_column - Whether to display a column for the taxonomy on its post type listing screens.
287 * * Defaults to false.
288 * - meta_box_cb - Provide a callback function for the meta box display.
289 * * If not set, defaults to post_categories_meta_box for hierarchical taxonomies
290 * and post_tags_meta_box for non-hierarchical.
291 * * If false, no meta box is shown.
292 * - capabilities - Array of capabilities for this taxonomy.
293 * * You can see accepted values in this function.
294 * - rewrite - Triggers the handling of rewrites for this taxonomy. Defaults to true, using $taxonomy as slug.
295 * * To prevent rewrite, set to false.
296 * * To specify rewrite rules, an array can be passed with any of these keys
297 * * 'slug' => string Customize the permastruct slug. Defaults to $taxonomy key
298 * * 'with_front' => bool Should the permastruct be prepended with WP_Rewrite::$front. Defaults to true.
299 * * 'hierarchical' => bool Either hierarchical rewrite tag or not. Defaults to false.
300 * * 'ep_mask' => const Assign an endpoint mask.
301 * * If not specified, defaults to EP_NONE.
302 * - query_var - Sets the query_var key for this taxonomy. Defaults to $taxonomy key
303 * * If false, a taxonomy cannot be loaded at ?{query_var}={term_slug}
304 * * If specified as a string, the query ?{query_var_string}={term_slug} will be valid.
305 * - update_count_callback - Works much like a hook, in that it will be called when the count is updated.
306 * * Defaults to _update_post_term_count() for taxonomies attached to post types, which then confirms
307 * that the objects are published before counting them.
308 * * Defaults to _update_generic_term_count() for taxonomies attached to other object types, such as links.
309 * - _builtin - true if this taxonomy is a native or "built-in" taxonomy. THIS IS FOR INTERNAL USE ONLY!
312 * @uses $wp_taxonomies Inserts new taxonomy object into the list
313 * @uses $wp Adds query vars
315 * @param string $taxonomy Taxonomy key, must not exceed 32 characters.
316 * @param array|string $object_type Name of the object type for the taxonomy object.
317 * @param array|string $args See optional args description above.
318 * @return null|WP_Error WP_Error if errors, otherwise null.
320 function register_taxonomy( $taxonomy, $object_type, $args = array() ) {
321 global $wp_taxonomies, $wp;
323 if ( ! is_array( $wp_taxonomies ) )
324 $wp_taxonomies = array();
330 'hierarchical' => false,
332 'show_in_menu' => null,
333 'show_in_nav_menus' => null,
334 'show_tagcloud' => null,
335 'show_admin_column' => false,
336 'meta_box_cb' => null,
337 'capabilities' => array(),
339 'query_var' => $taxonomy,
340 'update_count_callback' => '',
343 $args = wp_parse_args( $args, $defaults );
345 if ( strlen( $taxonomy ) > 32 ) {
346 _doing_it_wrong( __FUNCTION__, __( 'Taxonomies cannot exceed 32 characters in length' ), '4.0' );
347 return new WP_Error( 'taxonomy_too_long', __( 'Taxonomies cannot exceed 32 characters in length' ) );
350 if ( false !== $args['query_var'] && ! empty( $wp ) ) {
351 if ( true === $args['query_var'] )
352 $args['query_var'] = $taxonomy;
354 $args['query_var'] = sanitize_title_with_dashes( $args['query_var'] );
355 $wp->add_query_var( $args['query_var'] );
358 if ( false !== $args['rewrite'] && ( is_admin() || '' != get_option( 'permalink_structure' ) ) ) {
359 $args['rewrite'] = wp_parse_args( $args['rewrite'], array(
360 'with_front' => true,
361 'hierarchical' => false,
362 'ep_mask' => EP_NONE,
365 if ( empty( $args['rewrite']['slug'] ) )
366 $args['rewrite']['slug'] = sanitize_title_with_dashes( $taxonomy );
368 if ( $args['hierarchical'] && $args['rewrite']['hierarchical'] )
373 add_rewrite_tag( "%$taxonomy%", $tag, $args['query_var'] ? "{$args['query_var']}=" : "taxonomy=$taxonomy&term=" );
374 add_permastruct( $taxonomy, "{$args['rewrite']['slug']}/%$taxonomy%", $args['rewrite'] );
377 // If not set, default to the setting for public.
378 if ( null === $args['show_ui'] )
379 $args['show_ui'] = $args['public'];
381 // If not set, default to the setting for show_ui.
382 if ( null === $args['show_in_menu' ] || ! $args['show_ui'] )
383 $args['show_in_menu' ] = $args['show_ui'];
385 // If not set, default to the setting for public.
386 if ( null === $args['show_in_nav_menus'] )
387 $args['show_in_nav_menus'] = $args['public'];
389 // If not set, default to the setting for show_ui.
390 if ( null === $args['show_tagcloud'] )
391 $args['show_tagcloud'] = $args['show_ui'];
393 $default_caps = array(
394 'manage_terms' => 'manage_categories',
395 'edit_terms' => 'manage_categories',
396 'delete_terms' => 'manage_categories',
397 'assign_terms' => 'edit_posts',
399 $args['cap'] = (object) array_merge( $default_caps, $args['capabilities'] );
400 unset( $args['capabilities'] );
402 $args['name'] = $taxonomy;
403 $args['object_type'] = array_unique( (array) $object_type );
405 $args['labels'] = get_taxonomy_labels( (object) $args );
406 $args['label'] = $args['labels']->name;
408 // If not set, use the default meta box
409 if ( null === $args['meta_box_cb'] ) {
410 if ( $args['hierarchical'] )
411 $args['meta_box_cb'] = 'post_categories_meta_box';
413 $args['meta_box_cb'] = 'post_tags_meta_box';
416 $wp_taxonomies[ $taxonomy ] = (object) $args;
418 // register callback handling for metabox
419 add_filter( 'wp_ajax_add-' . $taxonomy, '_wp_ajax_add_hierarchical_term' );
422 * Fires after a taxonomy is registered.
426 * @param string $taxonomy Taxonomy slug.
427 * @param array|string $object_type Object type or array of object types.
428 * @param array $args Array of taxonomy registration arguments.
430 do_action( 'registered_taxonomy', $taxonomy, $object_type, $args );
434 * Builds an object with all taxonomy labels out of a taxonomy object
436 * Accepted keys of the label array in the taxonomy object:
438 * - name - general name for the taxonomy, usually plural. The same as and overridden by $tax->label. Default is Tags/Categories
439 * - singular_name - name for one object of this taxonomy. Default is Tag/Category
440 * - search_items - Default is Search Tags/Search Categories
441 * - popular_items - This string isn't used on hierarchical taxonomies. Default is Popular Tags
442 * - all_items - Default is All Tags/All Categories
443 * - parent_item - This string isn't used on non-hierarchical taxonomies. In hierarchical ones the default is Parent Category
444 * - parent_item_colon - The same as `parent_item`, but with colon `:` in the end
445 * - edit_item - Default is Edit Tag/Edit Category
446 * - view_item - Default is View Tag/View Category
447 * - update_item - Default is Update Tag/Update Category
448 * - add_new_item - Default is Add New Tag/Add New Category
449 * - new_item_name - Default is New Tag Name/New Category Name
450 * - separate_items_with_commas - This string isn't used on hierarchical taxonomies. Default is "Separate tags with commas", used in the meta box.
451 * - 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.
452 * - 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.
453 * - not_found - This string isn't used on hierarchical taxonomies. Default is "No tags found", used in the meta box.
455 * Above, the first default value is for non-hierarchical taxonomies (like tags) and the second one is for hierarchical taxonomies (like categories).
458 * @param object $tax Taxonomy object
459 * @return object object with all the labels as member variables
462 function get_taxonomy_labels( $tax ) {
463 $tax->labels = (array) $tax->labels;
465 if ( isset( $tax->helps ) && empty( $tax->labels['separate_items_with_commas'] ) )
466 $tax->labels['separate_items_with_commas'] = $tax->helps;
468 if ( isset( $tax->no_tagcloud ) && empty( $tax->labels['not_found'] ) )
469 $tax->labels['not_found'] = $tax->no_tagcloud;
471 $nohier_vs_hier_defaults = array(
472 'name' => array( _x( 'Tags', 'taxonomy general name' ), _x( 'Categories', 'taxonomy general name' ) ),
473 'singular_name' => array( _x( 'Tag', 'taxonomy singular name' ), _x( 'Category', 'taxonomy singular name' ) ),
474 'search_items' => array( __( 'Search Tags' ), __( 'Search Categories' ) ),
475 'popular_items' => array( __( 'Popular Tags' ), null ),
476 'all_items' => array( __( 'All Tags' ), __( 'All Categories' ) ),
477 'parent_item' => array( null, __( 'Parent Category' ) ),
478 'parent_item_colon' => array( null, __( 'Parent Category:' ) ),
479 'edit_item' => array( __( 'Edit Tag' ), __( 'Edit Category' ) ),
480 'view_item' => array( __( 'View Tag' ), __( 'View Category' ) ),
481 'update_item' => array( __( 'Update Tag' ), __( 'Update Category' ) ),
482 'add_new_item' => array( __( 'Add New Tag' ), __( 'Add New Category' ) ),
483 'new_item_name' => array( __( 'New Tag Name' ), __( 'New Category Name' ) ),
484 'separate_items_with_commas' => array( __( 'Separate tags with commas' ), null ),
485 'add_or_remove_items' => array( __( 'Add or remove tags' ), null ),
486 'choose_from_most_used' => array( __( 'Choose from the most used tags' ), null ),
487 'not_found' => array( __( 'No tags found.' ), null ),
489 $nohier_vs_hier_defaults['menu_name'] = $nohier_vs_hier_defaults['name'];
491 return _get_custom_object_labels( $tax, $nohier_vs_hier_defaults );
495 * Add an already registered taxonomy to an object type.
498 * @uses $wp_taxonomies Modifies taxonomy object
500 * @param string $taxonomy Name of taxonomy object
501 * @param string $object_type Name of the object type
502 * @return bool True if successful, false if not
504 function register_taxonomy_for_object_type( $taxonomy, $object_type) {
505 global $wp_taxonomies;
507 if ( !isset($wp_taxonomies[$taxonomy]) )
510 if ( ! get_post_type_object($object_type) )
513 if ( ! in_array( $object_type, $wp_taxonomies[$taxonomy]->object_type ) )
514 $wp_taxonomies[$taxonomy]->object_type[] = $object_type;
520 * Remove an already registered taxonomy from an object type.
524 * @param string $taxonomy Name of taxonomy object.
525 * @param string $object_type Name of the object type.
526 * @return bool True if successful, false if not.
528 function unregister_taxonomy_for_object_type( $taxonomy, $object_type ) {
529 global $wp_taxonomies;
531 if ( ! isset( $wp_taxonomies[ $taxonomy ] ) )
534 if ( ! get_post_type_object( $object_type ) )
537 $key = array_search( $object_type, $wp_taxonomies[ $taxonomy ]->object_type, true );
538 if ( false === $key )
541 unset( $wp_taxonomies[ $taxonomy ]->object_type[ $key ] );
550 * Retrieve object_ids of valid taxonomy and term.
552 * The strings of $taxonomies must exist before this function will continue. On
553 * failure of finding a valid taxonomy, it will return an WP_Error class, kind
554 * of like Exceptions in PHP 5, except you can't catch them. Even so, you can
555 * still test for the WP_Error class and get the error message.
557 * The $terms aren't checked the same as $taxonomies, but still need to exist
558 * for $object_ids to be returned.
560 * It is possible to change the order that object_ids is returned by either
561 * using PHP sort family functions or using the database by using $args with
562 * either ASC or DESC array. The value should be in the key named 'order'.
566 * @global wpdb $wpdb WordPress database abstraction object.
568 * @param int|array $term_ids Term id or array of term ids of terms that will be used
569 * @param string|array $taxonomies String of taxonomy name or Array of string values of taxonomy names
570 * @param array|string $args Change the order of the object_ids, either ASC or DESC
571 * @return WP_Error|array If the taxonomy does not exist, then WP_Error will be returned. On success
572 * the array can be empty meaning that there are no $object_ids found or it will return the $object_ids found.
574 function get_objects_in_term( $term_ids, $taxonomies, $args = array() ) {
577 if ( ! is_array( $term_ids ) ) {
578 $term_ids = array( $term_ids );
580 if ( ! is_array( $taxonomies ) ) {
581 $taxonomies = array( $taxonomies );
583 foreach ( (array) $taxonomies as $taxonomy ) {
584 if ( ! taxonomy_exists( $taxonomy ) ) {
585 return new WP_Error( 'invalid_taxonomy', __( 'Invalid taxonomy' ) );
589 $defaults = array( 'order' => 'ASC' );
590 $args = wp_parse_args( $args, $defaults );
592 $order = ( 'desc' == strtolower( $args['order'] ) ) ? 'DESC' : 'ASC';
594 $term_ids = array_map('intval', $term_ids );
596 $taxonomies = "'" . implode( "', '", $taxonomies ) . "'";
597 $term_ids = "'" . implode( "', '", $term_ids ) . "'";
599 $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");
601 if ( ! $object_ids ){
608 * Given a taxonomy query, generates SQL to be appended to a main query.
614 * @param array $tax_query A compact tax query
615 * @param string $primary_table
616 * @param string $primary_id_column
619 function get_tax_sql( $tax_query, $primary_table, $primary_id_column ) {
620 $tax_query_obj = new WP_Tax_Query( $tax_query );
621 return $tax_query_obj->get_sql( $primary_table, $primary_id_column );
625 * Class for generating SQL clauses that filter a primary query according to object taxonomy terms.
627 * `WP_Tax_Query` is a helper that allows primary query classes, such as {@see WP_Query}, to filter
628 * their results by object metadata, by generating `JOIN` and `WHERE` subclauses to be attached
629 * to the primary SQL query string.
636 * Array of taxonomy queries.
638 * See {@see WP_Tax_Query::__construct()} for information on tax query arguments.
644 public $queries = array();
647 * The relation between the queries. Can be one of 'AND' or 'OR'.
656 * Standard response when the query should not return any rows.
662 private static $no_results = array( 'join' => array( '' ), 'where' => array( '0 = 1' ) );
665 * A flat list of table aliases used in the JOIN clauses.
671 protected $table_aliases = array();
674 * Terms and taxonomies fetched by this query.
676 * We store this data in a flat array because they are referenced in a
677 * number of places by {@see WP_Query}.
683 public $queried_terms = array();
686 * Database table that where the metadata's objects are stored (eg $wpdb->users).
692 public $primary_table;
695 * Column in 'primary_table' that represents the ID of the object.
701 public $primary_id_column;
707 * @since 4.1.0 Added support for `$operator` 'NOT EXISTS' and 'EXISTS' values.
710 * @param array $tax_query {
711 * Array of taxonomy query clauses.
713 * @type string $relation Optional. The MySQL keyword used to join
714 * the clauses of the query. Accepts 'AND', or 'OR'. Default 'AND'.
716 * Optional. An array of first-order clause parameters, or another fully-formed tax query.
718 * @type string $taxonomy Taxonomy being queried. Optional when field=term_taxonomy_id.
719 * @type string|int|array $terms Term or terms to filter by.
720 * @type string $field Field to match $terms against. Accepts 'term_id', 'slug',
721 * 'name', or 'term_taxonomy_id'. Default: 'term_id'.
722 * @type string $operator MySQL operator to be used with $terms in the WHERE clause.
723 * Accepts 'AND', 'IN', 'NOT IN', 'EXISTS', 'NOT EXISTS'.
725 * @type bool $include_children Optional. Whether to include child terms.
726 * Requires a $taxonomy. Default: true.
730 public function __construct( $tax_query ) {
731 if ( isset( $tax_query['relation'] ) ) {
732 $this->relation = $this->sanitize_relation( $tax_query['relation'] );
734 $this->relation = 'AND';
737 $this->queries = $this->sanitize_query( $tax_query );
741 * Ensure the 'tax_query' argument passed to the class constructor is well-formed.
743 * Ensures that each query-level clause has a 'relation' key, and that
744 * each first-order clause contains all the necessary keys from `$defaults`.
749 * @param array $queries Array of queries clauses.
750 * @return array Sanitized array of query clauses.
752 public function sanitize_query( $queries ) {
753 $cleaned_query = array();
758 'field' => 'term_id',
760 'include_children' => true,
763 foreach ( $queries as $key => $query ) {
764 if ( 'relation' === $key ) {
765 $cleaned_query['relation'] = $this->sanitize_relation( $query );
767 // First-order clause.
768 } else if ( self::is_first_order_clause( $query ) ) {
770 $cleaned_clause = array_merge( $defaults, $query );
771 $cleaned_clause['terms'] = (array) $cleaned_clause['terms'];
772 $cleaned_query[] = $cleaned_clause;
775 * Keep a copy of the clause in the flate
776 * $queried_terms array, for use in WP_Query.
778 if ( ! empty( $cleaned_clause['taxonomy'] ) && 'NOT IN' !== $cleaned_clause['operator'] ) {
779 $taxonomy = $cleaned_clause['taxonomy'];
780 if ( ! isset( $this->queried_terms[ $taxonomy ] ) ) {
781 $this->queried_terms[ $taxonomy ] = array();
785 * Backward compatibility: Only store the first
786 * 'terms' and 'field' found for a given taxonomy.
788 if ( ! empty( $cleaned_clause['terms'] ) && ! isset( $this->queried_terms[ $taxonomy ]['terms'] ) ) {
789 $this->queried_terms[ $taxonomy ]['terms'] = $cleaned_clause['terms'];
792 if ( ! empty( $cleaned_clause['field'] ) && ! isset( $this->queried_terms[ $taxonomy ]['field'] ) ) {
793 $this->queried_terms[ $taxonomy ]['field'] = $cleaned_clause['field'];
797 // Otherwise, it's a nested query, so we recurse.
798 } else if ( is_array( $query ) ) {
799 $cleaned_subquery = $this->sanitize_query( $query );
801 if ( ! empty( $cleaned_subquery ) ) {
802 // All queries with children must have a relation.
803 if ( ! isset( $cleaned_subquery['relation'] ) ) {
804 $cleaned_subquery['relation'] = 'AND';
807 $cleaned_query[] = $cleaned_subquery;
812 return $cleaned_query;
816 * Sanitize a 'relation' operator.
821 * @param string $relation Raw relation key from the query argument.
822 * @return string Sanitized relation ('AND' or 'OR').
824 public function sanitize_relation( $relation ) {
825 if ( 'OR' === strtoupper( $relation ) ) {
833 * Determine whether a clause is first-order.
835 * A "first-order" clause is one that contains any of the first-order
836 * clause keys ('terms', 'taxonomy', 'include_children', 'field',
837 * 'operator'). An empty clause also counts as a first-order clause,
838 * for backward compatibility. Any clause that doesn't meet this is
839 * determined, by process of elimination, to be a higher-order query.
844 * @param array $query Tax query arguments.
845 * @return bool Whether the query clause is a first-order clause.
847 protected static function is_first_order_clause( $query ) {
848 return is_array( $query ) && ( empty( $query ) || array_key_exists( 'terms', $query ) || array_key_exists( 'taxonomy', $query ) || array_key_exists( 'include_children', $query ) || array_key_exists( 'field', $query ) || array_key_exists( 'operator', $query ) );
852 * Generates SQL clauses to be appended to a main query.
857 * @param string $primary_table Database table where the object being filtered is stored (eg wp_users).
858 * @param string $primary_id_column ID column for the filtered object in $primary_table.
860 * Array containing JOIN and WHERE SQL clauses to append to the main query.
862 * @type string $join SQL fragment to append to the main JOIN clause.
863 * @type string $where SQL fragment to append to the main WHERE clause.
866 public function get_sql( $primary_table, $primary_id_column ) {
867 $this->primary_table = $primary_table;
868 $this->primary_id_column = $primary_id_column;
870 return $this->get_sql_clauses();
874 * Generate SQL clauses to be appended to a main query.
876 * Called by the public {@see WP_Tax_Query::get_sql()}, this method
877 * is abstracted out to maintain parity with the other Query classes.
883 * Array containing JOIN and WHERE SQL clauses to append to the main query.
885 * @type string $join SQL fragment to append to the main JOIN clause.
886 * @type string $where SQL fragment to append to the main WHERE clause.
889 protected function get_sql_clauses() {
891 * $queries are passed by reference to get_sql_for_query() for recursion.
892 * To keep $this->queries unaltered, pass a copy.
894 $queries = $this->queries;
895 $sql = $this->get_sql_for_query( $queries );
897 if ( ! empty( $sql['where'] ) ) {
898 $sql['where'] = ' AND ' . $sql['where'];
905 * Generate SQL clauses for a single query array.
907 * If nested subqueries are found, this method recurses the tree to
908 * produce the properly nested SQL.
913 * @param array $query Query to parse, passed by reference.
914 * @param int $depth Optional. Number of tree levels deep we currently are.
915 * Used to calculate indentation. Default 0.
917 * Array containing JOIN and WHERE SQL clauses to append to a single query array.
919 * @type string $join SQL fragment to append to the main JOIN clause.
920 * @type string $where SQL fragment to append to the main WHERE clause.
923 protected function get_sql_for_query( &$query, $depth = 0 ) {
935 for ( $i = 0; $i < $depth; $i++ ) {
939 foreach ( $query as $key => &$clause ) {
940 if ( 'relation' === $key ) {
941 $relation = $query['relation'];
942 } else if ( is_array( $clause ) ) {
944 // This is a first-order clause.
945 if ( $this->is_first_order_clause( $clause ) ) {
946 $clause_sql = $this->get_sql_for_clause( $clause, $query );
948 $where_count = count( $clause_sql['where'] );
949 if ( ! $where_count ) {
950 $sql_chunks['where'][] = '';
951 } else if ( 1 === $where_count ) {
952 $sql_chunks['where'][] = $clause_sql['where'][0];
954 $sql_chunks['where'][] = '( ' . implode( ' AND ', $clause_sql['where'] ) . ' )';
957 $sql_chunks['join'] = array_merge( $sql_chunks['join'], $clause_sql['join'] );
958 // This is a subquery, so we recurse.
960 $clause_sql = $this->get_sql_for_query( $clause, $depth + 1 );
962 $sql_chunks['where'][] = $clause_sql['where'];
963 $sql_chunks['join'][] = $clause_sql['join'];
968 // Filter to remove empties.
969 $sql_chunks['join'] = array_filter( $sql_chunks['join'] );
970 $sql_chunks['where'] = array_filter( $sql_chunks['where'] );
972 if ( empty( $relation ) ) {
976 // Filter duplicate JOIN clauses and combine into a single string.
977 if ( ! empty( $sql_chunks['join'] ) ) {
978 $sql['join'] = implode( ' ', array_unique( $sql_chunks['join'] ) );
981 // Generate a single WHERE clause with proper brackets and indentation.
982 if ( ! empty( $sql_chunks['where'] ) ) {
983 $sql['where'] = '( ' . "\n " . $indent . implode( ' ' . "\n " . $indent . $relation . ' ' . "\n " . $indent, $sql_chunks['where'] ) . "\n" . $indent . ')';
990 * Generate SQL JOIN and WHERE clauses for a "first-order" query clause.
995 * @param array $clause Query clause, passed by reference
996 * @param array $parent_query Parent query array.
998 * Array containing JOIN and WHERE SQL clauses to append to a first-order query.
1000 * @type string $join SQL fragment to append to the main JOIN clause.
1001 * @type string $where SQL fragment to append to the main WHERE clause.
1004 public function get_sql_for_clause( &$clause, $parent_query ) {
1014 $this->clean_query( $clause );
1016 if ( is_wp_error( $clause ) ) {
1017 return self::$no_results;
1020 $terms = $clause['terms'];
1021 $operator = strtoupper( $clause['operator'] );
1023 if ( 'IN' == $operator ) {
1025 if ( empty( $terms ) ) {
1026 return self::$no_results;
1029 $terms = implode( ',', $terms );
1032 * Before creating another table join, see if this clause has a
1033 * sibling with an existing join that can be shared.
1035 $alias = $this->find_compatible_table_alias( $clause, $parent_query );
1036 if ( false === $alias ) {
1037 $i = count( $this->table_aliases );
1038 $alias = $i ? 'tt' . $i : $wpdb->term_relationships;
1040 // Store the alias as part of a flat array to build future iterators.
1041 $this->table_aliases[] = $alias;
1043 // Store the alias with this clause, so later siblings can use it.
1044 $clause['alias'] = $alias;
1046 $join .= " INNER JOIN $wpdb->term_relationships";
1047 $join .= $i ? " AS $alias" : '';
1048 $join .= " ON ($this->primary_table.$this->primary_id_column = $alias.object_id)";
1052 $where = "$alias.term_taxonomy_id $operator ($terms)";
1054 } elseif ( 'NOT IN' == $operator ) {
1056 if ( empty( $terms ) ) {
1060 $terms = implode( ',', $terms );
1062 $where = "$this->primary_table.$this->primary_id_column NOT IN (
1064 FROM $wpdb->term_relationships
1065 WHERE term_taxonomy_id IN ($terms)
1068 } elseif ( 'AND' == $operator ) {
1070 if ( empty( $terms ) ) {
1074 $num_terms = count( $terms );
1076 $terms = implode( ',', $terms );
1080 FROM $wpdb->term_relationships
1081 WHERE term_taxonomy_id IN ($terms)
1082 AND object_id = $this->primary_table.$this->primary_id_column
1085 } elseif ( 'NOT EXISTS' === $operator || 'EXISTS' === $operator ) {
1087 $where = $wpdb->prepare( "$operator (
1089 FROM $wpdb->term_relationships
1090 INNER JOIN $wpdb->term_taxonomy
1091 ON $wpdb->term_taxonomy.term_taxonomy_id = $wpdb->term_relationships.term_taxonomy_id
1092 WHERE $wpdb->term_taxonomy.taxonomy = %s
1093 AND $wpdb->term_relationships.object_id = $this->primary_table.$this->primary_id_column
1094 )", $clause['taxonomy'] );
1098 $sql['join'][] = $join;
1099 $sql['where'][] = $where;
1104 * Identify an existing table alias that is compatible with the current query clause.
1106 * We avoid unnecessary table joins by allowing each clause to look for
1107 * an existing table alias that is compatible with the query that it
1110 * An existing alias is compatible if (a) it is a sibling of `$clause`
1111 * (ie, it's under the scope of the same relation), and (b) the combination
1112 * of operator and relation between the clauses allows for a shared table
1113 * join. In the case of {@see WP_Tax_Query}, this only applies to 'IN'
1114 * clauses that are connected by the relation 'OR'.
1119 * @param array $clause Query clause.
1120 * @param array $parent_query Parent query of $clause.
1121 * @return string|bool Table alias if found, otherwise false.
1123 protected function find_compatible_table_alias( $clause, $parent_query ) {
1126 // Sanity check. Only IN queries use the JOIN syntax .
1127 if ( ! isset( $clause['operator'] ) || 'IN' !== $clause['operator'] ) {
1131 // Since we're only checking IN queries, we're only concerned with OR relations.
1132 if ( ! isset( $parent_query['relation'] ) || 'OR' !== $parent_query['relation'] ) {
1136 $compatible_operators = array( 'IN' );
1138 foreach ( $parent_query as $sibling ) {
1139 if ( ! is_array( $sibling ) || ! $this->is_first_order_clause( $sibling ) ) {
1143 if ( empty( $sibling['alias'] ) || empty( $sibling['operator'] ) ) {
1147 // The sibling must both have compatible operator to share its alias.
1148 if ( in_array( strtoupper( $sibling['operator'] ), $compatible_operators ) ) {
1149 $alias = $sibling['alias'];
1158 * Validates a single query.
1163 * @param array &$query The single query.
1165 private function clean_query( &$query ) {
1166 if ( empty( $query['taxonomy'] ) ) {
1167 if ( 'term_taxonomy_id' !== $query['field'] ) {
1168 $query = new WP_Error( 'Invalid taxonomy' );
1172 // so long as there are shared terms, include_children requires that a taxonomy is set
1173 $query['include_children'] = false;
1174 } elseif ( ! taxonomy_exists( $query['taxonomy'] ) ) {
1175 $query = new WP_Error( 'Invalid taxonomy' );
1179 $query['terms'] = array_unique( (array) $query['terms'] );
1181 if ( is_taxonomy_hierarchical( $query['taxonomy'] ) && $query['include_children'] ) {
1182 $this->transform_query( $query, 'term_id' );
1184 if ( is_wp_error( $query ) )
1187 $children = array();
1188 foreach ( $query['terms'] as $term ) {
1189 $children = array_merge( $children, get_term_children( $term, $query['taxonomy'] ) );
1190 $children[] = $term;
1192 $query['terms'] = $children;
1195 $this->transform_query( $query, 'term_taxonomy_id' );
1199 * Transforms a single query, from one field to another.
1203 * @param array &$query The single query.
1204 * @param string $resulting_field The resulting field. Accepts 'slug', 'name', 'term_taxonomy_id',
1205 * or 'term_id'. Default: 'term_id'.
1207 public function transform_query( &$query, $resulting_field ) {
1210 if ( empty( $query['terms'] ) )
1213 if ( $query['field'] == $resulting_field )
1216 $resulting_field = sanitize_key( $resulting_field );
1218 switch ( $query['field'] ) {
1221 $terms = "'" . implode( "','", array_map( 'sanitize_title_for_query', $query['terms'] ) ) . "'";
1222 $terms = $wpdb->get_col( "
1223 SELECT $wpdb->term_taxonomy.$resulting_field
1224 FROM $wpdb->term_taxonomy
1225 INNER JOIN $wpdb->terms USING (term_id)
1226 WHERE taxonomy = '{$query['taxonomy']}'
1227 AND $wpdb->terms.{$query['field']} IN ($terms)
1230 case 'term_taxonomy_id':
1231 $terms = implode( ',', array_map( 'intval', $query['terms'] ) );
1232 $terms = $wpdb->get_col( "
1233 SELECT $resulting_field
1234 FROM $wpdb->term_taxonomy
1235 WHERE term_taxonomy_id IN ($terms)
1239 $terms = implode( ',', array_map( 'intval', $query['terms'] ) );
1240 $terms = $wpdb->get_col( "
1241 SELECT $resulting_field
1242 FROM $wpdb->term_taxonomy
1243 WHERE taxonomy = '{$query['taxonomy']}'
1244 AND term_id IN ($terms)
1248 if ( 'AND' == $query['operator'] && count( $terms ) < count( $query['terms'] ) ) {
1249 $query = new WP_Error( 'Inexistent terms' );
1253 $query['terms'] = $terms;
1254 $query['field'] = $resulting_field;
1259 * Get all Term data from database by Term ID.
1261 * The usage of the get_term function is to apply filters to a term object. It
1262 * is possible to get a term object from the database before applying the
1265 * $term ID must be part of $taxonomy, to get from the database. Failure, might
1266 * be able to be captured by the hooks. Failure would be the same value as $wpdb
1267 * returns for the get_row method.
1269 * There are two hooks, one is specifically for each term, named 'get_term', and
1270 * the second is for the taxonomy name, 'term_$taxonomy'. Both hooks gets the
1271 * term object, and the taxonomy name as parameters. Both hooks are expected to
1272 * return a Term object.
1274 * 'get_term' hook - Takes two parameters the term Object and the taxonomy name.
1275 * Must return term object. Used in get_term() as a catch-all filter for every
1278 * 'get_$taxonomy' hook - Takes two parameters the term Object and the taxonomy
1279 * name. Must return term object. $taxonomy will be the taxonomy name, so for
1280 * example, if 'category', it would be 'get_category' as the filter name. Useful
1281 * for custom taxonomies or plugging into default taxonomies.
1285 * @global wpdb $wpdb WordPress database abstraction object.
1286 * @see sanitize_term_field() The $context param lists the available values for get_term_by() $filter param.
1288 * @param int|object $term If integer, will get from database. If object will apply filters and return $term.
1289 * @param string $taxonomy Taxonomy name that $term is part of.
1290 * @param string $output Constant OBJECT, ARRAY_A, or ARRAY_N
1291 * @param string $filter Optional, default is raw or no WordPress defined filter will applied.
1292 * @return mixed|null|WP_Error Term Row from database. Will return null if $term is empty. If taxonomy does not
1293 * exist then WP_Error will be returned.
1295 function get_term($term, $taxonomy, $output = OBJECT, $filter = 'raw') {
1298 if ( empty($term) ) {
1299 $error = new WP_Error('invalid_term', __('Empty Term'));
1303 if ( ! taxonomy_exists($taxonomy) ) {
1304 $error = new WP_Error('invalid_taxonomy', __('Invalid taxonomy'));
1308 if ( is_object($term) && empty($term->filter) ) {
1309 wp_cache_add( $term->term_id, $term, $taxonomy );
1312 if ( is_object($term) )
1313 $term = $term->term_id;
1314 if ( !$term = (int) $term )
1316 if ( ! $_term = wp_cache_get( $term, $taxonomy ) ) {
1317 $_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) );
1320 wp_cache_add( $term, $_term, $taxonomy );
1329 * @param int|object $_term Term object or ID.
1330 * @param string $taxonomy The taxonomy slug.
1332 $_term = apply_filters( 'get_term', $_term, $taxonomy );
1335 * Filter a taxonomy.
1337 * The dynamic portion of the filter name, `$taxonomy`, refers
1338 * to the taxonomy slug.
1342 * @param int|object $_term Term object or ID.
1343 * @param string $taxonomy The taxonomy slug.
1345 $_term = apply_filters( "get_$taxonomy", $_term, $taxonomy );
1346 $_term = sanitize_term($_term, $taxonomy, $filter);
1348 if ( $output == OBJECT ) {
1350 } elseif ( $output == ARRAY_A ) {
1351 $__term = get_object_vars($_term);
1353 } elseif ( $output == ARRAY_N ) {
1354 $__term = array_values(get_object_vars($_term));
1362 * Get all Term data from database by Term field and data.
1364 * Warning: $value is not escaped for 'name' $field. You must do it yourself, if
1367 * The default $field is 'id', therefore it is possible to also use null for
1368 * field, but not recommended that you do so.
1370 * If $value does not exist, the return value will be false. If $taxonomy exists
1371 * and $field and $value combinations exist, the Term will be returned.
1375 * @global wpdb $wpdb WordPress database abstraction object.
1376 * @see sanitize_term_field() The $context param lists the available values for get_term_by() $filter param.
1378 * @param string $field Either 'slug', 'name', 'id' (term_id), or 'term_taxonomy_id'
1379 * @param string|int $value Search for this term value
1380 * @param string $taxonomy Taxonomy Name
1381 * @param string $output Constant OBJECT, ARRAY_A, or ARRAY_N
1382 * @param string $filter Optional, default is raw or no WordPress defined filter will applied.
1383 * @return mixed Term Row from database. Will return false if $taxonomy does not exist or $term was not found.
1385 function get_term_by($field, $value, $taxonomy, $output = OBJECT, $filter = 'raw') {
1388 if ( ! taxonomy_exists($taxonomy) )
1391 if ( 'slug' == $field ) {
1393 $value = sanitize_title($value);
1394 if ( empty($value) )
1396 } else if ( 'name' == $field ) {
1397 // Assume already escaped
1398 $value = wp_unslash($value);
1400 } else if ( 'term_taxonomy_id' == $field ) {
1401 $value = (int) $value;
1402 $field = 'tt.term_taxonomy_id';
1404 $term = get_term( (int) $value, $taxonomy, $output, $filter );
1405 if ( is_wp_error( $term ) )
1410 $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 ) );
1414 wp_cache_add( $term->term_id, $term, $taxonomy );
1416 /** This filter is documented in wp-includes/taxonomy.php */
1417 $term = apply_filters( 'get_term', $term, $taxonomy );
1419 /** This filter is documented in wp-includes/taxonomy.php */
1420 $term = apply_filters( "get_$taxonomy", $term, $taxonomy );
1422 $term = sanitize_term($term, $taxonomy, $filter);
1424 if ( $output == OBJECT ) {
1426 } elseif ( $output == ARRAY_A ) {
1427 return get_object_vars($term);
1428 } elseif ( $output == ARRAY_N ) {
1429 return array_values(get_object_vars($term));
1436 * Merge all term children into a single array of their IDs.
1438 * This recursive function will merge all of the children of $term into the same
1439 * array of term IDs. Only useful for taxonomies which are hierarchical.
1441 * Will return an empty array if $term does not exist in $taxonomy.
1445 * @global wpdb $wpdb WordPress database abstraction object.
1447 * @param string $term_id ID of Term to get children
1448 * @param string $taxonomy Taxonomy Name
1449 * @return array|WP_Error List of Term IDs. WP_Error returned if $taxonomy does not exist
1451 function get_term_children( $term_id, $taxonomy ) {
1452 if ( ! taxonomy_exists($taxonomy) )
1453 return new WP_Error('invalid_taxonomy', __('Invalid taxonomy'));
1455 $term_id = intval( $term_id );
1457 $terms = _get_term_hierarchy($taxonomy);
1459 if ( ! isset($terms[$term_id]) )
1462 $children = $terms[$term_id];
1464 foreach ( (array) $terms[$term_id] as $child ) {
1465 if ( $term_id == $child ) {
1469 if ( isset($terms[$child]) )
1470 $children = array_merge($children, get_term_children($child, $taxonomy));
1477 * Get sanitized Term field.
1479 * Does checks for $term, based on the $taxonomy. The function is for contextual
1480 * reasons and for simplicity of usage. See sanitize_term_field() for more
1485 * @param string $field Term field to fetch
1486 * @param int $term Term ID
1487 * @param string $taxonomy Taxonomy Name
1488 * @param string $context Optional, default is display. Look at sanitize_term_field() for available options.
1489 * @return mixed Will return an empty string if $term is not an object or if $field is not set in $term.
1491 function get_term_field( $field, $term, $taxonomy, $context = 'display' ) {
1492 $term = (int) $term;
1493 $term = get_term( $term, $taxonomy );
1494 if ( is_wp_error($term) )
1497 if ( !is_object($term) )
1500 if ( !isset($term->$field) )
1503 return sanitize_term_field($field, $term->$field, $term->term_id, $taxonomy, $context);
1507 * Sanitizes Term for editing.
1509 * Return value is sanitize_term() and usage is for sanitizing the term for
1510 * editing. Function is for contextual and simplicity.
1514 * @param int|object $id Term ID or Object
1515 * @param string $taxonomy Taxonomy Name
1516 * @return mixed|null|WP_Error Will return empty string if $term is not an object.
1518 function get_term_to_edit( $id, $taxonomy ) {
1519 $term = get_term( $id, $taxonomy );
1521 if ( is_wp_error($term) )
1524 if ( !is_object($term) )
1527 return sanitize_term($term, $taxonomy, 'edit');
1531 * Retrieve the terms in a given taxonomy or list of taxonomies.
1533 * You can fully inject any customizations to the query before it is sent, as
1534 * well as control the output with a filter.
1536 * The 'get_terms' filter will be called when the cache has the term and will
1537 * pass the found term along with the array of $taxonomies and array of $args.
1538 * This filter is also called before the array of terms is passed and will pass
1539 * the array of terms, along with the $taxonomies and $args.
1541 * The 'list_terms_exclusions' filter passes the compiled exclusions along with
1544 * The 'get_terms_orderby' filter passes the ORDER BY clause for the query
1545 * along with the $args array.
1547 * The 'get_terms_fields' filter passes the fields for the SELECT query
1548 * along with the $args array.
1552 * @global wpdb $wpdb WordPress database abstraction object.
1554 * @param string|array $taxonomies Taxonomy name or list of Taxonomy names.
1555 * @param array|string $args {
1556 * Optional. Array or string of arguments to get terms.
1558 * @type string $orderby Field(s) to order terms by. Accepts term fields ('name', 'slug',
1559 * 'term_group', 'term_id', 'id'), 'count' for term taxonomy count,
1560 * 'include' to match the 'order' of the $include param, or 'none'
1561 * to skip ORDER BY. Defaults to 'name'.
1562 * @type string $order Whether to order terms in ascending or descending order.
1563 * Accepts 'ASC' (ascending) or 'DESC' (descending).
1565 * @type bool|int $hide_empty Whether to hide terms not assigned to any posts. Accepts
1566 * 1|true or 0|false. Default 1|true.
1567 * @type array|string $include Array or comma/space-separated string of term ids to include.
1568 * Default empty array.
1569 * @type array|string $exclude Array or comma/space-separated string of term ids to exclude.
1570 * If $include is non-empty, $exclude is ignored.
1571 * Default empty array.
1572 * @type array|string $exclude_tree Array or comma/space-separated string of term ids to exclude
1573 * along with all of their descendant terms. If $include is
1574 * non-empty, $exclude_tree is ignored. Default empty array.
1575 * @type int $number Maximum number of terms to return. Accepts 1+ or -1 (all).
1577 * @type int $offset The number by which to offset the terms query. Default empty.
1578 * @type string $fields Term fields to query for. Accepts 'all' (returns an array of
1579 * term objects), 'ids' or 'names' (returns an array of integers
1580 * or strings, respectively. Default 'all'.
1581 * @type string|array $slug Optional. Slug or array of slugs to return term(s) for. Default empty.
1582 * @type bool $hierarchical Whether to include terms that have non-empty descendants (even
1583 * if $hide_empty is set to true). Default true.
1584 * @type string $search Search criteria to match terms. Will be SQL-formatted with
1585 * wildcards before and after. Default empty.
1586 * @type string $name__like Retrieve terms with criteria by which a term is LIKE $name__like.
1588 * @type string $description__like Retrieve terms where the description is LIKE $description__like.
1590 * @type bool $pad_counts Whether to pad the quantity of a term's children in the quantity
1591 * of each term's "count" object variable. Default false.
1592 * @type string $get Whether to return terms regardless of ancestry or whether the terms
1593 * are empty. Accepts 'all' or empty (disabled). Default empty.
1594 * @type int $child_of Term ID to retrieve child terms of. If multiple taxonomies
1595 * are passed, $child_of is ignored. Default 0.
1596 * @type int|string $parent Parent term ID to retrieve direct-child terms of. Default empty.
1597 * @type string $cache_domain Unique cache key to be produced when this query is stored in an
1598 * object cache. Default is 'core'.
1600 * @return array|WP_Error List of Term Objects and their children. Will return WP_Error, if any of $taxonomies
1603 function get_terms( $taxonomies, $args = '' ) {
1605 $empty_array = array();
1607 $single_taxonomy = ! is_array( $taxonomies ) || 1 === count( $taxonomies );
1608 if ( ! is_array( $taxonomies ) ) {
1609 $taxonomies = array( $taxonomies );
1612 foreach ( $taxonomies as $taxonomy ) {
1613 if ( ! taxonomy_exists($taxonomy) ) {
1614 $error = new WP_Error('invalid_taxonomy', __('Invalid taxonomy'));
1619 $defaults = array('orderby' => 'name', 'order' => 'ASC',
1620 'hide_empty' => true, 'exclude' => array(), 'exclude_tree' => array(), 'include' => array(),
1621 'number' => '', 'fields' => 'all', 'slug' => '', 'parent' => '',
1622 'hierarchical' => true, 'child_of' => 0, 'get' => '', 'name__like' => '', 'description__like' => '',
1623 'pad_counts' => false, 'offset' => '', 'search' => '', 'cache_domain' => 'core' );
1624 $args = wp_parse_args( $args, $defaults );
1625 $args['number'] = absint( $args['number'] );
1626 $args['offset'] = absint( $args['offset'] );
1628 // Save queries by not crawling the tree in the case of multiple taxes or a flat tax.
1629 if ( ! $single_taxonomy || ! is_taxonomy_hierarchical( reset( $taxonomies ) ) ) {
1630 $args['hierarchical'] = false;
1631 $args['pad_counts'] = false;
1634 // 'parent' overrides 'child_of'.
1635 if ( 0 < intval( $args['parent'] ) ) {
1636 $args['child_of'] = false;
1639 if ( 'all' == $args['get'] ) {
1640 $args['child_of'] = 0;
1641 $args['hide_empty'] = 0;
1642 $args['hierarchical'] = false;
1643 $args['pad_counts'] = false;
1647 * Filter the terms query arguments.
1651 * @param array $args An array of arguments.
1652 * @param string|array $taxonomies A taxonomy or array of taxonomies.
1654 $args = apply_filters( 'get_terms_args', $args, $taxonomies );
1656 $child_of = $args['child_of'];
1658 $hierarchy = _get_term_hierarchy( reset( $taxonomies ) );
1659 if ( ! isset( $hierarchy[ $child_of ] ) ) {
1660 return $empty_array;
1664 $parent = $args['parent'];
1666 $hierarchy = _get_term_hierarchy( reset( $taxonomies ) );
1667 if ( ! isset( $hierarchy[ $parent ] ) ) {
1668 return $empty_array;
1672 // $args can be whatever, only use the args defined in defaults to compute the key
1673 $filter_key = ( has_filter('list_terms_exclusions') ) ? serialize($GLOBALS['wp_filter']['list_terms_exclusions']) : '';
1674 $key = md5( serialize( wp_array_slice_assoc( $args, array_keys( $defaults ) ) ) . serialize( $taxonomies ) . $filter_key );
1675 $last_changed = wp_cache_get( 'last_changed', 'terms' );
1676 if ( ! $last_changed ) {
1677 $last_changed = microtime();
1678 wp_cache_set( 'last_changed', $last_changed, 'terms' );
1680 $cache_key = "get_terms:$key:$last_changed";
1681 $cache = wp_cache_get( $cache_key, 'terms' );
1682 if ( false !== $cache ) {
1685 * Filter the given taxonomy's terms cache.
1689 * @param array $cache Cached array of terms for the given taxonomy.
1690 * @param string|array $taxonomies A taxonomy or array of taxonomies.
1691 * @param array $args An array of arguments to get terms.
1693 $cache = apply_filters( 'get_terms', $cache, $taxonomies, $args );
1697 $_orderby = strtolower( $args['orderby'] );
1698 if ( 'count' == $_orderby ) {
1699 $orderby = 'tt.count';
1700 } else if ( 'name' == $_orderby ) {
1701 $orderby = 't.name';
1702 } else if ( 'slug' == $_orderby ) {
1703 $orderby = 't.slug';
1704 } else if ( 'include' == $_orderby && ! empty( $args['include'] ) ) {
1705 $include = implode( ',', array_map( 'absint', $args['include'] ) );
1706 $orderby = "FIELD( t.term_id, $include )";
1707 } else if ( 'term_group' == $_orderby ) {
1708 $orderby = 't.term_group';
1709 } else if ( 'none' == $_orderby ) {
1711 } elseif ( empty($_orderby) || 'id' == $_orderby ) {
1712 $orderby = 't.term_id';
1714 $orderby = 't.name';
1717 * Filter the ORDERBY clause of the terms query.
1721 * @param string $orderby ORDERBY clause of the terms query.
1722 * @param array $args An array of terms query arguments.
1723 * @param string|array $taxonomies A taxonomy or array of taxonomies.
1725 $orderby = apply_filters( 'get_terms_orderby', $orderby, $args, $taxonomies );
1727 $order = strtoupper( $args['order'] );
1728 if ( ! empty( $orderby ) ) {
1729 $orderby = "ORDER BY $orderby";
1734 if ( '' !== $order && ! in_array( $order, array( 'ASC', 'DESC' ) ) ) {
1738 $where = "tt.taxonomy IN ('" . implode("', '", $taxonomies) . "')";
1740 $exclude = $args['exclude'];
1741 $exclude_tree = $args['exclude_tree'];
1742 $include = $args['include'];
1745 if ( ! empty( $include ) ) {
1748 $inclusions = implode( ',', wp_parse_id_list( $include ) );
1751 if ( ! empty( $inclusions ) ) {
1752 $inclusions = ' AND t.term_id IN ( ' . $inclusions . ' )';
1753 $where .= $inclusions;
1756 if ( ! empty( $exclude_tree ) ) {
1757 $exclude_tree = wp_parse_id_list( $exclude_tree );
1758 $excluded_children = $exclude_tree;
1759 foreach ( $exclude_tree as $extrunk ) {
1760 $excluded_children = array_merge(
1762 (array) get_terms( $taxonomies[0], array( 'child_of' => intval( $extrunk ), 'fields' => 'ids', 'hide_empty' => 0 ) )
1765 $exclusions = implode( ',', array_map( 'intval', $excluded_children ) );
1770 if ( ! empty( $exclude ) ) {
1771 $exterms = wp_parse_id_list( $exclude );
1772 if ( empty( $exclusions ) ) {
1773 $exclusions = implode( ',', $exterms );
1775 $exclusions .= ', ' . implode( ',', $exterms );
1779 if ( ! empty( $exclusions ) ) {
1780 $exclusions = ' AND t.term_id NOT IN (' . $exclusions . ')';
1784 * Filter the terms to exclude from the terms query.
1788 * @param string $exclusions NOT IN clause of the terms query.
1789 * @param array $args An array of terms query arguments.
1790 * @param string|array $taxonomies A taxonomy or array of taxonomies.
1792 $exclusions = apply_filters( 'list_terms_exclusions', $exclusions, $args, $taxonomies );
1794 if ( ! empty( $exclusions ) ) {
1795 $where .= $exclusions;
1798 if ( ! empty( $args['slug'] ) ) {
1799 if ( is_array( $args['slug'] ) ) {
1800 $slug = array_map( 'sanitize_title', $args['slug'] );
1801 $where .= " AND t.slug IN ('" . implode( "', '", $slug ) . "')";
1803 $slug = sanitize_title( $args['slug'] );
1804 $where .= " AND t.slug = '$slug'";
1808 if ( ! empty( $args['name__like'] ) ) {
1809 $where .= $wpdb->prepare( " AND t.name LIKE %s", '%' . $wpdb->esc_like( $args['name__like'] ) . '%' );
1812 if ( ! empty( $args['description__like'] ) ) {
1813 $where .= $wpdb->prepare( " AND tt.description LIKE %s", '%' . $wpdb->esc_like( $args['description__like'] ) . '%' );
1816 if ( '' !== $parent ) {
1817 $parent = (int) $parent;
1818 $where .= " AND tt.parent = '$parent'";
1821 $hierarchical = $args['hierarchical'];
1822 if ( 'count' == $args['fields'] ) {
1823 $hierarchical = false;
1825 if ( $args['hide_empty'] && !$hierarchical ) {
1826 $where .= ' AND tt.count > 0';
1829 $number = $args['number'];
1830 $offset = $args['offset'];
1832 // don't limit the query results when we have to descend the family tree
1833 if ( $number && ! $hierarchical && ! $child_of && '' === $parent ) {
1835 $limits = 'LIMIT ' . $offset . ',' . $number;
1837 $limits = 'LIMIT ' . $number;
1843 if ( ! empty( $args['search'] ) ) {
1844 $like = '%' . $wpdb->esc_like( $args['search'] ) . '%';
1845 $where .= $wpdb->prepare( ' AND ((t.name LIKE %s) OR (t.slug LIKE %s))', $like, $like );
1849 switch ( $args['fields'] ) {
1851 $selects = array( 't.*', 'tt.*' );
1855 $selects = array( 't.term_id', 'tt.parent', 'tt.count' );
1858 $selects = array( 't.term_id', 'tt.parent', 'tt.count', 't.name' );
1863 $selects = array( 'COUNT(*)' );
1866 $selects = array( 't.term_id', 't.name', 'tt.count' );
1869 $selects = array( 't.term_id', 't.slug', 'tt.count' );
1873 $_fields = $args['fields'];
1876 * Filter the fields to select in the terms query.
1880 * @param array $selects An array of fields to select for the terms query.
1881 * @param array $args An array of term query arguments.
1882 * @param string|array $taxonomies A taxonomy or array of taxonomies.
1884 $fields = implode( ', ', apply_filters( 'get_terms_fields', $selects, $args, $taxonomies ) );
1886 $join = "INNER JOIN $wpdb->term_taxonomy AS tt ON t.term_id = tt.term_id";
1888 $pieces = array( 'fields', 'join', 'where', 'orderby', 'order', 'limits' );
1891 * Filter the terms query SQL clauses.
1895 * @param array $pieces Terms query SQL clauses.
1896 * @param string|array $taxonomies A taxonomy or array of taxonomies.
1897 * @param array $args An array of terms query arguments.
1899 $clauses = apply_filters( 'terms_clauses', compact( $pieces ), $taxonomies, $args );
1900 $fields = isset( $clauses[ 'fields' ] ) ? $clauses[ 'fields' ] : '';
1901 $join = isset( $clauses[ 'join' ] ) ? $clauses[ 'join' ] : '';
1902 $where = isset( $clauses[ 'where' ] ) ? $clauses[ 'where' ] : '';
1903 $orderby = isset( $clauses[ 'orderby' ] ) ? $clauses[ 'orderby' ] : '';
1904 $order = isset( $clauses[ 'order' ] ) ? $clauses[ 'order' ] : '';
1905 $limits = isset( $clauses[ 'limits' ] ) ? $clauses[ 'limits' ] : '';
1907 $query = "SELECT $fields FROM $wpdb->terms AS t $join WHERE $where $orderby $order $limits";
1909 if ( 'count' == $_fields ) {
1910 $term_count = $wpdb->get_var($query);
1914 $terms = $wpdb->get_results($query);
1915 if ( 'all' == $_fields ) {
1916 update_term_cache( $terms );
1919 if ( empty($terms) ) {
1920 wp_cache_add( $cache_key, array(), 'terms', DAY_IN_SECONDS );
1922 /** This filter is documented in wp-includes/taxonomy.php */
1923 $terms = apply_filters( 'get_terms', array(), $taxonomies, $args );
1928 $children = _get_term_hierarchy( reset( $taxonomies ) );
1929 if ( ! empty( $children ) ) {
1930 $terms = _get_term_children( $child_of, $terms, reset( $taxonomies ) );
1934 // Update term counts to include children.
1935 if ( $args['pad_counts'] && 'all' == $_fields ) {
1936 _pad_term_counts( $terms, reset( $taxonomies ) );
1938 // Make sure we show empty categories that have children.
1939 if ( $hierarchical && $args['hide_empty'] && is_array( $terms ) ) {
1940 foreach ( $terms as $k => $term ) {
1941 if ( ! $term->count ) {
1942 $children = get_term_children( $term->term_id, reset( $taxonomies ) );
1943 if ( is_array( $children ) ) {
1944 foreach ( $children as $child_id ) {
1945 $child = get_term( $child_id, reset( $taxonomies ) );
1946 if ( $child->count ) {
1952 // It really is empty
1960 if ( 'id=>parent' == $_fields ) {
1961 while ( $term = array_shift( $terms ) ) {
1962 $_terms[$term->term_id] = $term->parent;
1964 } elseif ( 'ids' == $_fields ) {
1965 while ( $term = array_shift( $terms ) ) {
1966 $_terms[] = $term->term_id;
1968 } elseif ( 'names' == $_fields ) {
1969 while ( $term = array_shift( $terms ) ) {
1970 $_terms[] = $term->name;
1972 } elseif ( 'id=>name' == $_fields ) {
1973 while ( $term = array_shift( $terms ) ) {
1974 $_terms[$term->term_id] = $term->name;
1976 } elseif ( 'id=>slug' == $_fields ) {
1977 while ( $term = array_shift( $terms ) ) {
1978 $_terms[$term->term_id] = $term->slug;
1982 if ( ! empty( $_terms ) ) {
1986 if ( $number && is_array( $terms ) && count( $terms ) > $number ) {
1987 $terms = array_slice( $terms, $offset, $number );
1990 wp_cache_add( $cache_key, $terms, 'terms', DAY_IN_SECONDS );
1992 /** This filter is documented in wp-includes/taxonomy */
1993 $terms = apply_filters( 'get_terms', $terms, $taxonomies, $args );
1998 * Check if Term exists.
2000 * Formerly is_term(), introduced in 2.3.0.
2004 * @global wpdb $wpdb WordPress database abstraction object.
2006 * @param int|string $term The term to check
2007 * @param string $taxonomy The taxonomy name to use
2008 * @param int $parent Optional. ID of parent term under which to confine the exists search.
2009 * @return mixed Returns null if the term does not exist. Returns the term ID
2010 * if no taxonomy is specified and the term ID exists. Returns
2011 * an array of the term ID and the term taxonomy ID the taxonomy
2012 * is specified and the pairing exists.
2014 function term_exists( $term, $taxonomy = '', $parent = null ) {
2017 $select = "SELECT term_id FROM $wpdb->terms as t WHERE ";
2018 $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 ";
2020 if ( is_int($term) ) {
2023 $where = 't.term_id = %d';
2024 if ( !empty($taxonomy) )
2025 return $wpdb->get_row( $wpdb->prepare( $tax_select . $where . " AND tt.taxonomy = %s", $term, $taxonomy ), ARRAY_A );
2027 return $wpdb->get_var( $wpdb->prepare( $select . $where, $term ) );
2030 $term = trim( wp_unslash( $term ) );
2031 $slug = sanitize_title( $term );
2033 $where = 't.slug = %s';
2034 $else_where = 't.name = %s';
2035 $where_fields = array($slug);
2036 $else_where_fields = array($term);
2037 $orderby = 'ORDER BY t.term_id ASC';
2039 if ( !empty($taxonomy) ) {
2040 if ( is_numeric( $parent ) ) {
2041 $parent = (int) $parent;
2042 $where_fields[] = $parent;
2043 $else_where_fields[] = $parent;
2044 $where .= ' AND tt.parent = %d';
2045 $else_where .= ' AND tt.parent = %d';
2048 $where_fields[] = $taxonomy;
2049 $else_where_fields[] = $taxonomy;
2051 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 $orderby $limit", $where_fields), ARRAY_A) )
2054 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 $orderby $limit", $else_where_fields), ARRAY_A);
2057 if ( $result = $wpdb->get_var( $wpdb->prepare("SELECT term_id FROM $wpdb->terms as t WHERE $where $orderby $limit", $where_fields) ) )
2060 return $wpdb->get_var( $wpdb->prepare("SELECT term_id FROM $wpdb->terms as t WHERE $else_where $orderby $limit", $else_where_fields) );
2064 * Check if a term is an ancestor of another term.
2066 * You can use either an id or the term object for both parameters.
2070 * @param int|object $term1 ID or object to check if this is the parent term.
2071 * @param int|object $term2 The child term.
2072 * @param string $taxonomy Taxonomy name that $term1 and $term2 belong to.
2073 * @return bool Whether $term2 is child of $term1
2075 function term_is_ancestor_of( $term1, $term2, $taxonomy ) {
2076 if ( ! isset( $term1->term_id ) )
2077 $term1 = get_term( $term1, $taxonomy );
2078 if ( ! isset( $term2->parent ) )
2079 $term2 = get_term( $term2, $taxonomy );
2081 if ( empty( $term1->term_id ) || empty( $term2->parent ) )
2083 if ( $term2->parent == $term1->term_id )
2086 return term_is_ancestor_of( $term1, get_term( $term2->parent, $taxonomy ), $taxonomy );
2090 * Sanitize Term all fields.
2092 * Relies on sanitize_term_field() to sanitize the term. The difference is that
2093 * this function will sanitize <strong>all</strong> fields. The context is based
2094 * on sanitize_term_field().
2096 * The $term is expected to be either an array or an object.
2100 * @param array|object $term The term to check
2101 * @param string $taxonomy The taxonomy name to use
2102 * @param string $context Default is 'display'.
2103 * @return array|object Term with all fields sanitized
2105 function sanitize_term($term, $taxonomy, $context = 'display') {
2107 $fields = array( 'term_id', 'name', 'description', 'slug', 'count', 'parent', 'term_group', 'term_taxonomy_id', 'object_id' );
2109 $do_object = is_object( $term );
2111 $term_id = $do_object ? $term->term_id : (isset($term['term_id']) ? $term['term_id'] : 0);
2113 foreach ( (array) $fields as $field ) {
2115 if ( isset($term->$field) )
2116 $term->$field = sanitize_term_field($field, $term->$field, $term_id, $taxonomy, $context);
2118 if ( isset($term[$field]) )
2119 $term[$field] = sanitize_term_field($field, $term[$field], $term_id, $taxonomy, $context);
2124 $term->filter = $context;
2126 $term['filter'] = $context;
2132 * Cleanse the field value in the term based on the context.
2134 * Passing a term field value through the function should be assumed to have
2135 * cleansed the value for whatever context the term field is going to be used.
2137 * If no context or an unsupported context is given, then default filters will
2140 * There are enough filters for each context to support a custom filtering
2141 * without creating your own filter function. Simply create a function that
2142 * hooks into the filter you need.
2146 * @global wpdb $wpdb WordPress database abstraction object.
2148 * @param string $field Term field to sanitize
2149 * @param string $value Search for this term value
2150 * @param int $term_id Term ID
2151 * @param string $taxonomy Taxonomy Name
2152 * @param string $context Either edit, db, display, attribute, or js.
2153 * @return mixed sanitized field
2155 function sanitize_term_field($field, $value, $term_id, $taxonomy, $context) {
2156 $int_fields = array( 'parent', 'term_id', 'count', 'term_group', 'term_taxonomy_id', 'object_id' );
2157 if ( in_array( $field, $int_fields ) ) {
2158 $value = (int) $value;
2163 if ( 'raw' == $context )
2166 if ( 'edit' == $context ) {
2169 * Filter a term field to edit before it is sanitized.
2171 * The dynamic portion of the filter name, `$field`, refers to the term field.
2175 * @param mixed $value Value of the term field.
2176 * @param int $term_id Term ID.
2177 * @param string $taxonomy Taxonomy slug.
2179 $value = apply_filters( "edit_term_{$field}", $value, $term_id, $taxonomy );
2182 * Filter the taxonomy field to edit before it is sanitized.
2184 * The dynamic portions of the filter name, `$taxonomy` and `$field`, refer
2185 * to the taxonomy slug and taxonomy field, respectively.
2189 * @param mixed $value Value of the taxonomy field to edit.
2190 * @param int $term_id Term ID.
2192 $value = apply_filters( "edit_{$taxonomy}_{$field}", $value, $term_id );
2193 if ( 'description' == $field )
2194 $value = esc_html($value); // textarea_escaped
2196 $value = esc_attr($value);
2197 } else if ( 'db' == $context ) {
2200 * Filter a term field value before it is sanitized.
2202 * The dynamic portion of the filter name, `$field`, refers to the term field.
2206 * @param mixed $value Value of the term field.
2207 * @param string $taxonomy Taxonomy slug.
2209 $value = apply_filters( "pre_term_{$field}", $value, $taxonomy );
2212 * Filter a taxonomy field before it is sanitized.
2214 * The dynamic portions of the filter name, `$taxonomy` and `$field`, refer
2215 * to the taxonomy slug and field name, respectively.
2219 * @param mixed $value Value of the taxonomy field.
2221 $value = apply_filters( "pre_{$taxonomy}_{$field}", $value );
2222 // Back compat filters
2223 if ( 'slug' == $field ) {
2225 * Filter the category nicename before it is sanitized.
2227 * Use the pre_{$taxonomy}_{$field} hook instead.
2231 * @param string $value The category nicename.
2233 $value = apply_filters( 'pre_category_nicename', $value );
2236 } else if ( 'rss' == $context ) {
2239 * Filter the term field for use in RSS.
2241 * The dynamic portion of the filter name, `$field`, refers to the term field.
2245 * @param mixed $value Value of the term field.
2246 * @param string $taxonomy Taxonomy slug.
2248 $value = apply_filters( "term_{$field}_rss", $value, $taxonomy );
2251 * Filter the taxonomy field for use in RSS.
2253 * The dynamic portions of the hook name, `$taxonomy`, and $field, refer
2254 * to the taxonomy slug and field name, respectively.
2258 * @param mixed $value Value of the taxonomy field.
2260 $value = apply_filters( "{$taxonomy}_{$field}_rss", $value );
2262 // Use display filters by default.
2265 * Filter the term field sanitized for display.
2267 * The dynamic portion of the filter name, `$field`, refers to the term field name.
2271 * @param mixed $value Value of the term field.
2272 * @param int $term_id Term ID.
2273 * @param string $taxonomy Taxonomy slug.
2274 * @param string $context Context to retrieve the term field value.
2276 $value = apply_filters( "term_{$field}", $value, $term_id, $taxonomy, $context );
2279 * Filter the taxonomy field sanitized for display.
2281 * The dynamic portions of the filter name, `$taxonomy`, and $field, refer
2282 * to the taxonomy slug and taxonomy field, respectively.
2286 * @param mixed $value Value of the taxonomy field.
2287 * @param int $term_id Term ID.
2288 * @param string $context Context to retrieve the taxonomy field value.
2290 $value = apply_filters( "{$taxonomy}_{$field}", $value, $term_id, $context );
2293 if ( 'attribute' == $context )
2294 $value = esc_attr($value);
2295 else if ( 'js' == $context )
2296 $value = esc_js($value);
2302 * Count how many terms are in Taxonomy.
2304 * Default $args is 'hide_empty' which can be 'hide_empty=true' or array('hide_empty' => true).
2308 * @param string $taxonomy Taxonomy name
2309 * @param array|string $args Overwrite defaults. See get_terms()
2310 * @return int|WP_Error How many terms are in $taxonomy. WP_Error if $taxonomy does not exist.
2312 function wp_count_terms( $taxonomy, $args = array() ) {
2313 $defaults = array('hide_empty' => false);
2314 $args = wp_parse_args($args, $defaults);
2316 // backwards compatibility
2317 if ( isset($args['ignore_empty']) ) {
2318 $args['hide_empty'] = $args['ignore_empty'];
2319 unset($args['ignore_empty']);
2322 $args['fields'] = 'count';
2324 return get_terms($taxonomy, $args);
2328 * Will unlink the object from the taxonomy or taxonomies.
2330 * Will remove all relationships between the object and any terms in
2331 * a particular taxonomy or taxonomies. Does not remove the term or
2336 * @param int $object_id The term Object Id that refers to the term
2337 * @param string|array $taxonomies List of Taxonomy Names or single Taxonomy name.
2339 function wp_delete_object_term_relationships( $object_id, $taxonomies ) {
2340 $object_id = (int) $object_id;
2342 if ( !is_array($taxonomies) )
2343 $taxonomies = array($taxonomies);
2345 foreach ( (array) $taxonomies as $taxonomy ) {
2346 $term_ids = wp_get_object_terms( $object_id, $taxonomy, array( 'fields' => 'ids' ) );
2347 $term_ids = array_map( 'intval', $term_ids );
2348 wp_remove_object_terms( $object_id, $term_ids, $taxonomy );
2353 * Removes a term from the database.
2355 * If the term is a parent of other terms, then the children will be updated to
2356 * that term's parent.
2358 * The $args 'default' will only override the terms found, if there is only one
2359 * term found. Any other and the found terms are used.
2361 * The $args 'force_default' will force the term supplied as default to be
2362 * assigned even if the object was not going to be termless
2366 * @global wpdb $wpdb WordPress database abstraction object.
2368 * @param int $term Term ID
2369 * @param string $taxonomy Taxonomy Name
2370 * @param array|string $args Optional. Change 'default' term id and override found term ids.
2371 * @return bool|WP_Error Returns false if not term; true if completes delete action.
2373 function wp_delete_term( $term, $taxonomy, $args = array() ) {
2376 $term = (int) $term;
2378 if ( ! $ids = term_exists($term, $taxonomy) )
2380 if ( is_wp_error( $ids ) )
2383 $tt_id = $ids['term_taxonomy_id'];
2385 $defaults = array();
2387 if ( 'category' == $taxonomy ) {
2388 $defaults['default'] = get_option( 'default_category' );
2389 if ( $defaults['default'] == $term )
2390 return 0; // Don't delete the default category
2393 $args = wp_parse_args($args, $defaults);
2395 if ( isset( $args['default'] ) ) {
2396 $default = (int) $args['default'];
2397 if ( ! term_exists( $default, $taxonomy ) ) {
2402 if ( isset( $args['force_default'] ) ) {
2403 $force_default = $args['force_default'];
2407 * Fires when deleting a term, before any modifications are made to posts or terms.
2411 * @param int $term Term ID.
2412 * @param string $taxonomy Taxonomy Name.
2414 do_action( 'pre_delete_term', $term, $taxonomy );
2416 // Update children to point to new parent
2417 if ( is_taxonomy_hierarchical($taxonomy) ) {
2418 $term_obj = get_term($term, $taxonomy);
2419 if ( is_wp_error( $term_obj ) )
2421 $parent = $term_obj->parent;
2423 $edit_ids = $wpdb->get_results( "SELECT term_id, term_taxonomy_id FROM $wpdb->term_taxonomy WHERE `parent` = " . (int)$term_obj->term_id );
2424 $edit_tt_ids = wp_list_pluck( $edit_ids, 'term_taxonomy_id' );
2427 * Fires immediately before a term to delete's children are reassigned a parent.
2431 * @param array $edit_tt_ids An array of term taxonomy IDs for the given term.
2433 do_action( 'edit_term_taxonomies', $edit_tt_ids );
2434 $wpdb->update( $wpdb->term_taxonomy, compact( 'parent' ), array( 'parent' => $term_obj->term_id) + compact( 'taxonomy' ) );
2436 // Clean the cache for all child terms.
2437 $edit_term_ids = wp_list_pluck( $edit_ids, 'term_id' );
2438 clean_term_cache( $edit_term_ids, $taxonomy );
2441 * Fires immediately after a term to delete's children are reassigned a parent.
2445 * @param array $edit_tt_ids An array of term taxonomy IDs for the given term.
2447 do_action( 'edited_term_taxonomies', $edit_tt_ids );
2450 $objects = $wpdb->get_col( $wpdb->prepare( "SELECT object_id FROM $wpdb->term_relationships WHERE term_taxonomy_id = %d", $tt_id ) );
2452 foreach ( (array) $objects as $object ) {
2453 $terms = wp_get_object_terms($object, $taxonomy, array('fields' => 'ids', 'orderby' => 'none'));
2454 if ( 1 == count($terms) && isset($default) ) {
2455 $terms = array($default);
2457 $terms = array_diff($terms, array($term));
2458 if (isset($default) && isset($force_default) && $force_default)
2459 $terms = array_merge($terms, array($default));
2461 $terms = array_map('intval', $terms);
2462 wp_set_object_terms($object, $terms, $taxonomy);
2465 // Clean the relationship caches for all object types using this term
2466 $tax_object = get_taxonomy( $taxonomy );
2467 foreach ( $tax_object->object_type as $object_type )
2468 clean_object_term_cache( $objects, $object_type );
2470 // Get the object before deletion so we can pass to actions below
2471 $deleted_term = get_term( $term, $taxonomy );
2474 * Fires immediately before a term taxonomy ID is deleted.
2478 * @param int $tt_id Term taxonomy ID.
2480 do_action( 'delete_term_taxonomy', $tt_id );
2481 $wpdb->delete( $wpdb->term_taxonomy, array( 'term_taxonomy_id' => $tt_id ) );
2484 * Fires immediately after a term taxonomy ID is deleted.
2488 * @param int $tt_id Term taxonomy ID.
2490 do_action( 'deleted_term_taxonomy', $tt_id );
2492 // Delete the term if no taxonomies use it.
2493 if ( !$wpdb->get_var( $wpdb->prepare( "SELECT COUNT(*) FROM $wpdb->term_taxonomy WHERE term_id = %d", $term) ) )
2494 $wpdb->delete( $wpdb->terms, array( 'term_id' => $term ) );
2496 clean_term_cache($term, $taxonomy);
2499 * Fires after a term is deleted from the database and the cache is cleaned.
2503 * @param int $term Term ID.
2504 * @param int $tt_id Term taxonomy ID.
2505 * @param string $taxonomy Taxonomy slug.
2506 * @param mixed $deleted_term Copy of the already-deleted term, in the form specified
2507 * by the parent function. WP_Error otherwise.
2509 do_action( 'delete_term', $term, $tt_id, $taxonomy, $deleted_term );
2512 * Fires after a term in a specific taxonomy is deleted.
2514 * The dynamic portion of the hook name, `$taxonomy`, refers to the specific
2515 * taxonomy the term belonged to.
2519 * @param int $term Term ID.
2520 * @param int $tt_id Term taxonomy ID.
2521 * @param mixed $deleted_term Copy of the already-deleted term, in the form specified
2522 * by the parent function. {@see WP_Error} otherwise.
2524 do_action( "delete_$taxonomy", $term, $tt_id, $deleted_term );
2530 * Deletes one existing category.
2534 * @param int $cat_ID
2535 * @return mixed Returns true if completes delete action; false if term doesn't exist;
2536 * Zero on attempted deletion of default Category; WP_Error object is also a possibility.
2538 function wp_delete_category( $cat_ID ) {
2539 return wp_delete_term( $cat_ID, 'category' );
2543 * Retrieves the terms associated with the given object(s), in the supplied taxonomies.
2545 * The following information has to do the $args parameter and for what can be
2546 * contained in the string or array of that parameter, if it exists.
2548 * The first argument is called, 'orderby' and has the default value of 'name'.
2549 * The other value that is supported is 'count'.
2551 * The second argument is called, 'order' and has the default value of 'ASC'.
2552 * The only other value that will be acceptable is 'DESC'.
2554 * The final argument supported is called, 'fields' and has the default value of
2555 * 'all'. There are multiple other options that can be used instead. Supported
2556 * values are as follows: 'all', 'ids', 'names', and finally
2557 * 'all_with_object_id'.
2559 * The fields argument also decides what will be returned. If 'all' or
2560 * 'all_with_object_id' is chosen or the default kept intact, then all matching
2561 * terms objects will be returned. If either 'ids' or 'names' is used, then an
2562 * array of all matching term ids or term names will be returned respectively.
2566 * @global wpdb $wpdb WordPress database abstraction object.
2568 * @param int|array $object_ids The ID(s) of the object(s) to retrieve.
2569 * @param string|array $taxonomies The taxonomies to retrieve terms from.
2570 * @param array|string $args Change what is returned
2571 * @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.
2573 function wp_get_object_terms($object_ids, $taxonomies, $args = array()) {
2576 if ( empty( $object_ids ) || empty( $taxonomies ) )
2579 if ( !is_array($taxonomies) )
2580 $taxonomies = array($taxonomies);
2582 foreach ( $taxonomies as $taxonomy ) {
2583 if ( ! taxonomy_exists($taxonomy) )
2584 return new WP_Error('invalid_taxonomy', __('Invalid taxonomy'));
2587 if ( !is_array($object_ids) )
2588 $object_ids = array($object_ids);
2589 $object_ids = array_map('intval', $object_ids);
2591 $defaults = array('orderby' => 'name', 'order' => 'ASC', 'fields' => 'all');
2592 $args = wp_parse_args( $args, $defaults );
2595 if ( count($taxonomies) > 1 ) {
2596 foreach ( $taxonomies as $index => $taxonomy ) {
2597 $t = get_taxonomy($taxonomy);
2598 if ( isset($t->args) && is_array($t->args) && $args != array_merge($args, $t->args) ) {
2599 unset($taxonomies[$index]);
2600 $terms = array_merge($terms, wp_get_object_terms($object_ids, $taxonomy, array_merge($args, $t->args)));
2604 $t = get_taxonomy($taxonomies[0]);
2605 if ( isset($t->args) && is_array($t->args) )
2606 $args = array_merge($args, $t->args);
2609 $orderby = $args['orderby'];
2610 $order = $args['order'];
2611 $fields = $args['fields'];
2613 if ( 'count' == $orderby )
2614 $orderby = 'tt.count';
2615 else if ( 'name' == $orderby )
2616 $orderby = 't.name';
2617 else if ( 'slug' == $orderby )
2618 $orderby = 't.slug';
2619 else if ( 'term_group' == $orderby )
2620 $orderby = 't.term_group';
2621 else if ( 'term_order' == $orderby )
2622 $orderby = 'tr.term_order';
2623 else if ( 'none' == $orderby ) {
2627 $orderby = 't.term_id';
2630 // tt_ids queries can only be none or tr.term_taxonomy_id
2631 if ( ('tt_ids' == $fields) && !empty($orderby) )
2632 $orderby = 'tr.term_taxonomy_id';
2634 if ( !empty($orderby) )
2635 $orderby = "ORDER BY $orderby";
2637 $order = strtoupper( $order );
2638 if ( '' !== $order && ! in_array( $order, array( 'ASC', 'DESC' ) ) )
2641 $taxonomies = "'" . implode("', '", $taxonomies) . "'";
2642 $object_ids = implode(', ', $object_ids);
2645 if ( 'all' == $fields )
2646 $select_this = 't.*, tt.*';
2647 else if ( 'ids' == $fields )
2648 $select_this = 't.term_id';
2649 else if ( 'names' == $fields )
2650 $select_this = 't.name';
2651 else if ( 'slugs' == $fields )
2652 $select_this = 't.slug';
2653 else if ( 'all_with_object_id' == $fields )
2654 $select_this = 't.*, tt.*, tr.object_id';
2656 $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";
2659 if ( 'all' == $fields || 'all_with_object_id' == $fields ) {
2660 $_terms = $wpdb->get_results( $query );
2661 foreach ( $_terms as $key => $term ) {
2662 $_terms[$key] = sanitize_term( $term, $taxonomy, 'raw' );
2664 $terms = array_merge( $terms, $_terms );
2665 update_term_cache( $terms );
2667 } else if ( 'ids' == $fields || 'names' == $fields || 'slugs' == $fields ) {
2668 $_terms = $wpdb->get_col( $query );
2669 $_field = ( 'ids' == $fields ) ? 'term_id' : 'name';
2670 foreach ( $_terms as $key => $term ) {
2671 $_terms[$key] = sanitize_term_field( $_field, $term, $term, $taxonomy, 'raw' );
2673 $terms = array_merge( $terms, $_terms );
2674 } else if ( 'tt_ids' == $fields ) {
2675 $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");
2676 foreach ( $terms as $key => $tt_id ) {
2677 $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.
2683 } elseif ( $objects && 'all_with_object_id' !== $fields ) {
2686 foreach ( $terms as $term ) {
2687 if ( in_array( $term->term_taxonomy_id, $_tt_ids ) ) {
2691 $_tt_ids[] = $term->term_taxonomy_id;
2695 } elseif ( ! $objects ) {
2696 $terms = array_values( array_unique( $terms ) );
2699 * Filter the terms for a given object or objects.
2703 * @param array $terms An array of terms for the given object or objects.
2704 * @param array|int $object_ids Object ID or array of IDs.
2705 * @param array|string $taxonomies A taxonomy or array of taxonomies.
2706 * @param array $args An array of arguments for retrieving terms for
2707 * the given object(s).
2709 return apply_filters( 'wp_get_object_terms', $terms, $object_ids, $taxonomies, $args );
2713 * Add a new term to the database.
2715 * A non-existent term is inserted in the following sequence:
2716 * 1. The term is added to the term table, then related to the taxonomy.
2717 * 2. If everything is correct, several actions are fired.
2718 * 3. The 'term_id_filter' is evaluated.
2719 * 4. The term cache is cleaned.
2720 * 5. Several more actions are fired.
2721 * 6. An array is returned containing the term_id and term_taxonomy_id.
2723 * If the 'slug' argument is not empty, then it is checked to see if the term
2724 * is invalid. If it is not a valid, existing term, it is added and the term_id
2727 * If the taxonomy is hierarchical, and the 'parent' argument is not empty,
2728 * the term is inserted and the term_id will be given.
2731 * If $taxonomy does not exist or $term is empty,
2732 * a WP_Error object will be returned.
2734 * If the term already exists on the same hierarchical level,
2735 * or the term slug and name are not unique, a WP_Error object will be returned.
2737 * @global wpdb $wpdb WordPress database abstraction object.
2741 * @param string $term The term to add or update.
2742 * @param string $taxonomy The taxonomy to which to add the term.
2743 * @param array|string $args {
2744 * Optional. Array or string of arguments for inserting a term.
2746 * @type string $alias_of Slug of the term to make this term an alias of.
2747 * Default empty string. Accepts a term slug.
2748 * @type string $description The term description. Default empty string.
2749 * @type int $parent The id of the parent term. Default 0.
2750 * @type string $slug The term slug to use. Default empty string.
2752 * @return array|WP_Error An array containing the `term_id` and `term_taxonomy_id`,
2753 * {@see WP_Error} otherwise.
2755 function wp_insert_term( $term, $taxonomy, $args = array() ) {
2758 if ( ! taxonomy_exists($taxonomy) ) {
2759 return new WP_Error('invalid_taxonomy', __('Invalid taxonomy'));
2762 * Filter a term before it is sanitized and inserted into the database.
2766 * @param string $term The term to add or update.
2767 * @param string $taxonomy Taxonomy slug.
2769 $term = apply_filters( 'pre_insert_term', $term, $taxonomy );
2770 if ( is_wp_error( $term ) ) {
2773 if ( is_int($term) && 0 == $term ) {
2774 return new WP_Error('invalid_term_id', __('Invalid term ID'));
2776 if ( '' == trim($term) ) {
2777 return new WP_Error('empty_term_name', __('A name is required for this term'));
2779 $defaults = array( 'alias_of' => '', 'description' => '', 'parent' => 0, 'slug' => '');
2780 $args = wp_parse_args( $args, $defaults );
2782 if ( $args['parent'] > 0 && ! term_exists( (int) $args['parent'] ) ) {
2783 return new WP_Error( 'missing_parent', __( 'Parent term does not exist.' ) );
2785 $args['name'] = $term;
2786 $args['taxonomy'] = $taxonomy;
2787 $args = sanitize_term($args, $taxonomy, 'db');
2789 // expected_slashed ($name)
2790 $name = wp_unslash( $args['name'] );
2791 $description = wp_unslash( $args['description'] );
2792 $parent = (int) $args['parent'];
2794 $slug_provided = ! empty( $args['slug'] );
2795 if ( ! $slug_provided ) {
2796 $_name = trim( $name );
2797 $existing_term = get_term_by( 'name', $_name, $taxonomy );
2798 if ( $existing_term ) {
2799 $slug = $existing_term->slug;
2801 $slug = sanitize_title( $name );
2804 $slug = $args['slug'];
2808 if ( $args['alias_of'] ) {
2809 $alias = get_term_by( 'slug', $args['alias_of'], $taxonomy );
2810 if ( ! empty( $alias->term_group ) ) {
2811 // The alias we want is already in a group, so let's use that one.
2812 $term_group = $alias->term_group;
2813 } else if ( ! empty( $alias->term_id ) ) {
2815 * The alias is not in a group, so we create a new one
2816 * and add the alias to it.
2818 $term_group = $wpdb->get_var("SELECT MAX(term_group) FROM $wpdb->terms") + 1;
2820 wp_update_term( $alias->term_id, $taxonomy, array(
2821 'term_group' => $term_group,
2826 // Terms with duplicate names are not allowed at the same level of a taxonomy hierarchy.
2827 if ( $exists = term_exists( $slug, $taxonomy ) ) {
2828 $existing_term = get_term( $exists['term_id'], $taxonomy );
2830 if ( $name === $existing_term->name ) {
2832 if ( is_taxonomy_hierarchical( $taxonomy ) ) {
2833 $siblings = get_terms( $taxonomy, array( 'fields' => 'names', 'get' => 'all', 'parent' => $parent ) );
2834 if ( in_array( $name, $siblings ) ) {
2835 return new WP_Error( 'term_exists', __( 'A term with the name and slug already exists with this parent.' ), $exists['term_id'] );
2839 return new WP_Error( 'term_exists', __( 'A term with the name and slug already exists in this taxonomy.' ), $exists['term_id'] );
2844 $slug = wp_unique_term_slug( $slug, (object) $args );
2846 if ( false === $wpdb->insert( $wpdb->terms, compact( 'name', 'slug', 'term_group' ) ) ) {
2847 return new WP_Error( 'db_insert_error', __( 'Could not insert term into the database' ), $wpdb->last_error );
2850 $term_id = (int) $wpdb->insert_id;
2852 // Seems unreachable, However, Is used in the case that a term name is provided, which sanitizes to an empty string.
2853 if ( empty($slug) ) {
2854 $slug = sanitize_title($slug, $term_id);
2856 /** This action is documented in wp-includes/taxonomy.php */
2857 do_action( 'edit_terms', $term_id, $taxonomy );
2858 $wpdb->update( $wpdb->terms, compact( 'slug' ), compact( 'term_id' ) );
2860 /** This action is documented in wp-includes/taxonomy.php */
2861 do_action( 'edited_terms', $term_id, $taxonomy );
2864 $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 ) );
2866 if ( !empty($tt_id) ) {
2867 return array('term_id' => $term_id, 'term_taxonomy_id' => $tt_id);
2869 $wpdb->insert( $wpdb->term_taxonomy, compact( 'term_id', 'taxonomy', 'description', 'parent') + array( 'count' => 0 ) );
2870 $tt_id = (int) $wpdb->insert_id;
2873 * Sanity check: if we just created a term with the same parent + taxonomy + slug but a higher term_id than
2874 * an existing term, then we have unwittingly created a duplicate term. Delete the dupe, and use the term_id
2875 * and term_taxonomy_id of the older term instead. Then return out of the function so that the "create" hooks
2878 $duplicate_term = $wpdb->get_row( $wpdb->prepare( "SELECT t.term_id, tt.term_taxonomy_id FROM $wpdb->terms t INNER JOIN $wpdb->term_taxonomy tt ON ( tt.term_id = t.term_id ) WHERE t.slug = %s AND tt.parent = %d AND tt.taxonomy = %s AND t.term_id < %d AND tt.term_taxonomy_id != %d", $slug, $parent, $taxonomy, $term_id, $tt_id ) );
2879 if ( $duplicate_term ) {
2880 $wpdb->delete( $wpdb->terms, array( 'term_id' => $term_id ) );
2881 $wpdb->delete( $wpdb->term_taxonomy, array( 'term_taxonomy_id' => $tt_id ) );
2883 $term_id = (int) $duplicate_term->term_id;
2884 $tt_id = (int) $duplicate_term->term_taxonomy_id;
2886 clean_term_cache( $term_id, $taxonomy );
2887 return array( 'term_id' => $term_id, 'term_taxonomy_id' => $tt_id );
2891 * Fires immediately after a new term is created, before the term cache is cleaned.
2895 * @param int $term_id Term ID.
2896 * @param int $tt_id Term taxonomy ID.
2897 * @param string $taxonomy Taxonomy slug.
2899 do_action( "create_term", $term_id, $tt_id, $taxonomy );
2902 * Fires after a new term is created for a specific taxonomy.
2904 * The dynamic portion of the hook name, `$taxonomy`, refers
2905 * to the slug of the taxonomy the term was created for.
2909 * @param int $term_id Term ID.
2910 * @param int $tt_id Term taxonomy ID.
2912 do_action( "create_$taxonomy", $term_id, $tt_id );
2915 * Filter the term ID after a new term is created.
2919 * @param int $term_id Term ID.
2920 * @param int $tt_id Taxonomy term ID.
2922 $term_id = apply_filters( 'term_id_filter', $term_id, $tt_id );
2924 clean_term_cache($term_id, $taxonomy);
2927 * Fires after a new term is created, and after the term cache has been cleaned.
2931 do_action( "created_term", $term_id, $tt_id, $taxonomy );
2934 * Fires after a new term in a specific taxonomy is created, and after the term
2935 * cache has been cleaned.
2939 * @param int $term_id Term ID.
2940 * @param int $tt_id Term taxonomy ID.
2942 do_action( "created_$taxonomy", $term_id, $tt_id );
2944 return array('term_id' => $term_id, 'term_taxonomy_id' => $tt_id);
2948 * Create Term and Taxonomy Relationships.
2950 * Relates an object (post, link etc) to a term and taxonomy type. Creates the
2951 * term and taxonomy relationship if it doesn't already exist. Creates a term if
2952 * it doesn't exist (using the slug).
2954 * A relationship means that the term is grouped in or belongs to the taxonomy.
2955 * A term has no meaning until it is given context by defining which taxonomy it
2960 * @param int $object_id The object to relate to.
2961 * @param array|int|string $terms A single term slug, single term id, or array of either term slugs or ids.
2962 * Will replace all existing related terms in this taxonomy.
2963 * @param array|string $taxonomy The context in which to relate the term to the object.
2964 * @param bool $append Optional. If false will delete difference of terms. Default false.
2965 * @return array|WP_Error Affected Term IDs.
2967 function wp_set_object_terms( $object_id, $terms, $taxonomy, $append = false ) {
2970 $object_id = (int) $object_id;
2972 if ( ! taxonomy_exists($taxonomy) )
2973 return new WP_Error('invalid_taxonomy', __('Invalid taxonomy'));
2975 if ( !is_array($terms) )
2976 $terms = array($terms);
2979 $old_tt_ids = wp_get_object_terms($object_id, $taxonomy, array('fields' => 'tt_ids', 'orderby' => 'none'));
2981 $old_tt_ids = array();
2984 $term_ids = array();
2985 $new_tt_ids = array();
2987 foreach ( (array) $terms as $term) {
2988 if ( !strlen(trim($term)) )
2991 if ( !$term_info = term_exists($term, $taxonomy) ) {
2992 // Skip if a non-existent term ID is passed.
2993 if ( is_int($term) )
2995 $term_info = wp_insert_term($term, $taxonomy);
2997 if ( is_wp_error($term_info) )
2999 $term_ids[] = $term_info['term_id'];
3000 $tt_id = $term_info['term_taxonomy_id'];
3003 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 ) ) )
3007 * Fires immediately before an object-term relationship is added.
3011 * @param int $object_id Object ID.
3012 * @param int $tt_id Term taxonomy ID.
3014 do_action( 'add_term_relationship', $object_id, $tt_id );
3015 $wpdb->insert( $wpdb->term_relationships, array( 'object_id' => $object_id, 'term_taxonomy_id' => $tt_id ) );
3018 * Fires immediately after an object-term relationship is added.
3022 * @param int $object_id Object ID.
3023 * @param int $tt_id Term taxonomy ID.
3025 do_action( 'added_term_relationship', $object_id, $tt_id );
3026 $new_tt_ids[] = $tt_id;
3030 wp_update_term_count( $new_tt_ids, $taxonomy );
3033 $delete_tt_ids = array_diff( $old_tt_ids, $tt_ids );
3035 if ( $delete_tt_ids ) {
3036 $in_delete_tt_ids = "'" . implode( "', '", $delete_tt_ids ) . "'";
3037 $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 ) );
3038 $delete_term_ids = array_map( 'intval', $delete_term_ids );
3040 $remove = wp_remove_object_terms( $object_id, $delete_term_ids, $taxonomy );
3041 if ( is_wp_error( $remove ) ) {
3047 $t = get_taxonomy($taxonomy);
3048 if ( ! $append && isset($t->sort) && $t->sort ) {
3051 $final_tt_ids = wp_get_object_terms($object_id, $taxonomy, array('fields' => 'tt_ids'));
3052 foreach ( $tt_ids as $tt_id )
3053 if ( in_array($tt_id, $final_tt_ids) )
3054 $values[] = $wpdb->prepare( "(%d, %d, %d)", $object_id, $tt_id, ++$term_order);
3056 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)" ) )
3057 return new WP_Error( 'db_insert_error', __( 'Could not insert term relationship into the database' ), $wpdb->last_error );
3060 wp_cache_delete( $object_id, $taxonomy . '_relationships' );
3063 * Fires after an object's terms have been set.
3067 * @param int $object_id Object ID.
3068 * @param array $terms An array of object terms.
3069 * @param array $tt_ids An array of term taxonomy IDs.
3070 * @param string $taxonomy Taxonomy slug.
3071 * @param bool $append Whether to append new terms to the old terms.
3072 * @param array $old_tt_ids Old array of term taxonomy IDs.
3074 do_action( 'set_object_terms', $object_id, $terms, $tt_ids, $taxonomy, $append, $old_tt_ids );
3079 * Add term(s) associated with a given object.
3083 * @param int $object_id The ID of the object to which the terms will be added.
3084 * @param array|int|string $terms The slug(s) or ID(s) of the term(s) to add.
3085 * @param array|string $taxonomy Taxonomy name.
3086 * @return array|WP_Error Affected Term IDs
3088 function wp_add_object_terms( $object_id, $terms, $taxonomy ) {
3089 return wp_set_object_terms( $object_id, $terms, $taxonomy, true );
3093 * Remove term(s) associated with a given object.
3097 * @global wpdb $wpdb WordPress database abstraction object.
3099 * @param int $object_id The ID of the object from which the terms will be removed.
3100 * @param array|int|string $terms The slug(s) or ID(s) of the term(s) to remove.
3101 * @param array|string $taxonomy Taxonomy name.
3102 * @return bool|WP_Error True on success, false or WP_Error on failure.
3104 function wp_remove_object_terms( $object_id, $terms, $taxonomy ) {
3107 $object_id = (int) $object_id;
3109 if ( ! taxonomy_exists( $taxonomy ) ) {
3110 return new WP_Error( 'invalid_taxonomy', __( 'Invalid Taxonomy' ) );
3113 if ( ! is_array( $terms ) ) {
3114 $terms = array( $terms );
3119 foreach ( (array) $terms as $term ) {
3120 if ( ! strlen( trim( $term ) ) ) {
3124 if ( ! $term_info = term_exists( $term, $taxonomy ) ) {
3125 // Skip if a non-existent term ID is passed.
3126 if ( is_int( $term ) ) {
3131 if ( is_wp_error( $term_info ) ) {
3135 $tt_ids[] = $term_info['term_taxonomy_id'];
3139 $in_tt_ids = "'" . implode( "', '", $tt_ids ) . "'";
3142 * Fires immediately before an object-term relationship is deleted.
3146 * @param int $object_id Object ID.
3147 * @param array $tt_ids An array of term taxonomy IDs.
3149 do_action( 'delete_term_relationships', $object_id, $tt_ids );
3150 $deleted = $wpdb->query( $wpdb->prepare( "DELETE FROM $wpdb->term_relationships WHERE object_id = %d AND term_taxonomy_id IN ($in_tt_ids)", $object_id ) );
3153 * Fires immediately after an object-term relationship is deleted.
3157 * @param int $object_id Object ID.
3158 * @param array $tt_ids An array of term taxonomy IDs.
3160 do_action( 'deleted_term_relationships', $object_id, $tt_ids );
3161 wp_update_term_count( $tt_ids, $taxonomy );
3163 return (bool) $deleted;
3170 * Will make slug unique, if it isn't already.
3172 * The $slug has to be unique global to every taxonomy, meaning that one
3173 * taxonomy term can't have a matching slug with another taxonomy term. Each
3174 * slug has to be globally unique for every taxonomy.
3176 * The way this works is that if the taxonomy that the term belongs to is
3177 * hierarchical and has a parent, it will append that parent to the $slug.
3179 * If that still doesn't return an unique slug, then it try to append a number
3180 * until it finds a number that is truly unique.
3182 * The only purpose for $term is for appending a parent, if one exists.
3186 * @global wpdb $wpdb WordPress database abstraction object.
3188 * @param string $slug The string that will be tried for a unique slug
3189 * @param object $term The term object that the $slug will belong too
3190 * @return string Will return a true unique slug.
3192 function wp_unique_term_slug($slug, $term) {
3195 if ( ! term_exists( $slug ) )
3198 // As of 4.1, duplicate slugs are allowed as long as they're in different taxonomies.
3199 if ( get_option( 'db_version' ) >= 30133 && ! get_term_by( 'slug', $slug, $term->taxonomy ) ) {
3203 // If the taxonomy supports hierarchy and the term has a parent, make the slug unique
3204 // by incorporating parent slugs.
3205 if ( is_taxonomy_hierarchical($term->taxonomy) && !empty($term->parent) ) {
3206 $the_parent = $term->parent;
3207 while ( ! empty($the_parent) ) {
3208 $parent_term = get_term($the_parent, $term->taxonomy);
3209 if ( is_wp_error($parent_term) || empty($parent_term) )
3211 $slug .= '-' . $parent_term->slug;
3212 if ( ! term_exists( $slug ) )
3215 if ( empty($parent_term->parent) )
3217 $the_parent = $parent_term->parent;
3221 // If we didn't get a unique slug, try appending a number to make it unique.
3222 if ( ! empty( $term->term_id ) )
3223 $query = $wpdb->prepare( "SELECT slug FROM $wpdb->terms WHERE slug = %s AND term_id != %d", $slug, $term->term_id );
3225 $query = $wpdb->prepare( "SELECT slug FROM $wpdb->terms WHERE slug = %s", $slug );
3227 if ( $wpdb->get_var( $query ) ) {
3230 $alt_slug = $slug . "-$num";
3232 $slug_check = $wpdb->get_var( $wpdb->prepare( "SELECT slug FROM $wpdb->terms WHERE slug = %s", $alt_slug ) );
3233 } while ( $slug_check );
3241 * Update term based on arguments provided.
3243 * The $args will indiscriminately override all values with the same field name.
3244 * Care must be taken to not override important information need to update or
3245 * update will fail (or perhaps create a new term, neither would be acceptable).
3247 * Defaults will set 'alias_of', 'description', 'parent', and 'slug' if not
3248 * defined in $args already.
3250 * 'alias_of' will create a term group, if it doesn't already exist, and update
3253 * If the 'slug' argument in $args is missing, then the 'name' in $args will be
3254 * used. It should also be noted that if you set 'slug' and it isn't unique then
3255 * a WP_Error will be passed back. If you don't pass any slug, then a unique one
3256 * will be created for you.
3258 * For what can be overrode in $args, check the term scheme can contain and stay
3259 * away from the term keys.
3263 * @global wpdb $wpdb WordPress database abstraction object.
3265 * @param int $term_id The ID of the term
3266 * @param string $taxonomy The context in which to relate the term to the object.
3267 * @param array|string $args Overwrite term field values
3268 * @return array|WP_Error Returns Term ID and Taxonomy Term ID
3270 function wp_update_term( $term_id, $taxonomy, $args = array() ) {
3273 if ( ! taxonomy_exists($taxonomy) )
3274 return new WP_Error('invalid_taxonomy', __('Invalid taxonomy'));
3276 $term_id = (int) $term_id;
3278 // First, get all of the original args
3279 $term = get_term ($term_id, $taxonomy, ARRAY_A);
3281 if ( is_wp_error( $term ) )
3284 // Escape data pulled from DB.
3285 $term = wp_slash($term);
3287 // Merge old and new args with new args overwriting old ones.
3288 $args = array_merge($term, $args);
3290 $defaults = array( 'alias_of' => '', 'description' => '', 'parent' => 0, 'slug' => '');
3291 $args = wp_parse_args($args, $defaults);
3292 $args = sanitize_term($args, $taxonomy, 'db');
3293 $parsed_args = $args;
3295 // expected_slashed ($name)
3296 $name = wp_unslash( $args['name'] );
3297 $description = wp_unslash( $args['description'] );
3299 $parsed_args['name'] = $name;
3300 $parsed_args['description'] = $description;
3302 if ( '' == trim($name) )
3303 return new WP_Error('empty_term_name', __('A name is required for this term'));
3305 if ( $parsed_args['parent'] > 0 && ! term_exists( (int) $parsed_args['parent'] ) ) {
3306 return new WP_Error( 'missing_parent', __( 'Parent term does not exist.' ) );
3309 $empty_slug = false;
3310 if ( empty( $args['slug'] ) ) {
3312 $slug = sanitize_title($name);
3314 $slug = $args['slug'];
3317 $parsed_args['slug'] = $slug;
3319 $term_group = isset( $parsed_args['term_group'] ) ? $parsed_args['term_group'] : 0;
3320 if ( $args['alias_of'] ) {
3321 $alias = get_term_by( 'slug', $args['alias_of'], $taxonomy );
3322 if ( ! empty( $alias->term_group ) ) {
3323 // The alias we want is already in a group, so let's use that one.
3324 $term_group = $alias->term_group;
3325 } else if ( ! empty( $alias->term_id ) ) {
3327 * The alias is not in a group, so we create a new one
3328 * and add the alias to it.
3330 $term_group = $wpdb->get_var("SELECT MAX(term_group) FROM $wpdb->terms") + 1;
3332 wp_update_term( $alias->term_id, $taxonomy, array(
3333 'term_group' => $term_group,
3337 $parsed_args['term_group'] = $term_group;
3341 * Filter the term parent.
3343 * Hook to this filter to see if it will cause a hierarchy loop.
3347 * @param int $parent ID of the parent term.
3348 * @param int $term_id Term ID.
3349 * @param string $taxonomy Taxonomy slug.
3350 * @param array $parsed_args An array of potentially altered update arguments for the given term.
3351 * @param array $args An array of update arguments for the given term.
3353 $parent = apply_filters( 'wp_update_term_parent', $args['parent'], $term_id, $taxonomy, $parsed_args, $args );
3355 // Check for duplicate slug
3356 $id = $wpdb->get_var( $wpdb->prepare( "SELECT term_id FROM $wpdb->terms WHERE slug = %s", $slug ) );
3357 if ( $id && ($id != $term_id) ) {
3358 // If an empty slug was passed or the parent changed, reset the slug to something unique.
3360 if ( $empty_slug || ( $parent != $term['parent']) )
3361 $slug = wp_unique_term_slug($slug, (object) $args);
3363 return new WP_Error('duplicate_term_slug', sprintf(__('The slug “%s” is already in use by another term'), $slug));
3366 $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) );
3369 * Fires immediately before the given terms are edited.
3373 * @param int $term_id Term ID.
3374 * @param string $taxonomy Taxonomy slug.
3376 do_action( 'edit_terms', $term_id, $taxonomy );
3377 $wpdb->update($wpdb->terms, compact( 'name', 'slug', 'term_group' ), compact( 'term_id' ) );
3378 if ( empty($slug) ) {
3379 $slug = sanitize_title($name, $term_id);
3380 $wpdb->update( $wpdb->terms, compact( 'slug' ), compact( 'term_id' ) );
3384 * Fires immediately after the given terms are edited.
3388 * @param int $term_id Term ID
3389 * @param string $taxonomy Taxonomy slug.
3391 do_action( 'edited_terms', $term_id, $taxonomy );
3394 * Fires immediate before a term-taxonomy relationship is updated.
3398 * @param int $tt_id Term taxonomy ID.
3399 * @param string $taxonomy Taxonomy slug.
3401 do_action( 'edit_term_taxonomy', $tt_id, $taxonomy );
3402 $wpdb->update( $wpdb->term_taxonomy, compact( 'term_id', 'taxonomy', 'description', 'parent' ), array( 'term_taxonomy_id' => $tt_id ) );
3405 * Fires immediately after a term-taxonomy relationship is updated.
3409 * @param int $tt_id Term taxonomy ID.
3410 * @param string $taxonomy Taxonomy slug.
3412 do_action( 'edited_term_taxonomy', $tt_id, $taxonomy );
3414 // Clean the relationship caches for all object types using this term
3415 $objects = $wpdb->get_col( $wpdb->prepare( "SELECT object_id FROM $wpdb->term_relationships WHERE term_taxonomy_id = %d", $tt_id ) );
3416 $tax_object = get_taxonomy( $taxonomy );
3417 foreach ( $tax_object->object_type as $object_type ) {
3418 clean_object_term_cache( $objects, $object_type );
3422 * Fires after a term has been updated, but before the term cache has been cleaned.
3426 * @param int $term_id Term ID.
3427 * @param int $tt_id Term taxonomy ID.
3428 * @param string $taxonomy Taxonomy slug.
3430 do_action( "edit_term", $term_id, $tt_id, $taxonomy );
3433 * Fires after a term in a specific taxonomy has been updated, but before the term
3434 * cache has been cleaned.
3436 * The dynamic portion of the hook name, `$taxonomy`, refers to the taxonomy slug.
3440 * @param int $term_id Term ID.
3441 * @param int $tt_id Term taxonomy ID.
3443 do_action( "edit_$taxonomy", $term_id, $tt_id );
3445 /** This filter is documented in wp-includes/taxonomy.php */
3446 $term_id = apply_filters( 'term_id_filter', $term_id, $tt_id );
3448 clean_term_cache($term_id, $taxonomy);
3451 * Fires after a term has been updated, and the term cache has been cleaned.
3455 * @param int $term_id Term ID.
3456 * @param int $tt_id Term taxonomy ID.
3457 * @param string $taxonomy Taxonomy slug.
3459 do_action( "edited_term", $term_id, $tt_id, $taxonomy );
3462 * Fires after a term for a specific taxonomy has been updated, and the term
3463 * cache has been cleaned.
3465 * The dynamic portion of the hook name, `$taxonomy`, refers to the taxonomy slug.
3469 * @param int $term_id Term ID.
3470 * @param int $tt_id Term taxonomy ID.
3472 do_action( "edited_$taxonomy", $term_id, $tt_id );
3474 return array('term_id' => $term_id, 'term_taxonomy_id' => $tt_id);
3478 * Enable or disable term counting.
3482 * @param bool $defer Optional. Enable if true, disable if false.
3483 * @return bool Whether term counting is enabled or disabled.
3485 function wp_defer_term_counting($defer=null) {
3486 static $_defer = false;
3488 if ( is_bool($defer) ) {
3490 // flush any deferred counts
3492 wp_update_term_count( null, null, true );
3499 * Updates the amount of terms in taxonomy.
3501 * If there is a taxonomy callback applied, then it will be called for updating
3504 * The default action is to count what the amount of terms have the relationship
3505 * of term ID. Once that is done, then update the database.
3509 * @global wpdb $wpdb WordPress database abstraction object.
3511 * @param int|array $terms The term_taxonomy_id of the terms
3512 * @param string $taxonomy The context of the term.
3513 * @return bool If no terms will return false, and if successful will return true.
3515 function wp_update_term_count( $terms, $taxonomy, $do_deferred=false ) {
3516 static $_deferred = array();
3518 if ( $do_deferred ) {
3519 foreach ( (array) array_keys($_deferred) as $tax ) {
3520 wp_update_term_count_now( $_deferred[$tax], $tax );
3521 unset( $_deferred[$tax] );
3525 if ( empty($terms) )
3528 if ( !is_array($terms) )
3529 $terms = array($terms);
3531 if ( wp_defer_term_counting() ) {
3532 if ( !isset($_deferred[$taxonomy]) )
3533 $_deferred[$taxonomy] = array();
3534 $_deferred[$taxonomy] = array_unique( array_merge($_deferred[$taxonomy], $terms) );
3538 return wp_update_term_count_now( $terms, $taxonomy );
3542 * Perform term count update immediately.
3546 * @param array $terms The term_taxonomy_id of terms to update.
3547 * @param string $taxonomy The context of the term.
3548 * @return bool Always true when complete.
3550 function wp_update_term_count_now( $terms, $taxonomy ) {
3551 $terms = array_map('intval', $terms);
3553 $taxonomy = get_taxonomy($taxonomy);
3554 if ( !empty($taxonomy->update_count_callback) ) {
3555 call_user_func($taxonomy->update_count_callback, $terms, $taxonomy);
3557 $object_types = (array) $taxonomy->object_type;
3558 foreach ( $object_types as &$object_type ) {
3559 if ( 0 === strpos( $object_type, 'attachment:' ) )
3560 list( $object_type ) = explode( ':', $object_type );
3563 if ( $object_types == array_filter( $object_types, 'post_type_exists' ) ) {
3564 // Only post types are attached to this taxonomy
3565 _update_post_term_count( $terms, $taxonomy );
3567 // Default count updater
3568 _update_generic_term_count( $terms, $taxonomy );
3572 clean_term_cache($terms, '', false);
3582 * Removes the taxonomy relationship to terms from the cache.
3584 * Will remove the entire taxonomy relationship containing term $object_id. The
3585 * term IDs have to exist within the taxonomy $object_type for the deletion to
3590 * @see get_object_taxonomies() for more on $object_type
3592 * @param int|array $object_ids Single or list of term object ID(s)
3593 * @param array|string $object_type The taxonomy object type
3595 function clean_object_term_cache($object_ids, $object_type) {
3596 if ( !is_array($object_ids) )
3597 $object_ids = array($object_ids);
3599 $taxonomies = get_object_taxonomies( $object_type );
3601 foreach ( $object_ids as $id ) {
3602 foreach ( $taxonomies as $taxonomy ) {
3603 wp_cache_delete($id, "{$taxonomy}_relationships");
3608 * Fires after the object term cache has been cleaned.
3612 * @param array $object_ids An array of object IDs.
3613 * @param string $objet_type Object type.
3615 do_action( 'clean_object_term_cache', $object_ids, $object_type );
3619 * Will remove all of the term ids from the cache.
3623 * @global wpdb $wpdb WordPress database abstraction object.
3625 * @param int|array $ids Single or list of Term IDs
3626 * @param string $taxonomy Can be empty and will assume tt_ids, else will use for context.
3627 * @param bool $clean_taxonomy Whether to clean taxonomy wide caches (true), or just individual term object caches (false). Default is true.
3629 function clean_term_cache($ids, $taxonomy = '', $clean_taxonomy = true) {
3632 if ( !is_array($ids) )
3635 $taxonomies = array();
3636 // If no taxonomy, assume tt_ids.
3637 if ( empty($taxonomy) ) {
3638 $tt_ids = array_map('intval', $ids);
3639 $tt_ids = implode(', ', $tt_ids);
3640 $terms = $wpdb->get_results("SELECT term_id, taxonomy FROM $wpdb->term_taxonomy WHERE term_taxonomy_id IN ($tt_ids)");
3642 foreach ( (array) $terms as $term ) {
3643 $taxonomies[] = $term->taxonomy;
3644 $ids[] = $term->term_id;
3645 wp_cache_delete($term->term_id, $term->taxonomy);
3647 $taxonomies = array_unique($taxonomies);
3649 $taxonomies = array($taxonomy);
3650 foreach ( $taxonomies as $taxonomy ) {
3651 foreach ( $ids as $id ) {
3652 wp_cache_delete($id, $taxonomy);
3657 foreach ( $taxonomies as $taxonomy ) {
3658 if ( $clean_taxonomy ) {
3659 wp_cache_delete('all_ids', $taxonomy);
3660 wp_cache_delete('get', $taxonomy);
3661 delete_option("{$taxonomy}_children");
3662 // Regenerate {$taxonomy}_children
3663 _get_term_hierarchy($taxonomy);
3667 * Fires once after each taxonomy's term cache has been cleaned.
3671 * @param array $ids An array of term IDs.
3672 * @param string $taxonomy Taxonomy slug.
3674 do_action( 'clean_term_cache', $ids, $taxonomy );
3677 wp_cache_set( 'last_changed', microtime(), 'terms' );
3681 * Retrieves the taxonomy relationship to the term object id.
3685 * @param int|array $id Term object ID
3686 * @param string $taxonomy Taxonomy Name
3687 * @return bool|array Empty array if $terms found, but not $taxonomy. False if nothing is in cache for $taxonomy and $id.
3689 function get_object_term_cache($id, $taxonomy) {
3690 $cache = wp_cache_get($id, "{$taxonomy}_relationships");
3695 * Updates the cache for Term ID(s).
3697 * Will only update the cache for terms not already cached.
3699 * The $object_ids expects that the ids be separated by commas, if it is a
3702 * It should be noted that update_object_term_cache() is very time extensive. It
3703 * is advised that the function is not called very often or at least not for a
3704 * lot of terms that exist in a lot of taxonomies. The amount of time increases
3705 * for each term and it also increases for each taxonomy the term belongs to.
3709 * @param string|array $object_ids Single or list of term object ID(s)
3710 * @param array|string $object_type The taxonomy object type
3711 * @return null|false Null value is given with empty $object_ids. False if
3713 function update_object_term_cache($object_ids, $object_type) {
3714 if ( empty($object_ids) )
3717 if ( !is_array($object_ids) )
3718 $object_ids = explode(',', $object_ids);
3720 $object_ids = array_map('intval', $object_ids);
3722 $taxonomies = get_object_taxonomies($object_type);
3725 foreach ( (array) $object_ids as $id ) {
3726 foreach ( $taxonomies as $taxonomy ) {
3727 if ( false === wp_cache_get($id, "{$taxonomy}_relationships") ) {
3734 if ( empty( $ids ) )
3737 $terms = wp_get_object_terms($ids, $taxonomies, array('fields' => 'all_with_object_id'));
3739 $object_terms = array();
3740 foreach ( (array) $terms as $term )
3741 $object_terms[$term->object_id][$term->taxonomy][$term->term_id] = $term;
3743 foreach ( $ids as $id ) {
3744 foreach ( $taxonomies as $taxonomy ) {
3745 if ( ! isset($object_terms[$id][$taxonomy]) ) {
3746 if ( !isset($object_terms[$id]) )
3747 $object_terms[$id] = array();
3748 $object_terms[$id][$taxonomy] = array();
3753 foreach ( $object_terms as $id => $value ) {
3754 foreach ( $value as $taxonomy => $terms ) {
3755 wp_cache_add( $id, $terms, "{$taxonomy}_relationships" );
3761 * Updates Terms to Taxonomy in cache.
3765 * @param array $terms List of Term objects to change
3766 * @param string $taxonomy Optional. Update Term to this taxonomy in cache
3768 function update_term_cache($terms, $taxonomy = '') {
3769 foreach ( (array) $terms as $term ) {
3770 $term_taxonomy = $taxonomy;
3771 if ( empty($term_taxonomy) )
3772 $term_taxonomy = $term->taxonomy;
3774 wp_cache_add( $term->term_id, $term, $term_taxonomy );
3783 * Retrieves children of taxonomy as Term IDs.
3788 * @param string $taxonomy Taxonomy Name
3789 * @return array Empty if $taxonomy isn't hierarchical or returns children as Term IDs.
3791 function _get_term_hierarchy($taxonomy) {
3792 if ( !is_taxonomy_hierarchical($taxonomy) )
3794 $children = get_option("{$taxonomy}_children");
3796 if ( is_array($children) )
3798 $children = array();
3799 $terms = get_terms($taxonomy, array('get' => 'all', 'orderby' => 'id', 'fields' => 'id=>parent'));
3800 foreach ( $terms as $term_id => $parent ) {
3802 $children[$parent][] = $term_id;
3804 update_option("{$taxonomy}_children", $children);
3810 * Get the subset of $terms that are descendants of $term_id.
3812 * If $terms is an array of objects, then _get_term_children returns an array of objects.
3813 * If $terms is an array of IDs, then _get_term_children returns an array of IDs.
3818 * @param int $term_id The ancestor term: all returned terms should be descendants of $term_id.
3819 * @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.
3820 * @param string $taxonomy The taxonomy which determines the hierarchy of the terms.
3821 * @return array The subset of $terms that are descendants of $term_id.
3823 function _get_term_children($term_id, $terms, $taxonomy) {
3824 $empty_array = array();
3825 if ( empty($terms) )
3826 return $empty_array;
3828 $term_list = array();
3829 $has_children = _get_term_hierarchy($taxonomy);
3831 if ( ( 0 != $term_id ) && ! isset($has_children[$term_id]) )
3832 return $empty_array;
3834 foreach ( (array) $terms as $term ) {
3836 if ( !is_object($term) ) {
3837 $term = get_term($term, $taxonomy);
3838 if ( is_wp_error( $term ) )
3843 if ( $term->term_id == $term_id ) {
3847 if ( $term->parent == $term_id ) {
3849 $term_list[] = $term->term_id;
3851 $term_list[] = $term;
3853 if ( !isset($has_children[$term->term_id]) )
3856 if ( $children = _get_term_children($term->term_id, $terms, $taxonomy) )
3857 $term_list = array_merge($term_list, $children);
3865 * Add count of children to parent count.
3867 * Recalculates term counts by including items from child terms. Assumes all
3868 * relevant children are already in the $terms argument.
3873 * @global wpdb $wpdb WordPress database abstraction object.
3875 * @param array $terms List of Term IDs
3876 * @param string $taxonomy Term Context
3877 * @return null Will break from function if conditions are not met.
3879 function _pad_term_counts(&$terms, $taxonomy) {
3882 // This function only works for hierarchical taxonomies like post categories.
3883 if ( !is_taxonomy_hierarchical( $taxonomy ) )
3886 $term_hier = _get_term_hierarchy($taxonomy);
3888 if ( empty($term_hier) )
3891 $term_items = array();
3893 foreach ( (array) $terms as $key => $term ) {
3894 $terms_by_id[$term->term_id] = & $terms[$key];
3895 $term_ids[$term->term_taxonomy_id] = $term->term_id;
3898 // Get the object and term ids and stick them in a lookup table
3899 $tax_obj = get_taxonomy($taxonomy);
3900 $object_types = esc_sql($tax_obj->object_type);
3901 $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'");
3902 foreach ( $results as $row ) {
3903 $id = $term_ids[$row->term_taxonomy_id];
3904 $term_items[$id][$row->object_id] = isset($term_items[$id][$row->object_id]) ? ++$term_items[$id][$row->object_id] : 1;
3907 // Touch every ancestor's lookup row for each post in each term
3908 foreach ( $term_ids as $term_id ) {
3910 while ( !empty( $terms_by_id[$child] ) && $parent = $terms_by_id[$child]->parent ) {
3911 if ( !empty( $term_items[$term_id] ) )
3912 foreach ( $term_items[$term_id] as $item_id => $touches ) {
3913 $term_items[$parent][$item_id] = isset($term_items[$parent][$item_id]) ? ++$term_items[$parent][$item_id]: 1;
3919 // Transfer the touched cells
3920 foreach ( (array) $term_items as $id => $items )
3921 if ( isset($terms_by_id[$id]) )
3922 $terms_by_id[$id]->count = count($items);
3926 // Default callbacks
3930 * Will update term count based on object types of the current taxonomy.
3932 * Private function for the default callback for post_tag and category
3938 * @global wpdb $wpdb WordPress database abstraction object.
3940 * @param array $terms List of Term taxonomy IDs
3941 * @param object $taxonomy Current taxonomy object of terms
3943 function _update_post_term_count( $terms, $taxonomy ) {
3946 $object_types = (array) $taxonomy->object_type;
3948 foreach ( $object_types as &$object_type )
3949 list( $object_type ) = explode( ':', $object_type );
3951 $object_types = array_unique( $object_types );
3953 if ( false !== ( $check_attachments = array_search( 'attachment', $object_types ) ) ) {
3954 unset( $object_types[ $check_attachments ] );
3955 $check_attachments = true;
3958 if ( $object_types )
3959 $object_types = esc_sql( array_filter( $object_types, 'post_type_exists' ) );
3961 foreach ( (array) $terms as $term ) {
3964 // Attachments can be 'inherit' status, we need to base count off the parent's status if so
3965 if ( $check_attachments )
3966 $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 ) );
3968 if ( $object_types )
3969 $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 ) );
3971 /** This action is documented in wp-includes/taxonomy.php */
3972 do_action( 'edit_term_taxonomy', $term, $taxonomy );
3973 $wpdb->update( $wpdb->term_taxonomy, compact( 'count' ), array( 'term_taxonomy_id' => $term ) );
3975 /** This action is documented in wp-includes/taxonomy.php */
3976 do_action( 'edited_term_taxonomy', $term, $taxonomy );
3981 * Will update term count based on number of objects.
3983 * Default callback for the link_category taxonomy.
3987 * @global wpdb $wpdb WordPress database abstraction object.
3989 * @param array $terms List of Term taxonomy IDs
3990 * @param object $taxonomy Current taxonomy object of terms
3992 function _update_generic_term_count( $terms, $taxonomy ) {
3995 foreach ( (array) $terms as $term ) {
3996 $count = $wpdb->get_var( $wpdb->prepare( "SELECT COUNT(*) FROM $wpdb->term_relationships WHERE term_taxonomy_id = %d", $term ) );
3998 /** This action is documented in wp-includes/taxonomy.php */
3999 do_action( 'edit_term_taxonomy', $term, $taxonomy );
4000 $wpdb->update( $wpdb->term_taxonomy, compact( 'count' ), array( 'term_taxonomy_id' => $term ) );
4002 /** This action is documented in wp-includes/taxonomy.php */
4003 do_action( 'edited_term_taxonomy', $term, $taxonomy );
4008 * Generate a permalink for a taxonomy term archive.
4012 * @param object|int|string $term The term object, ID, or slug whose link will be retrieved.
4013 * @param string $taxonomy Optional. Taxonomy. Default empty.
4014 * @return string|WP_Error HTML link to taxonomy term archive on success, WP_Error if term does not exist.
4016 function get_term_link( $term, $taxonomy = '') {
4019 if ( !is_object($term) ) {
4020 if ( is_int($term) ) {
4021 $term = get_term($term, $taxonomy);
4023 $term = get_term_by('slug', $term, $taxonomy);
4027 if ( !is_object($term) )
4028 $term = new WP_Error('invalid_term', __('Empty Term'));
4030 if ( is_wp_error( $term ) )
4033 $taxonomy = $term->taxonomy;
4035 $termlink = $wp_rewrite->get_extra_permastruct($taxonomy);
4037 $slug = $term->slug;
4038 $t = get_taxonomy($taxonomy);
4040 if ( empty($termlink) ) {
4041 if ( 'category' == $taxonomy )
4042 $termlink = '?cat=' . $term->term_id;
4043 elseif ( $t->query_var )
4044 $termlink = "?$t->query_var=$slug";
4046 $termlink = "?taxonomy=$taxonomy&term=$slug";
4047 $termlink = home_url($termlink);
4049 if ( $t->rewrite['hierarchical'] ) {
4050 $hierarchical_slugs = array();
4051 $ancestors = get_ancestors( $term->term_id, $taxonomy, 'taxonomy' );
4052 foreach ( (array)$ancestors as $ancestor ) {
4053 $ancestor_term = get_term($ancestor, $taxonomy);
4054 $hierarchical_slugs[] = $ancestor_term->slug;
4056 $hierarchical_slugs = array_reverse($hierarchical_slugs);
4057 $hierarchical_slugs[] = $slug;
4058 $termlink = str_replace("%$taxonomy%", implode('/', $hierarchical_slugs), $termlink);
4060 $termlink = str_replace("%$taxonomy%", $slug, $termlink);
4062 $termlink = home_url( user_trailingslashit($termlink, 'category') );
4064 // Back Compat filters.
4065 if ( 'post_tag' == $taxonomy ) {
4068 * Filter the tag link.
4071 * @deprecated 2.5.0 Use 'term_link' instead.
4073 * @param string $termlink Tag link URL.
4074 * @param int $term_id Term ID.
4076 $termlink = apply_filters( 'tag_link', $termlink, $term->term_id );
4077 } elseif ( 'category' == $taxonomy ) {
4080 * Filter the category link.
4083 * @deprecated 2.5.0 Use 'term_link' instead.
4085 * @param string $termlink Category link URL.
4086 * @param int $term_id Term ID.
4088 $termlink = apply_filters( 'category_link', $termlink, $term->term_id );
4092 * Filter the term link.
4096 * @param string $termlink Term link URL.
4097 * @param object $term Term object.
4098 * @param string $taxonomy Taxonomy slug.
4100 return apply_filters( 'term_link', $termlink, $term, $taxonomy );
4104 * Display the taxonomies of a post with available options.
4106 * This function can be used within the loop to display the taxonomies for a
4107 * post without specifying the Post ID. You can also use it outside the Loop to
4108 * display the taxonomies for a specific post.
4112 * @param array $args {
4113 * Arguments about which post to use and how to format the output. Shares all of the arguments supported by
4114 * {@link get_the_taxonomies()}, in addition to the following.
4116 * @type int|WP_Post $post Post ID or object to get taxonomies of. Default current post.
4117 * @type string $before Displays before the taxonomies. Default empty string.
4118 * @type string $sep Separates each taxonomy. Default is a space.
4119 * @type string $after Displays after the taxonomies. Default empty string.
4121 * @param array $args See {@link get_the_taxonomies()} for a description of arguments and their defaults.
4123 function the_taxonomies( $args = array() ) {
4131 $r = wp_parse_args( $args, $defaults );
4133 echo $r['before'] . join( $r['sep'], get_the_taxonomies( $r['post'], $r ) ) . $r['after'];
4137 * Retrieve all taxonomies associated with a post.
4139 * This function can be used within the loop. It will also return an array of
4140 * the taxonomies with links to the taxonomy and name.
4144 * @param int|WP_Post $post Optional. Post ID or WP_Post object. Default is global $post.
4145 * @param array $args {
4146 * Arguments about how to format the list of taxonomies.
4148 * @type string $template Template for displaying a taxonomy label and list of terms.
4149 * Default is "Label: Terms."
4150 * @type string $term_template Template for displaying a single term in the list. Default is the term name
4151 * linked to its archive.
4153 * @return array List of taxonomies.
4155 function get_the_taxonomies( $post = 0, $args = array() ) {
4156 $post = get_post( $post );
4158 $args = wp_parse_args( $args, array(
4159 /* translators: %s: taxonomy label, %l: list of terms formatted as per $term_template */
4160 'template' => __( '%s: %l.' ),
4161 'term_template' => '<a href="%1$s">%2$s</a>',
4164 $taxonomies = array();
4170 foreach ( get_object_taxonomies( $post ) as $taxonomy ) {
4171 $t = (array) get_taxonomy( $taxonomy );
4172 if ( empty( $t['label'] ) ) {
4173 $t['label'] = $taxonomy;
4175 if ( empty( $t['args'] ) ) {
4176 $t['args'] = array();
4178 if ( empty( $t['template'] ) ) {
4179 $t['template'] = $args['template'];
4181 if ( empty( $t['term_template'] ) ) {
4182 $t['term_template'] = $args['term_template'];
4185 $terms = get_object_term_cache( $post->ID, $taxonomy );
4186 if ( false === $terms ) {
4187 $terms = wp_get_object_terms( $post->ID, $taxonomy, $t['args'] );
4191 foreach ( $terms as $term ) {
4192 $links[] = wp_sprintf( $t['term_template'], esc_attr( get_term_link( $term ) ), $term->name );
4195 $taxonomies[$taxonomy] = wp_sprintf( $t['template'], $t['label'], $links, $terms );
4202 * Retrieve all taxonomies of a post with just the names.
4206 * @param int|WP_Post $post Optional. Post ID or WP_Post object. Default is global $post.
4209 function get_post_taxonomies( $post = 0 ) {
4210 $post = get_post( $post );
4212 return get_object_taxonomies($post);
4216 * Determine if the given object is associated with any of the given terms.
4218 * The given terms are checked against the object's terms' term_ids, names and slugs.
4219 * Terms given as integers will only be checked against the object's terms' term_ids.
4220 * If no terms are given, determines if object is associated with any terms in the given taxonomy.
4224 * @param int $object_id ID of the object (post ID, link ID, ...)
4225 * @param string $taxonomy Single taxonomy name
4226 * @param int|string|array $terms Optional. Term term_id, name, slug or array of said
4227 * @return bool|WP_Error. WP_Error on input error.
4229 function is_object_in_term( $object_id, $taxonomy, $terms = null ) {
4230 if ( !$object_id = (int) $object_id )
4231 return new WP_Error( 'invalid_object', __( 'Invalid object ID' ) );
4233 $object_terms = get_object_term_cache( $object_id, $taxonomy );
4234 if ( false === $object_terms )
4235 $object_terms = wp_get_object_terms( $object_id, $taxonomy );
4237 if ( is_wp_error( $object_terms ) )
4238 return $object_terms;
4239 if ( empty( $object_terms ) )
4241 if ( empty( $terms ) )
4242 return ( !empty( $object_terms ) );
4244 $terms = (array) $terms;
4246 if ( $ints = array_filter( $terms, 'is_int' ) )
4247 $strs = array_diff( $terms, $ints );
4251 foreach ( $object_terms as $object_term ) {
4252 // If term is an int, check against term_ids only.
4253 if ( $ints && in_array( $object_term->term_id, $ints ) ) {
4258 // Only check numeric strings against term_id, to avoid false matches due to type juggling.
4259 $numeric_strs = array_map( 'intval', array_filter( $strs, 'is_numeric' ) );
4260 if ( in_array( $object_term->term_id, $numeric_strs, true ) ) {
4264 if ( in_array( $object_term->name, $strs ) ) return true;
4265 if ( in_array( $object_term->slug, $strs ) ) return true;
4273 * Determine if the given object type is associated with the given taxonomy.
4277 * @param string $object_type Object type string
4278 * @param string $taxonomy Single taxonomy name
4279 * @return bool True if object is associated with the taxonomy, otherwise false.
4281 function is_object_in_taxonomy($object_type, $taxonomy) {
4282 $taxonomies = get_object_taxonomies($object_type);
4284 if ( empty($taxonomies) )
4287 if ( in_array($taxonomy, $taxonomies) )
4294 * Get an array of ancestor IDs for a given object.
4297 * @since 4.1.0 Introduced the `$resource_type` argument.
4299 * @param int $object_id Optional. The ID of the object. Default 0.
4300 * @param string $object_type Optional. The type of object for which we'll be retrieving
4301 * ancestors. Accepts a post type or a taxonomy name. Default empty.
4302 * @param string $resource_type Optional. Type of resource $object_type is. Accepts 'post_type'
4303 * or 'taxonomy'. Default empty.
4304 * @return array An array of ancestors from lowest to highest in the hierarchy.
4306 function get_ancestors( $object_id = 0, $object_type = '', $resource_type = '' ) {
4307 $object_id = (int) $object_id;
4309 $ancestors = array();
4311 if ( empty( $object_id ) ) {
4313 /** This filter is documented in wp-includes/taxonomy.php */
4314 return apply_filters( 'get_ancestors', $ancestors, $object_id, $object_type, $resource_type );
4317 if ( ! $resource_type ) {
4318 if ( is_taxonomy_hierarchical( $object_type ) ) {
4319 $resource_type = 'taxonomy';
4320 } else if ( post_type_exists( $object_type ) ) {
4321 $resource_type = 'post_type';
4325 if ( 'taxonomy' === $resource_type ) {
4326 $term = get_term($object_id, $object_type);
4327 while ( ! is_wp_error($term) && ! empty( $term->parent ) && ! in_array( $term->parent, $ancestors ) ) {
4328 $ancestors[] = (int) $term->parent;
4329 $term = get_term($term->parent, $object_type);
4331 } elseif ( 'post_type' === $resource_type ) {
4332 $ancestors = get_post_ancestors($object_id);
4336 * Filter a given object's ancestors.
4340 * @param array $ancestors An array of object ancestors.
4341 * @param int $object_id Object ID.
4342 * @param string $object_type Type of object.
4343 * @param string $resource_type Type of resource $object_type is.
4345 return apply_filters( 'get_ancestors', $ancestors, $object_id, $object_type );
4349 * Returns the term's parent's term_ID
4353 * @param int $term_id
4354 * @param string $taxonomy
4356 * @return int|bool false on error
4358 function wp_get_term_taxonomy_parent_id( $term_id, $taxonomy ) {
4359 $term = get_term( $term_id, $taxonomy );
4360 if ( !$term || is_wp_error( $term ) )
4362 return (int) $term->parent;
4366 * Checks the given subset of the term hierarchy for hierarchy loops.
4367 * Prevents loops from forming and breaks those that it finds.
4369 * Attached to the wp_update_term_parent filter.
4373 * @param int $parent term_id of the parent for the term we're checking.
4374 * @param int $term_id The term we're checking.
4375 * @param string $taxonomy The taxonomy of the term we're checking.
4377 * @return int The new parent for the term.
4379 function wp_check_term_hierarchy_for_loops( $parent, $term_id, $taxonomy ) {
4380 // Nothing fancy here - bail
4384 // Can't be its own parent
4385 if ( $parent == $term_id )
4388 // Now look for larger loops
4390 if ( !$loop = wp_find_hierarchy_loop( 'wp_get_term_taxonomy_parent_id', $term_id, $parent, array( $taxonomy ) ) )
4391 return $parent; // No loop
4393 // Setting $parent to the given value causes a loop
4394 if ( isset( $loop[$term_id] ) )
4397 // There's a loop, but it doesn't contain $term_id. Break the loop.
4398 foreach ( array_keys( $loop ) as $loop_member )
4399 wp_update_term( $loop_member, $taxonomy, array( 'parent' => 0 ) );