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' ),
132 * Get a list of registered taxonomy objects.
135 * @uses $wp_taxonomies
137 * @param array $args An array of key => value arguments to match against the taxonomy objects.
138 * @param string $output The type of output to return, either taxonomy 'names' or 'objects'. 'names' is the default.
139 * @param string $operator The logical operation to perform. 'or' means only one element
140 * from the array needs to match; 'and' means all elements must match. The default is 'and'.
141 * @return array A list of taxonomy names or objects
143 function get_taxonomies( $args = array(), $output = 'names', $operator = 'and' ) {
144 global $wp_taxonomies;
146 $field = ('names' == $output) ? 'name' : false;
148 return wp_filter_object_list($wp_taxonomies, $args, $operator, $field);
152 * Return all of the taxonomy names that are of $object_type.
154 * It appears that this function can be used to find all of the names inside of
155 * $wp_taxonomies global variable.
157 * `<?php $taxonomies = get_object_taxonomies('post'); ?>` Should
158 * result in `Array( 'category', 'post_tag' )`
162 * @uses $wp_taxonomies
164 * @param array|string|object $object Name of the type of taxonomy object, or an object (row from posts)
165 * @param string $output The type of output to return, either taxonomy 'names' or 'objects'. 'names' is the default.
166 * @return array The names of all taxonomy of $object_type.
168 function get_object_taxonomies($object, $output = 'names') {
169 global $wp_taxonomies;
171 if ( is_object($object) ) {
172 if ( $object->post_type == 'attachment' )
173 return get_attachment_taxonomies($object);
174 $object = $object->post_type;
177 $object = (array) $object;
179 $taxonomies = array();
180 foreach ( (array) $wp_taxonomies as $tax_name => $tax_obj ) {
181 if ( array_intersect($object, (array) $tax_obj->object_type) ) {
182 if ( 'names' == $output )
183 $taxonomies[] = $tax_name;
185 $taxonomies[ $tax_name ] = $tax_obj;
193 * Retrieves the taxonomy object of $taxonomy.
195 * The get_taxonomy function will first check that the parameter string given
196 * is a taxonomy object and if it is, it will return it.
200 * @uses $wp_taxonomies
202 * @param string $taxonomy Name of taxonomy object to return
203 * @return object|bool The Taxonomy Object or false if $taxonomy doesn't exist
205 function get_taxonomy( $taxonomy ) {
206 global $wp_taxonomies;
208 if ( ! taxonomy_exists( $taxonomy ) )
211 return $wp_taxonomies[$taxonomy];
215 * Checks that the taxonomy name exists.
217 * Formerly is_taxonomy(), introduced in 2.3.0.
221 * @uses $wp_taxonomies
223 * @param string $taxonomy Name of taxonomy object
224 * @return bool Whether the taxonomy exists.
226 function taxonomy_exists( $taxonomy ) {
227 global $wp_taxonomies;
229 return isset( $wp_taxonomies[$taxonomy] );
233 * Whether the taxonomy object is hierarchical.
235 * Checks to make sure that the taxonomy is an object first. Then Gets the
236 * object, and finally returns the hierarchical value in the object.
238 * A false return value might also mean that the taxonomy does not exist.
242 * @param string $taxonomy Name of taxonomy object
243 * @return bool Whether the taxonomy is hierarchical
245 function is_taxonomy_hierarchical($taxonomy) {
246 if ( ! taxonomy_exists($taxonomy) )
249 $taxonomy = get_taxonomy($taxonomy);
250 return $taxonomy->hierarchical;
254 * Create or modify a taxonomy object. Do not use before init.
256 * A simple function for creating or modifying a taxonomy object based on the
257 * parameters given. The function will accept an array (third optional
258 * parameter), along with strings for the taxonomy name and another string for
261 * Nothing is returned, so expect error maybe or use taxonomy_exists() to check
262 * whether taxonomy exists.
264 * Optional $args contents:
266 * - label - Name of the taxonomy shown in the menu. Usually plural. If not set, labels['name'] will be used.
267 * - labels - An array of labels for this taxonomy.
268 * * By default tag labels are used for non-hierarchical types and category labels for hierarchical ones.
269 * * You can see accepted values in {@link get_taxonomy_labels()}.
270 * - description - A short descriptive summary of what the taxonomy is for. Defaults to blank.
271 * - public - If the taxonomy should be publicly queryable; //@TODO not implemented.
272 * * Defaults to true.
273 * - hierarchical - Whether the taxonomy is hierarchical (e.g. category). Defaults to false.
274 * - show_ui - Whether to generate a default UI for managing this taxonomy in the admin.
275 * * If not set, the default is inherited from public.
276 * - show_in_menu - Whether to show the taxonomy in the admin menu.
277 * * If true, the taxonomy is shown as a submenu of the object type menu.
278 * * If false, no menu is shown.
279 * * show_ui must be true.
280 * * If not set, the default is inherited from show_ui.
281 * - show_in_nav_menus - Makes this taxonomy available for selection in navigation menus.
282 * * If not set, the default is inherited from public.
283 * - show_tagcloud - Whether to list the taxonomy in the Tag Cloud Widget.
284 * * If not set, the default is inherited from show_ui.
285 * - show_in_quick_edit - Whether to show the taxonomy in the quick/bulk edit panel.
286 * * It not set, the default is inherited from show_ui.
287 * - show_admin_column - Whether to display a column for the taxonomy on its post type listing screens.
288 * * Defaults to false.
289 * - meta_box_cb - Provide a callback function for the meta box display.
290 * * If not set, defaults to post_categories_meta_box for hierarchical taxonomies
291 * and post_tags_meta_box for non-hierarchical.
292 * * If false, no meta box is shown.
293 * - capabilities - Array of capabilities for this taxonomy.
294 * * You can see accepted values in this function.
295 * - rewrite - Triggers the handling of rewrites for this taxonomy. Defaults to true, using $taxonomy as slug.
296 * * To prevent rewrite, set to false.
297 * * To specify rewrite rules, an array can be passed with any of these keys
298 * * 'slug' => string Customize the permastruct slug. Defaults to $taxonomy key
299 * * 'with_front' => bool Should the permastruct be prepended with WP_Rewrite::$front. Defaults to true.
300 * * 'hierarchical' => bool Either hierarchical rewrite tag or not. Defaults to false.
301 * * 'ep_mask' => const Assign an endpoint mask.
302 * * If not specified, defaults to EP_NONE.
303 * - query_var - Sets the query_var key for this taxonomy. Defaults to $taxonomy key
304 * * If false, a taxonomy cannot be loaded at ?{query_var}={term_slug}
305 * * If specified as a string, the query ?{query_var_string}={term_slug} will be valid.
306 * - update_count_callback - Works much like a hook, in that it will be called when the count is updated.
307 * * Defaults to _update_post_term_count() for taxonomies attached to post types, which then confirms
308 * that the objects are published before counting them.
309 * * Defaults to _update_generic_term_count() for taxonomies attached to other object types, such as links.
310 * - _builtin - true if this taxonomy is a native or "built-in" taxonomy. THIS IS FOR INTERNAL USE ONLY!
313 * @since 4.2.0 Introduced `show_in_quick_edit` argument.
315 * @global array $wp_taxonomies Registered taxonomies.
316 * @global WP $wp WP instance.
318 * @param string $taxonomy Taxonomy key, must not exceed 32 characters.
319 * @param array|string $object_type Name of the object type for the taxonomy object.
320 * @param array|string $args See optional args description above.
321 * @return null|WP_Error WP_Error if errors, otherwise null.
323 function register_taxonomy( $taxonomy, $object_type, $args = array() ) {
324 global $wp_taxonomies, $wp;
326 if ( ! is_array( $wp_taxonomies ) )
327 $wp_taxonomies = array();
333 'hierarchical' => false,
335 'show_in_menu' => null,
336 'show_in_nav_menus' => null,
337 'show_tagcloud' => null,
338 'show_in_quick_edit' => null,
339 'show_admin_column' => false,
340 'meta_box_cb' => null,
341 'capabilities' => array(),
343 'query_var' => $taxonomy,
344 'update_count_callback' => '',
347 $args = wp_parse_args( $args, $defaults );
349 if ( empty( $taxonomy ) || strlen( $taxonomy ) > 32 ) {
350 _doing_it_wrong( __FUNCTION__, __( 'Taxonomy names must be between 1 and 32 characters in length.' ), '4.2' );
351 return new WP_Error( 'taxonomy_length_invalid', __( 'Taxonomy names must be between 1 and 32 characters in length.' ) );
354 if ( false !== $args['query_var'] && ! empty( $wp ) ) {
355 if ( true === $args['query_var'] )
356 $args['query_var'] = $taxonomy;
358 $args['query_var'] = sanitize_title_with_dashes( $args['query_var'] );
359 $wp->add_query_var( $args['query_var'] );
362 if ( false !== $args['rewrite'] && ( is_admin() || '' != get_option( 'permalink_structure' ) ) ) {
363 $args['rewrite'] = wp_parse_args( $args['rewrite'], array(
364 'with_front' => true,
365 'hierarchical' => false,
366 'ep_mask' => EP_NONE,
369 if ( empty( $args['rewrite']['slug'] ) )
370 $args['rewrite']['slug'] = sanitize_title_with_dashes( $taxonomy );
372 if ( $args['hierarchical'] && $args['rewrite']['hierarchical'] )
377 add_rewrite_tag( "%$taxonomy%", $tag, $args['query_var'] ? "{$args['query_var']}=" : "taxonomy=$taxonomy&term=" );
378 add_permastruct( $taxonomy, "{$args['rewrite']['slug']}/%$taxonomy%", $args['rewrite'] );
381 // If not set, default to the setting for public.
382 if ( null === $args['show_ui'] )
383 $args['show_ui'] = $args['public'];
385 // If not set, default to the setting for show_ui.
386 if ( null === $args['show_in_menu' ] || ! $args['show_ui'] )
387 $args['show_in_menu' ] = $args['show_ui'];
389 // If not set, default to the setting for public.
390 if ( null === $args['show_in_nav_menus'] )
391 $args['show_in_nav_menus'] = $args['public'];
393 // If not set, default to the setting for show_ui.
394 if ( null === $args['show_tagcloud'] )
395 $args['show_tagcloud'] = $args['show_ui'];
397 // If not set, default to the setting for show_ui.
398 if ( null === $args['show_in_quick_edit'] ) {
399 $args['show_in_quick_edit'] = $args['show_ui'];
402 $default_caps = array(
403 'manage_terms' => 'manage_categories',
404 'edit_terms' => 'manage_categories',
405 'delete_terms' => 'manage_categories',
406 'assign_terms' => 'edit_posts',
408 $args['cap'] = (object) array_merge( $default_caps, $args['capabilities'] );
409 unset( $args['capabilities'] );
411 $args['name'] = $taxonomy;
412 $args['object_type'] = array_unique( (array) $object_type );
414 $args['labels'] = get_taxonomy_labels( (object) $args );
415 $args['label'] = $args['labels']->name;
417 // If not set, use the default meta box
418 if ( null === $args['meta_box_cb'] ) {
419 if ( $args['hierarchical'] )
420 $args['meta_box_cb'] = 'post_categories_meta_box';
422 $args['meta_box_cb'] = 'post_tags_meta_box';
425 $wp_taxonomies[ $taxonomy ] = (object) $args;
427 // register callback handling for metabox
428 add_filter( 'wp_ajax_add-' . $taxonomy, '_wp_ajax_add_hierarchical_term' );
431 * Fires after a taxonomy is registered.
435 * @param string $taxonomy Taxonomy slug.
436 * @param array|string $object_type Object type or array of object types.
437 * @param array $args Array of taxonomy registration arguments.
439 do_action( 'registered_taxonomy', $taxonomy, $object_type, $args );
443 * Builds an object with all taxonomy labels out of a taxonomy object
445 * Accepted keys of the label array in the taxonomy object:
447 * - name - general name for the taxonomy, usually plural. The same as and overridden by $tax->label. Default is Tags/Categories
448 * - singular_name - name for one object of this taxonomy. Default is Tag/Category
449 * - search_items - Default is Search Tags/Search Categories
450 * - popular_items - This string isn't used on hierarchical taxonomies. Default is Popular Tags
451 * - all_items - Default is All Tags/All Categories
452 * - parent_item - This string isn't used on non-hierarchical taxonomies. In hierarchical ones the default is Parent Category
453 * - parent_item_colon - The same as `parent_item`, but with colon `:` in the end
454 * - edit_item - Default is Edit Tag/Edit Category
455 * - view_item - Default is View Tag/View Category
456 * - update_item - Default is Update Tag/Update Category
457 * - add_new_item - Default is Add New Tag/Add New Category
458 * - new_item_name - Default is New Tag Name/New Category Name
459 * - separate_items_with_commas - This string isn't used on hierarchical taxonomies. Default is "Separate tags with commas", used in the meta box.
460 * - 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.
461 * - 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.
462 * - not_found - Default is "No tags found"/"No categories found", used in the meta box and taxonomy list table.
464 * Above, the first default value is for non-hierarchical taxonomies (like tags) and the second one is for hierarchical taxonomies (like categories).
467 * @param object $tax Taxonomy object
468 * @return object object with all the labels as member variables
471 function get_taxonomy_labels( $tax ) {
472 $tax->labels = (array) $tax->labels;
474 if ( isset( $tax->helps ) && empty( $tax->labels['separate_items_with_commas'] ) )
475 $tax->labels['separate_items_with_commas'] = $tax->helps;
477 if ( isset( $tax->no_tagcloud ) && empty( $tax->labels['not_found'] ) )
478 $tax->labels['not_found'] = $tax->no_tagcloud;
480 $nohier_vs_hier_defaults = array(
481 'name' => array( _x( 'Tags', 'taxonomy general name' ), _x( 'Categories', 'taxonomy general name' ) ),
482 'singular_name' => array( _x( 'Tag', 'taxonomy singular name' ), _x( 'Category', 'taxonomy singular name' ) ),
483 'search_items' => array( __( 'Search Tags' ), __( 'Search Categories' ) ),
484 'popular_items' => array( __( 'Popular Tags' ), null ),
485 'all_items' => array( __( 'All Tags' ), __( 'All Categories' ) ),
486 'parent_item' => array( null, __( 'Parent Category' ) ),
487 'parent_item_colon' => array( null, __( 'Parent Category:' ) ),
488 'edit_item' => array( __( 'Edit Tag' ), __( 'Edit Category' ) ),
489 'view_item' => array( __( 'View Tag' ), __( 'View Category' ) ),
490 'update_item' => array( __( 'Update Tag' ), __( 'Update Category' ) ),
491 'add_new_item' => array( __( 'Add New Tag' ), __( 'Add New Category' ) ),
492 'new_item_name' => array( __( 'New Tag Name' ), __( 'New Category Name' ) ),
493 'separate_items_with_commas' => array( __( 'Separate tags with commas' ), null ),
494 'add_or_remove_items' => array( __( 'Add or remove tags' ), null ),
495 'choose_from_most_used' => array( __( 'Choose from the most used tags' ), null ),
496 'not_found' => array( __( 'No tags found.' ), __( 'No categories found.' ) ),
498 $nohier_vs_hier_defaults['menu_name'] = $nohier_vs_hier_defaults['name'];
500 return _get_custom_object_labels( $tax, $nohier_vs_hier_defaults );
504 * Add an already registered taxonomy to an object type.
507 * @uses $wp_taxonomies Modifies taxonomy object
509 * @param string $taxonomy Name of taxonomy object
510 * @param string $object_type Name of the object type
511 * @return bool True if successful, false if not
513 function register_taxonomy_for_object_type( $taxonomy, $object_type) {
514 global $wp_taxonomies;
516 if ( !isset($wp_taxonomies[$taxonomy]) )
519 if ( ! get_post_type_object($object_type) )
522 if ( ! in_array( $object_type, $wp_taxonomies[$taxonomy]->object_type ) )
523 $wp_taxonomies[$taxonomy]->object_type[] = $object_type;
529 * Remove an already registered taxonomy from an object type.
533 * @param string $taxonomy Name of taxonomy object.
534 * @param string $object_type Name of the object type.
535 * @return bool True if successful, false if not.
537 function unregister_taxonomy_for_object_type( $taxonomy, $object_type ) {
538 global $wp_taxonomies;
540 if ( ! isset( $wp_taxonomies[ $taxonomy ] ) )
543 if ( ! get_post_type_object( $object_type ) )
546 $key = array_search( $object_type, $wp_taxonomies[ $taxonomy ]->object_type, true );
547 if ( false === $key )
550 unset( $wp_taxonomies[ $taxonomy ]->object_type[ $key ] );
559 * Retrieve object_ids of valid taxonomy and term.
561 * The strings of $taxonomies must exist before this function will continue. On
562 * failure of finding a valid taxonomy, it will return an WP_Error class, kind
563 * of like Exceptions in PHP 5, except you can't catch them. Even so, you can
564 * still test for the WP_Error class and get the error message.
566 * The $terms aren't checked the same as $taxonomies, but still need to exist
567 * for $object_ids to be returned.
569 * It is possible to change the order that object_ids is returned by either
570 * using PHP sort family functions or using the database by using $args with
571 * either ASC or DESC array. The value should be in the key named 'order'.
575 * @global wpdb $wpdb WordPress database abstraction object.
577 * @param int|array $term_ids Term id or array of term ids of terms that will be used
578 * @param string|array $taxonomies String of taxonomy name or Array of string values of taxonomy names
579 * @param array|string $args Change the order of the object_ids, either ASC or DESC
580 * @return WP_Error|array If the taxonomy does not exist, then WP_Error will be returned. On success
581 * the array can be empty meaning that there are no $object_ids found or it will return the $object_ids found.
583 function get_objects_in_term( $term_ids, $taxonomies, $args = array() ) {
586 if ( ! is_array( $term_ids ) ) {
587 $term_ids = array( $term_ids );
589 if ( ! is_array( $taxonomies ) ) {
590 $taxonomies = array( $taxonomies );
592 foreach ( (array) $taxonomies as $taxonomy ) {
593 if ( ! taxonomy_exists( $taxonomy ) ) {
594 return new WP_Error( 'invalid_taxonomy', __( 'Invalid taxonomy' ) );
598 $defaults = array( 'order' => 'ASC' );
599 $args = wp_parse_args( $args, $defaults );
601 $order = ( 'desc' == strtolower( $args['order'] ) ) ? 'DESC' : 'ASC';
603 $term_ids = array_map('intval', $term_ids );
605 $taxonomies = "'" . implode( "', '", $taxonomies ) . "'";
606 $term_ids = "'" . implode( "', '", $term_ids ) . "'";
608 $object_ids = $wpdb->get_col("SELECT tr.object_id FROM $wpdb->term_relationships AS tr INNER JOIN $wpdb->term_taxonomy AS tt ON tr.term_taxonomy_id = tt.term_taxonomy_id WHERE tt.taxonomy IN ($taxonomies) AND tt.term_id IN ($term_ids) ORDER BY tr.object_id $order");
610 if ( ! $object_ids ){
617 * Given a taxonomy query, generates SQL to be appended to a main query.
623 * @param array $tax_query A compact tax query
624 * @param string $primary_table
625 * @param string $primary_id_column
628 function get_tax_sql( $tax_query, $primary_table, $primary_id_column ) {
629 $tax_query_obj = new WP_Tax_Query( $tax_query );
630 return $tax_query_obj->get_sql( $primary_table, $primary_id_column );
634 * Class for generating SQL clauses that filter a primary query according to object taxonomy terms.
636 * `WP_Tax_Query` is a helper that allows primary query classes, such as {@see WP_Query}, to filter
637 * their results by object metadata, by generating `JOIN` and `WHERE` subclauses to be attached
638 * to the primary SQL query string.
645 * Array of taxonomy queries.
647 * See {@see WP_Tax_Query::__construct()} for information on tax query arguments.
653 public $queries = array();
656 * The relation between the queries. Can be one of 'AND' or 'OR'.
665 * Standard response when the query should not return any rows.
671 private static $no_results = array( 'join' => array( '' ), 'where' => array( '0 = 1' ) );
674 * A flat list of table aliases used in the JOIN clauses.
680 protected $table_aliases = array();
683 * Terms and taxonomies fetched by this query.
685 * We store this data in a flat array because they are referenced in a
686 * number of places by {@see WP_Query}.
692 public $queried_terms = array();
695 * Database table that where the metadata's objects are stored (eg $wpdb->users).
701 public $primary_table;
704 * Column in 'primary_table' that represents the ID of the object.
710 public $primary_id_column;
716 * @since 4.1.0 Added support for `$operator` 'NOT EXISTS' and 'EXISTS' values.
719 * @param array $tax_query {
720 * Array of taxonomy query clauses.
722 * @type string $relation Optional. The MySQL keyword used to join
723 * the clauses of the query. Accepts 'AND', or 'OR'. Default 'AND'.
725 * Optional. An array of first-order clause parameters, or another fully-formed tax query.
727 * @type string $taxonomy Taxonomy being queried. Optional when field=term_taxonomy_id.
728 * @type string|int|array $terms Term or terms to filter by.
729 * @type string $field Field to match $terms against. Accepts 'term_id', 'slug',
730 * 'name', or 'term_taxonomy_id'. Default: 'term_id'.
731 * @type string $operator MySQL operator to be used with $terms in the WHERE clause.
732 * Accepts 'AND', 'IN', 'NOT IN', 'EXISTS', 'NOT EXISTS'.
734 * @type bool $include_children Optional. Whether to include child terms.
735 * Requires a $taxonomy. Default: true.
739 public function __construct( $tax_query ) {
740 if ( isset( $tax_query['relation'] ) ) {
741 $this->relation = $this->sanitize_relation( $tax_query['relation'] );
743 $this->relation = 'AND';
746 $this->queries = $this->sanitize_query( $tax_query );
750 * Ensure the 'tax_query' argument passed to the class constructor is well-formed.
752 * Ensures that each query-level clause has a 'relation' key, and that
753 * each first-order clause contains all the necessary keys from `$defaults`.
758 * @param array $queries Array of queries clauses.
759 * @return array Sanitized array of query clauses.
761 public function sanitize_query( $queries ) {
762 $cleaned_query = array();
767 'field' => 'term_id',
769 'include_children' => true,
772 foreach ( $queries as $key => $query ) {
773 if ( 'relation' === $key ) {
774 $cleaned_query['relation'] = $this->sanitize_relation( $query );
776 // First-order clause.
777 } elseif ( self::is_first_order_clause( $query ) ) {
779 $cleaned_clause = array_merge( $defaults, $query );
780 $cleaned_clause['terms'] = (array) $cleaned_clause['terms'];
781 $cleaned_query[] = $cleaned_clause;
784 * Keep a copy of the clause in the flate
785 * $queried_terms array, for use in WP_Query.
787 if ( ! empty( $cleaned_clause['taxonomy'] ) && 'NOT IN' !== $cleaned_clause['operator'] ) {
788 $taxonomy = $cleaned_clause['taxonomy'];
789 if ( ! isset( $this->queried_terms[ $taxonomy ] ) ) {
790 $this->queried_terms[ $taxonomy ] = array();
794 * Backward compatibility: Only store the first
795 * 'terms' and 'field' found for a given taxonomy.
797 if ( ! empty( $cleaned_clause['terms'] ) && ! isset( $this->queried_terms[ $taxonomy ]['terms'] ) ) {
798 $this->queried_terms[ $taxonomy ]['terms'] = $cleaned_clause['terms'];
801 if ( ! empty( $cleaned_clause['field'] ) && ! isset( $this->queried_terms[ $taxonomy ]['field'] ) ) {
802 $this->queried_terms[ $taxonomy ]['field'] = $cleaned_clause['field'];
806 // Otherwise, it's a nested query, so we recurse.
807 } elseif ( is_array( $query ) ) {
808 $cleaned_subquery = $this->sanitize_query( $query );
810 if ( ! empty( $cleaned_subquery ) ) {
811 // All queries with children must have a relation.
812 if ( ! isset( $cleaned_subquery['relation'] ) ) {
813 $cleaned_subquery['relation'] = 'AND';
816 $cleaned_query[] = $cleaned_subquery;
821 return $cleaned_query;
825 * Sanitize a 'relation' operator.
830 * @param string $relation Raw relation key from the query argument.
831 * @return string Sanitized relation ('AND' or 'OR').
833 public function sanitize_relation( $relation ) {
834 if ( 'OR' === strtoupper( $relation ) ) {
842 * Determine whether a clause is first-order.
844 * A "first-order" clause is one that contains any of the first-order
845 * clause keys ('terms', 'taxonomy', 'include_children', 'field',
846 * 'operator'). An empty clause also counts as a first-order clause,
847 * for backward compatibility. Any clause that doesn't meet this is
848 * determined, by process of elimination, to be a higher-order query.
853 * @param array $query Tax query arguments.
854 * @return bool Whether the query clause is a first-order clause.
856 protected static function is_first_order_clause( $query ) {
857 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 ) );
861 * Generates SQL clauses to be appended to a main query.
866 * @param string $primary_table Database table where the object being filtered is stored (eg wp_users).
867 * @param string $primary_id_column ID column for the filtered object in $primary_table.
869 * Array containing JOIN and WHERE SQL clauses to append to the main query.
871 * @type string $join SQL fragment to append to the main JOIN clause.
872 * @type string $where SQL fragment to append to the main WHERE clause.
875 public function get_sql( $primary_table, $primary_id_column ) {
876 $this->primary_table = $primary_table;
877 $this->primary_id_column = $primary_id_column;
879 return $this->get_sql_clauses();
883 * Generate SQL clauses to be appended to a main query.
885 * Called by the public {@see WP_Tax_Query::get_sql()}, this method
886 * is abstracted out to maintain parity with the other Query classes.
892 * Array containing JOIN and WHERE SQL clauses to append to the main query.
894 * @type string $join SQL fragment to append to the main JOIN clause.
895 * @type string $where SQL fragment to append to the main WHERE clause.
898 protected function get_sql_clauses() {
900 * $queries are passed by reference to get_sql_for_query() for recursion.
901 * To keep $this->queries unaltered, pass a copy.
903 $queries = $this->queries;
904 $sql = $this->get_sql_for_query( $queries );
906 if ( ! empty( $sql['where'] ) ) {
907 $sql['where'] = ' AND ' . $sql['where'];
914 * Generate SQL clauses for a single query array.
916 * If nested subqueries are found, this method recurses the tree to
917 * produce the properly nested SQL.
922 * @param array $query Query to parse, passed by reference.
923 * @param int $depth Optional. Number of tree levels deep we currently are.
924 * Used to calculate indentation. Default 0.
926 * Array containing JOIN and WHERE SQL clauses to append to a single query array.
928 * @type string $join SQL fragment to append to the main JOIN clause.
929 * @type string $where SQL fragment to append to the main WHERE clause.
932 protected function get_sql_for_query( &$query, $depth = 0 ) {
944 for ( $i = 0; $i < $depth; $i++ ) {
948 foreach ( $query as $key => &$clause ) {
949 if ( 'relation' === $key ) {
950 $relation = $query['relation'];
951 } elseif ( is_array( $clause ) ) {
953 // This is a first-order clause.
954 if ( $this->is_first_order_clause( $clause ) ) {
955 $clause_sql = $this->get_sql_for_clause( $clause, $query );
957 $where_count = count( $clause_sql['where'] );
958 if ( ! $where_count ) {
959 $sql_chunks['where'][] = '';
960 } elseif ( 1 === $where_count ) {
961 $sql_chunks['where'][] = $clause_sql['where'][0];
963 $sql_chunks['where'][] = '( ' . implode( ' AND ', $clause_sql['where'] ) . ' )';
966 $sql_chunks['join'] = array_merge( $sql_chunks['join'], $clause_sql['join'] );
967 // This is a subquery, so we recurse.
969 $clause_sql = $this->get_sql_for_query( $clause, $depth + 1 );
971 $sql_chunks['where'][] = $clause_sql['where'];
972 $sql_chunks['join'][] = $clause_sql['join'];
977 // Filter to remove empties.
978 $sql_chunks['join'] = array_filter( $sql_chunks['join'] );
979 $sql_chunks['where'] = array_filter( $sql_chunks['where'] );
981 if ( empty( $relation ) ) {
985 // Filter duplicate JOIN clauses and combine into a single string.
986 if ( ! empty( $sql_chunks['join'] ) ) {
987 $sql['join'] = implode( ' ', array_unique( $sql_chunks['join'] ) );
990 // Generate a single WHERE clause with proper brackets and indentation.
991 if ( ! empty( $sql_chunks['where'] ) ) {
992 $sql['where'] = '( ' . "\n " . $indent . implode( ' ' . "\n " . $indent . $relation . ' ' . "\n " . $indent, $sql_chunks['where'] ) . "\n" . $indent . ')';
999 * Generate SQL JOIN and WHERE clauses for a "first-order" query clause.
1004 * @param array $clause Query clause, passed by reference
1005 * @param array $parent_query Parent query array.
1007 * Array containing JOIN and WHERE SQL clauses to append to a first-order query.
1009 * @type string $join SQL fragment to append to the main JOIN clause.
1010 * @type string $where SQL fragment to append to the main WHERE clause.
1013 public function get_sql_for_clause( &$clause, $parent_query ) {
1023 $this->clean_query( $clause );
1025 if ( is_wp_error( $clause ) ) {
1026 return self::$no_results;
1029 $terms = $clause['terms'];
1030 $operator = strtoupper( $clause['operator'] );
1032 if ( 'IN' == $operator ) {
1034 if ( empty( $terms ) ) {
1035 return self::$no_results;
1038 $terms = implode( ',', $terms );
1041 * Before creating another table join, see if this clause has a
1042 * sibling with an existing join that can be shared.
1044 $alias = $this->find_compatible_table_alias( $clause, $parent_query );
1045 if ( false === $alias ) {
1046 $i = count( $this->table_aliases );
1047 $alias = $i ? 'tt' . $i : $wpdb->term_relationships;
1049 // Store the alias as part of a flat array to build future iterators.
1050 $this->table_aliases[] = $alias;
1052 // Store the alias with this clause, so later siblings can use it.
1053 $clause['alias'] = $alias;
1055 $join .= " INNER JOIN $wpdb->term_relationships";
1056 $join .= $i ? " AS $alias" : '';
1057 $join .= " ON ($this->primary_table.$this->primary_id_column = $alias.object_id)";
1061 $where = "$alias.term_taxonomy_id $operator ($terms)";
1063 } elseif ( 'NOT IN' == $operator ) {
1065 if ( empty( $terms ) ) {
1069 $terms = implode( ',', $terms );
1071 $where = "$this->primary_table.$this->primary_id_column NOT IN (
1073 FROM $wpdb->term_relationships
1074 WHERE term_taxonomy_id IN ($terms)
1077 } elseif ( 'AND' == $operator ) {
1079 if ( empty( $terms ) ) {
1083 $num_terms = count( $terms );
1085 $terms = implode( ',', $terms );
1089 FROM $wpdb->term_relationships
1090 WHERE term_taxonomy_id IN ($terms)
1091 AND object_id = $this->primary_table.$this->primary_id_column
1094 } elseif ( 'NOT EXISTS' === $operator || 'EXISTS' === $operator ) {
1096 $where = $wpdb->prepare( "$operator (
1098 FROM $wpdb->term_relationships
1099 INNER JOIN $wpdb->term_taxonomy
1100 ON $wpdb->term_taxonomy.term_taxonomy_id = $wpdb->term_relationships.term_taxonomy_id
1101 WHERE $wpdb->term_taxonomy.taxonomy = %s
1102 AND $wpdb->term_relationships.object_id = $this->primary_table.$this->primary_id_column
1103 )", $clause['taxonomy'] );
1107 $sql['join'][] = $join;
1108 $sql['where'][] = $where;
1113 * Identify an existing table alias that is compatible with the current query clause.
1115 * We avoid unnecessary table joins by allowing each clause to look for
1116 * an existing table alias that is compatible with the query that it
1119 * An existing alias is compatible if (a) it is a sibling of `$clause`
1120 * (ie, it's under the scope of the same relation), and (b) the combination
1121 * of operator and relation between the clauses allows for a shared table
1122 * join. In the case of {@see WP_Tax_Query}, this only applies to 'IN'
1123 * clauses that are connected by the relation 'OR'.
1128 * @param array $clause Query clause.
1129 * @param array $parent_query Parent query of $clause.
1130 * @return string|bool Table alias if found, otherwise false.
1132 protected function find_compatible_table_alias( $clause, $parent_query ) {
1135 // Sanity check. Only IN queries use the JOIN syntax .
1136 if ( ! isset( $clause['operator'] ) || 'IN' !== $clause['operator'] ) {
1140 // Since we're only checking IN queries, we're only concerned with OR relations.
1141 if ( ! isset( $parent_query['relation'] ) || 'OR' !== $parent_query['relation'] ) {
1145 $compatible_operators = array( 'IN' );
1147 foreach ( $parent_query as $sibling ) {
1148 if ( ! is_array( $sibling ) || ! $this->is_first_order_clause( $sibling ) ) {
1152 if ( empty( $sibling['alias'] ) || empty( $sibling['operator'] ) ) {
1156 // The sibling must both have compatible operator to share its alias.
1157 if ( in_array( strtoupper( $sibling['operator'] ), $compatible_operators ) ) {
1158 $alias = $sibling['alias'];
1167 * Validates a single query.
1172 * @param array &$query The single query.
1174 private function clean_query( &$query ) {
1175 if ( empty( $query['taxonomy'] ) ) {
1176 if ( 'term_taxonomy_id' !== $query['field'] ) {
1177 $query = new WP_Error( 'Invalid taxonomy' );
1181 // so long as there are shared terms, include_children requires that a taxonomy is set
1182 $query['include_children'] = false;
1183 } elseif ( ! taxonomy_exists( $query['taxonomy'] ) ) {
1184 $query = new WP_Error( 'Invalid taxonomy' );
1188 $query['terms'] = array_unique( (array) $query['terms'] );
1190 if ( is_taxonomy_hierarchical( $query['taxonomy'] ) && $query['include_children'] ) {
1191 $this->transform_query( $query, 'term_id' );
1193 if ( is_wp_error( $query ) )
1196 $children = array();
1197 foreach ( $query['terms'] as $term ) {
1198 $children = array_merge( $children, get_term_children( $term, $query['taxonomy'] ) );
1199 $children[] = $term;
1201 $query['terms'] = $children;
1204 $this->transform_query( $query, 'term_taxonomy_id' );
1208 * Transforms a single query, from one field to another.
1212 * @param array &$query The single query.
1213 * @param string $resulting_field The resulting field. Accepts 'slug', 'name', 'term_taxonomy_id',
1214 * or 'term_id'. Default: 'term_id'.
1216 public function transform_query( &$query, $resulting_field ) {
1219 if ( empty( $query['terms'] ) )
1222 if ( $query['field'] == $resulting_field )
1225 $resulting_field = sanitize_key( $resulting_field );
1227 switch ( $query['field'] ) {
1230 foreach ( $query['terms'] as &$term ) {
1232 * 0 is the $term_id parameter. We don't have a term ID yet, but it doesn't
1233 * matter because `sanitize_term_field()` ignores the $term_id param when the
1236 $term = "'" . esc_sql( sanitize_term_field( $query['field'], $term, 0, $query['taxonomy'], 'db' ) ) . "'";
1239 $terms = implode( ",", $query['terms'] );
1241 $terms = $wpdb->get_col( "
1242 SELECT $wpdb->term_taxonomy.$resulting_field
1243 FROM $wpdb->term_taxonomy
1244 INNER JOIN $wpdb->terms USING (term_id)
1245 WHERE taxonomy = '{$query['taxonomy']}'
1246 AND $wpdb->terms.{$query['field']} IN ($terms)
1249 case 'term_taxonomy_id':
1250 $terms = implode( ',', array_map( 'intval', $query['terms'] ) );
1251 $terms = $wpdb->get_col( "
1252 SELECT $resulting_field
1253 FROM $wpdb->term_taxonomy
1254 WHERE term_taxonomy_id IN ($terms)
1258 $terms = implode( ',', array_map( 'intval', $query['terms'] ) );
1259 $terms = $wpdb->get_col( "
1260 SELECT $resulting_field
1261 FROM $wpdb->term_taxonomy
1262 WHERE taxonomy = '{$query['taxonomy']}'
1263 AND term_id IN ($terms)
1267 if ( 'AND' == $query['operator'] && count( $terms ) < count( $query['terms'] ) ) {
1268 $query = new WP_Error( 'Inexistent terms' );
1272 $query['terms'] = $terms;
1273 $query['field'] = $resulting_field;
1278 * Get all Term data from database by Term ID.
1280 * The usage of the get_term function is to apply filters to a term object. It
1281 * is possible to get a term object from the database before applying the
1284 * $term ID must be part of $taxonomy, to get from the database. Failure, might
1285 * be able to be captured by the hooks. Failure would be the same value as $wpdb
1286 * returns for the get_row method.
1288 * There are two hooks, one is specifically for each term, named 'get_term', and
1289 * the second is for the taxonomy name, 'term_$taxonomy'. Both hooks gets the
1290 * term object, and the taxonomy name as parameters. Both hooks are expected to
1291 * return a Term object.
1293 * 'get_term' hook - Takes two parameters the term Object and the taxonomy name.
1294 * Must return term object. Used in get_term() as a catch-all filter for every
1297 * 'get_$taxonomy' hook - Takes two parameters the term Object and the taxonomy
1298 * name. Must return term object. $taxonomy will be the taxonomy name, so for
1299 * example, if 'category', it would be 'get_category' as the filter name. Useful
1300 * for custom taxonomies or plugging into default taxonomies.
1304 * @global wpdb $wpdb WordPress database abstraction object.
1305 * @see sanitize_term_field() The $context param lists the available values for get_term_by() $filter param.
1307 * @param int|object $term If integer, will get from database. If object will apply filters and return $term.
1308 * @param string $taxonomy Taxonomy name that $term is part of.
1309 * @param string $output Constant OBJECT, ARRAY_A, or ARRAY_N
1310 * @param string $filter Optional, default is raw or no WordPress defined filter will applied.
1311 * @return mixed|null|WP_Error Term Row from database. Will return null if $term is empty. If taxonomy does not
1312 * exist then WP_Error will be returned.
1314 function get_term($term, $taxonomy, $output = OBJECT, $filter = 'raw') {
1317 if ( empty($term) ) {
1318 $error = new WP_Error('invalid_term', __('Empty Term'));
1322 if ( ! taxonomy_exists($taxonomy) ) {
1323 $error = new WP_Error('invalid_taxonomy', __('Invalid taxonomy'));
1327 if ( is_object($term) && empty($term->filter) ) {
1328 wp_cache_add( $term->term_id, $term, $taxonomy );
1331 if ( is_object($term) )
1332 $term = $term->term_id;
1333 if ( !$term = (int) $term )
1335 if ( ! $_term = wp_cache_get( $term, $taxonomy ) ) {
1336 $_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) );
1339 wp_cache_add( $term, $_term, $taxonomy );
1348 * @param int|object $_term Term object or ID.
1349 * @param string $taxonomy The taxonomy slug.
1351 $_term = apply_filters( 'get_term', $_term, $taxonomy );
1354 * Filter a taxonomy.
1356 * The dynamic portion of the filter name, `$taxonomy`, refers
1357 * to the taxonomy slug.
1361 * @param int|object $_term Term object or ID.
1362 * @param string $taxonomy The taxonomy slug.
1364 $_term = apply_filters( "get_$taxonomy", $_term, $taxonomy );
1365 $_term = sanitize_term($_term, $taxonomy, $filter);
1367 if ( $output == OBJECT ) {
1369 } elseif ( $output == ARRAY_A ) {
1370 $__term = get_object_vars($_term);
1372 } elseif ( $output == ARRAY_N ) {
1373 $__term = array_values(get_object_vars($_term));
1381 * Get all Term data from database by Term field and data.
1383 * Warning: $value is not escaped for 'name' $field. You must do it yourself, if
1386 * The default $field is 'id', therefore it is possible to also use null for
1387 * field, but not recommended that you do so.
1389 * If $value does not exist, the return value will be false. If $taxonomy exists
1390 * and $field and $value combinations exist, the Term will be returned.
1394 * @global wpdb $wpdb WordPress database abstraction object.
1395 * @see sanitize_term_field() The $context param lists the available values for get_term_by() $filter param.
1397 * @param string $field Either 'slug', 'name', 'id' (term_id), or 'term_taxonomy_id'
1398 * @param string|int $value Search for this term value
1399 * @param string $taxonomy Taxonomy Name
1400 * @param string $output Constant OBJECT, ARRAY_A, or ARRAY_N
1401 * @param string $filter Optional, default is raw or no WordPress defined filter will applied.
1402 * @return mixed Term Row from database. Will return false if $taxonomy does not exist or $term was not found.
1404 function get_term_by($field, $value, $taxonomy, $output = OBJECT, $filter = 'raw') {
1407 if ( ! taxonomy_exists($taxonomy) )
1410 if ( 'slug' == $field ) {
1412 $value = sanitize_title($value);
1413 if ( empty($value) )
1415 } elseif ( 'name' == $field ) {
1416 // Assume already escaped
1417 $value = wp_unslash($value);
1419 } elseif ( 'term_taxonomy_id' == $field ) {
1420 $value = (int) $value;
1421 $field = 'tt.term_taxonomy_id';
1423 $term = get_term( (int) $value, $taxonomy, $output, $filter );
1424 if ( is_wp_error( $term ) )
1429 $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 ) );
1433 wp_cache_add( $term->term_id, $term, $taxonomy );
1435 /** This filter is documented in wp-includes/taxonomy.php */
1436 $term = apply_filters( 'get_term', $term, $taxonomy );
1438 /** This filter is documented in wp-includes/taxonomy.php */
1439 $term = apply_filters( "get_$taxonomy", $term, $taxonomy );
1441 $term = sanitize_term($term, $taxonomy, $filter);
1443 if ( $output == OBJECT ) {
1445 } elseif ( $output == ARRAY_A ) {
1446 return get_object_vars($term);
1447 } elseif ( $output == ARRAY_N ) {
1448 return array_values(get_object_vars($term));
1455 * Merge all term children into a single array of their IDs.
1457 * This recursive function will merge all of the children of $term into the same
1458 * array of term IDs. Only useful for taxonomies which are hierarchical.
1460 * Will return an empty array if $term does not exist in $taxonomy.
1464 * @global wpdb $wpdb WordPress database abstraction object.
1466 * @param string $term_id ID of Term to get children
1467 * @param string $taxonomy Taxonomy Name
1468 * @return array|WP_Error List of Term IDs. WP_Error returned if $taxonomy does not exist
1470 function get_term_children( $term_id, $taxonomy ) {
1471 if ( ! taxonomy_exists($taxonomy) )
1472 return new WP_Error('invalid_taxonomy', __('Invalid taxonomy'));
1474 $term_id = intval( $term_id );
1476 $terms = _get_term_hierarchy($taxonomy);
1478 if ( ! isset($terms[$term_id]) )
1481 $children = $terms[$term_id];
1483 foreach ( (array) $terms[$term_id] as $child ) {
1484 if ( $term_id == $child ) {
1488 if ( isset($terms[$child]) )
1489 $children = array_merge($children, get_term_children($child, $taxonomy));
1496 * Get sanitized Term field.
1498 * Does checks for $term, based on the $taxonomy. The function is for contextual
1499 * reasons and for simplicity of usage. See sanitize_term_field() for more
1504 * @param string $field Term field to fetch
1505 * @param int $term Term ID
1506 * @param string $taxonomy Taxonomy Name
1507 * @param string $context Optional, default is display. Look at sanitize_term_field() for available options.
1508 * @return mixed Will return an empty string if $term is not an object or if $field is not set in $term.
1510 function get_term_field( $field, $term, $taxonomy, $context = 'display' ) {
1511 $term = (int) $term;
1512 $term = get_term( $term, $taxonomy );
1513 if ( is_wp_error($term) )
1516 if ( !is_object($term) )
1519 if ( !isset($term->$field) )
1522 return sanitize_term_field($field, $term->$field, $term->term_id, $taxonomy, $context);
1526 * Sanitizes Term for editing.
1528 * Return value is sanitize_term() and usage is for sanitizing the term for
1529 * editing. Function is for contextual and simplicity.
1533 * @param int|object $id Term ID or Object
1534 * @param string $taxonomy Taxonomy Name
1535 * @return mixed|null|WP_Error Will return empty string if $term is not an object.
1537 function get_term_to_edit( $id, $taxonomy ) {
1538 $term = get_term( $id, $taxonomy );
1540 if ( is_wp_error($term) )
1543 if ( !is_object($term) )
1546 return sanitize_term($term, $taxonomy, 'edit');
1550 * Retrieve the terms in a given taxonomy or list of taxonomies.
1552 * You can fully inject any customizations to the query before it is sent, as
1553 * well as control the output with a filter.
1555 * The 'get_terms' filter will be called when the cache has the term and will
1556 * pass the found term along with the array of $taxonomies and array of $args.
1557 * This filter is also called before the array of terms is passed and will pass
1558 * the array of terms, along with the $taxonomies and $args.
1560 * The 'list_terms_exclusions' filter passes the compiled exclusions along with
1563 * The 'get_terms_orderby' filter passes the ORDER BY clause for the query
1564 * along with the $args array.
1567 * @since 4.2.0 Introduced 'name' and 'childless' parameters.
1569 * @global wpdb $wpdb WordPress database abstraction object.
1571 * @param string|array $taxonomies Taxonomy name or list of Taxonomy names.
1572 * @param array|string $args {
1573 * Optional. Array or string of arguments to get terms.
1575 * @type string $orderby Field(s) to order terms by. Accepts term fields ('name', 'slug',
1576 * 'term_group', 'term_id', 'id', 'description'), 'count' for term
1577 * taxonomy count, 'include' to match the 'order' of the $include param,
1578 * or 'none' to skip ORDER BY. Defaults to 'name'.
1579 * @type string $order Whether to order terms in ascending or descending order.
1580 * Accepts 'ASC' (ascending) or 'DESC' (descending).
1582 * @type bool|int $hide_empty Whether to hide terms not assigned to any posts. Accepts
1583 * 1|true or 0|false. Default 1|true.
1584 * @type array|string $include Array or comma/space-separated string of term ids to include.
1585 * Default empty array.
1586 * @type array|string $exclude Array or comma/space-separated string of term ids to exclude.
1587 * If $include is non-empty, $exclude is ignored.
1588 * Default empty array.
1589 * @type array|string $exclude_tree Array or comma/space-separated string of term ids to exclude
1590 * along with all of their descendant terms. If $include is
1591 * non-empty, $exclude_tree is ignored. Default empty array.
1592 * @type int|string $number Maximum number of terms to return. Accepts ''|0 (all) or any
1593 * positive number. Default ''|0 (all).
1594 * @type int $offset The number by which to offset the terms query. Default empty.
1595 * @type string $fields Term fields to query for. Accepts 'all' (returns an array of
1596 * term objects), 'ids' or 'names' (returns an array of integers
1597 * or strings, respectively. Default 'all'.
1598 * @type string|array $name Optional. Name or array of names to return term(s) for. Default empty.
1599 * @type string|array $slug Optional. Slug or array of slugs to return term(s) for. Default empty.
1600 * @type bool $hierarchical Whether to include terms that have non-empty descendants (even
1601 * if $hide_empty is set to true). Default true.
1602 * @type string $search Search criteria to match terms. Will be SQL-formatted with
1603 * wildcards before and after. Default empty.
1604 * @type string $name__like Retrieve terms with criteria by which a term is LIKE $name__like.
1606 * @type string $description__like Retrieve terms where the description is LIKE $description__like.
1608 * @type bool $pad_counts Whether to pad the quantity of a term's children in the quantity
1609 * of each term's "count" object variable. Default false.
1610 * @type string $get Whether to return terms regardless of ancestry or whether the terms
1611 * are empty. Accepts 'all' or empty (disabled). Default empty.
1612 * @type int $child_of Term ID to retrieve child terms of. If multiple taxonomies
1613 * are passed, $child_of is ignored. Default 0.
1614 * @type int|string $parent Parent term ID to retrieve direct-child terms of. Default empty.
1615 * @type bool $childless True to limit results to terms that have no children. This parameter has
1616 * no effect on non-hierarchical taxonomies. Default false.
1617 * @type string $cache_domain Unique cache key to be produced when this query is stored in an
1618 * object cache. Default is 'core'.
1620 * @return array|WP_Error List of Term Objects and their children. Will return WP_Error, if any of $taxonomies
1623 function get_terms( $taxonomies, $args = '' ) {
1625 $empty_array = array();
1627 $single_taxonomy = ! is_array( $taxonomies ) || 1 === count( $taxonomies );
1628 if ( ! is_array( $taxonomies ) ) {
1629 $taxonomies = array( $taxonomies );
1632 foreach ( $taxonomies as $taxonomy ) {
1633 if ( ! taxonomy_exists($taxonomy) ) {
1634 $error = new WP_Error('invalid_taxonomy', __('Invalid taxonomy'));
1639 $defaults = array('orderby' => 'name', 'order' => 'ASC',
1640 'hide_empty' => true, 'exclude' => array(), 'exclude_tree' => array(), 'include' => array(),
1641 'number' => '', 'fields' => 'all', 'name' => '', 'slug' => '', 'parent' => '', 'childless' => false,
1642 'hierarchical' => true, 'child_of' => 0, 'get' => '', 'name__like' => '', 'description__like' => '',
1643 'pad_counts' => false, 'offset' => '', 'search' => '', 'cache_domain' => 'core' );
1644 $args = wp_parse_args( $args, $defaults );
1645 $args['number'] = absint( $args['number'] );
1646 $args['offset'] = absint( $args['offset'] );
1648 // Save queries by not crawling the tree in the case of multiple taxes or a flat tax.
1649 $has_hierarchical_tax = false;
1650 foreach ( $taxonomies as $_tax ) {
1651 if ( is_taxonomy_hierarchical( $_tax ) ) {
1652 $has_hierarchical_tax = true;
1656 if ( ! $has_hierarchical_tax ) {
1657 $args['hierarchical'] = false;
1658 $args['pad_counts'] = false;
1661 // 'parent' overrides 'child_of'.
1662 if ( 0 < intval( $args['parent'] ) ) {
1663 $args['child_of'] = false;
1666 if ( 'all' == $args['get'] ) {
1667 $args['childless'] = false;
1668 $args['child_of'] = 0;
1669 $args['hide_empty'] = 0;
1670 $args['hierarchical'] = false;
1671 $args['pad_counts'] = false;
1675 * Filter the terms query arguments.
1679 * @param array $args An array of arguments.
1680 * @param array $taxonomies An array of taxonomies.
1682 $args = apply_filters( 'get_terms_args', $args, $taxonomies );
1684 // Avoid the query if the queried parent/child_of term has no descendants.
1685 $child_of = $args['child_of'];
1686 $parent = $args['parent'];
1689 $_parent = $child_of;
1690 } elseif ( $parent ) {
1697 $in_hierarchy = false;
1698 foreach ( $taxonomies as $_tax ) {
1699 $hierarchy = _get_term_hierarchy( $_tax );
1701 if ( isset( $hierarchy[ $_parent ] ) ) {
1702 $in_hierarchy = true;
1706 if ( ! $in_hierarchy ) {
1707 return $empty_array;
1711 // $args can be whatever, only use the args defined in defaults to compute the key
1712 $filter_key = ( has_filter('list_terms_exclusions') ) ? serialize($GLOBALS['wp_filter']['list_terms_exclusions']) : '';
1713 $key = md5( serialize( wp_array_slice_assoc( $args, array_keys( $defaults ) ) ) . serialize( $taxonomies ) . $filter_key );
1714 $last_changed = wp_cache_get( 'last_changed', 'terms' );
1715 if ( ! $last_changed ) {
1716 $last_changed = microtime();
1717 wp_cache_set( 'last_changed', $last_changed, 'terms' );
1719 $cache_key = "get_terms:$key:$last_changed";
1720 $cache = wp_cache_get( $cache_key, 'terms' );
1721 if ( false !== $cache ) {
1724 * Filter the given taxonomy's terms cache.
1728 * @param array $cache Cached array of terms for the given taxonomy.
1729 * @param array $taxonomies An array of taxonomies.
1730 * @param array $args An array of arguments to get terms.
1732 $cache = apply_filters( 'get_terms', $cache, $taxonomies, $args );
1736 $_orderby = strtolower( $args['orderby'] );
1737 if ( 'count' == $_orderby ) {
1738 $orderby = 'tt.count';
1739 } elseif ( 'name' == $_orderby ) {
1740 $orderby = 't.name';
1741 } elseif ( 'slug' == $_orderby ) {
1742 $orderby = 't.slug';
1743 } elseif ( 'include' == $_orderby && ! empty( $args['include'] ) ) {
1744 $include = implode( ',', array_map( 'absint', $args['include'] ) );
1745 $orderby = "FIELD( t.term_id, $include )";
1746 } elseif ( 'term_group' == $_orderby ) {
1747 $orderby = 't.term_group';
1748 } elseif ( 'description' == $_orderby ) {
1749 $orderby = 'tt.description';
1750 } elseif ( 'none' == $_orderby ) {
1752 } elseif ( empty($_orderby) || 'id' == $_orderby ) {
1753 $orderby = 't.term_id';
1755 $orderby = 't.name';
1758 * Filter the ORDERBY clause of the terms query.
1762 * @param string $orderby ORDERBY clause of the terms query.
1763 * @param array $args An array of terms query arguments.
1764 * @param array $taxonomies An array of taxonomies.
1766 $orderby = apply_filters( 'get_terms_orderby', $orderby, $args, $taxonomies );
1768 $order = strtoupper( $args['order'] );
1769 if ( ! empty( $orderby ) ) {
1770 $orderby = "ORDER BY $orderby";
1775 if ( '' !== $order && ! in_array( $order, array( 'ASC', 'DESC' ) ) ) {
1779 $where = "tt.taxonomy IN ('" . implode("', '", $taxonomies) . "')";
1781 $exclude = $args['exclude'];
1782 $exclude_tree = $args['exclude_tree'];
1783 $include = $args['include'];
1786 if ( ! empty( $include ) ) {
1789 $inclusions = implode( ',', wp_parse_id_list( $include ) );
1792 if ( ! empty( $inclusions ) ) {
1793 $inclusions = ' AND t.term_id IN ( ' . $inclusions . ' )';
1794 $where .= $inclusions;
1797 $exclusions = array();
1798 if ( ! empty( $exclude_tree ) ) {
1799 $exclude_tree = wp_parse_id_list( $exclude_tree );
1800 $excluded_children = $exclude_tree;
1801 foreach ( $exclude_tree as $extrunk ) {
1802 $excluded_children = array_merge(
1804 (array) get_terms( $taxonomies[0], array( 'child_of' => intval( $extrunk ), 'fields' => 'ids', 'hide_empty' => 0 ) )
1807 $exclusions = array_merge( $excluded_children, $exclusions );
1810 if ( ! empty( $exclude ) ) {
1811 $exclusions = array_merge( wp_parse_id_list( $exclude ), $exclusions );
1814 // 'childless' terms are those without an entry in the flattened term hierarchy.
1815 $childless = (bool) $args['childless'];
1817 foreach ( $taxonomies as $_tax ) {
1818 $term_hierarchy = _get_term_hierarchy( $_tax );
1819 $exclusions = array_merge( array_keys( $term_hierarchy ), $exclusions );
1823 if ( ! empty( $exclusions ) ) {
1824 $exclusions = ' AND t.term_id NOT IN (' . implode( ',', array_map( 'intval', $exclusions ) ) . ')';
1830 * Filter the terms to exclude from the terms query.
1834 * @param string $exclusions NOT IN clause of the terms query.
1835 * @param array $args An array of terms query arguments.
1836 * @param array $taxonomies An array of taxonomies.
1838 $exclusions = apply_filters( 'list_terms_exclusions', $exclusions, $args, $taxonomies );
1840 if ( ! empty( $exclusions ) ) {
1841 $where .= $exclusions;
1844 if ( ! empty( $args['name'] ) ) {
1845 if ( is_array( $args['name'] ) ) {
1846 $name = array_map( 'sanitize_text_field', $args['name'] );
1847 $where .= " AND t.name IN ('" . implode( "', '", array_map( 'esc_sql', $name ) ) . "')";
1849 $name = sanitize_text_field( $args['name'] );
1850 $where .= $wpdb->prepare( " AND t.name = %s", $name );
1854 if ( ! empty( $args['slug'] ) ) {
1855 if ( is_array( $args['slug'] ) ) {
1856 $slug = array_map( 'sanitize_title', $args['slug'] );
1857 $where .= " AND t.slug IN ('" . implode( "', '", $slug ) . "')";
1859 $slug = sanitize_title( $args['slug'] );
1860 $where .= " AND t.slug = '$slug'";
1864 if ( ! empty( $args['name__like'] ) ) {
1865 $where .= $wpdb->prepare( " AND t.name LIKE %s", '%' . $wpdb->esc_like( $args['name__like'] ) . '%' );
1868 if ( ! empty( $args['description__like'] ) ) {
1869 $where .= $wpdb->prepare( " AND tt.description LIKE %s", '%' . $wpdb->esc_like( $args['description__like'] ) . '%' );
1872 if ( '' !== $parent ) {
1873 $parent = (int) $parent;
1874 $where .= " AND tt.parent = '$parent'";
1877 $hierarchical = $args['hierarchical'];
1878 if ( 'count' == $args['fields'] ) {
1879 $hierarchical = false;
1881 if ( $args['hide_empty'] && !$hierarchical ) {
1882 $where .= ' AND tt.count > 0';
1885 $number = $args['number'];
1886 $offset = $args['offset'];
1888 // don't limit the query results when we have to descend the family tree
1889 if ( $number && ! $hierarchical && ! $child_of && '' === $parent ) {
1891 $limits = 'LIMIT ' . $offset . ',' . $number;
1893 $limits = 'LIMIT ' . $number;
1899 if ( ! empty( $args['search'] ) ) {
1900 $like = '%' . $wpdb->esc_like( $args['search'] ) . '%';
1901 $where .= $wpdb->prepare( ' AND ((t.name LIKE %s) OR (t.slug LIKE %s))', $like, $like );
1905 switch ( $args['fields'] ) {
1907 $selects = array( 't.*', 'tt.*' );
1911 $selects = array( 't.term_id', 'tt.parent', 'tt.count', 'tt.taxonomy' );
1914 $selects = array( 't.term_id', 'tt.parent', 'tt.count', 't.name', 'tt.taxonomy' );
1919 $selects = array( 'COUNT(*)' );
1922 $selects = array( 't.term_id', 't.name', 'tt.count', 'tt.taxonomy' );
1925 $selects = array( 't.term_id', 't.slug', 'tt.count', 'tt.taxonomy' );
1929 $_fields = $args['fields'];
1932 * Filter the fields to select in the terms query.
1934 * Field lists modified using this filter will only modify the term fields returned
1935 * by the function when the `$fields` parameter set to 'count' or 'all'. In all other
1936 * cases, the term fields in the results array will be determined by the `$fields`
1939 * Use of this filter can result in unpredictable behavior, and is not recommended.
1943 * @param array $selects An array of fields to select for the terms query.
1944 * @param array $args An array of term query arguments.
1945 * @param array $taxonomies An array of taxonomies.
1947 $fields = implode( ', ', apply_filters( 'get_terms_fields', $selects, $args, $taxonomies ) );
1949 $join = "INNER JOIN $wpdb->term_taxonomy AS tt ON t.term_id = tt.term_id";
1951 $pieces = array( 'fields', 'join', 'where', 'orderby', 'order', 'limits' );
1954 * Filter the terms query SQL clauses.
1958 * @param array $pieces Terms query SQL clauses.
1959 * @param array $taxonomies An array of taxonomies.
1960 * @param array $args An array of terms query arguments.
1962 $clauses = apply_filters( 'terms_clauses', compact( $pieces ), $taxonomies, $args );
1963 $fields = isset( $clauses[ 'fields' ] ) ? $clauses[ 'fields' ] : '';
1964 $join = isset( $clauses[ 'join' ] ) ? $clauses[ 'join' ] : '';
1965 $where = isset( $clauses[ 'where' ] ) ? $clauses[ 'where' ] : '';
1966 $orderby = isset( $clauses[ 'orderby' ] ) ? $clauses[ 'orderby' ] : '';
1967 $order = isset( $clauses[ 'order' ] ) ? $clauses[ 'order' ] : '';
1968 $limits = isset( $clauses[ 'limits' ] ) ? $clauses[ 'limits' ] : '';
1970 $query = "SELECT $fields FROM $wpdb->terms AS t $join WHERE $where $orderby $order $limits";
1972 if ( 'count' == $_fields ) {
1973 $term_count = $wpdb->get_var($query);
1977 $terms = $wpdb->get_results($query);
1978 if ( 'all' == $_fields ) {
1979 update_term_cache( $terms );
1982 if ( empty($terms) ) {
1983 wp_cache_add( $cache_key, array(), 'terms', DAY_IN_SECONDS );
1985 /** This filter is documented in wp-includes/taxonomy.php */
1986 $terms = apply_filters( 'get_terms', array(), $taxonomies, $args );
1991 foreach ( $taxonomies as $_tax ) {
1992 $children = _get_term_hierarchy( $_tax );
1993 if ( ! empty( $children ) ) {
1994 $terms = _get_term_children( $child_of, $terms, $_tax );
1999 // Update term counts to include children.
2000 if ( $args['pad_counts'] && 'all' == $_fields ) {
2001 foreach ( $taxonomies as $_tax ) {
2002 _pad_term_counts( $terms, $_tax );
2006 // Make sure we show empty categories that have children.
2007 if ( $hierarchical && $args['hide_empty'] && is_array( $terms ) ) {
2008 foreach ( $terms as $k => $term ) {
2009 if ( ! $term->count ) {
2010 $children = get_term_children( $term->term_id, $term->taxonomy );
2011 if ( is_array( $children ) ) {
2012 foreach ( $children as $child_id ) {
2013 $child = get_term( $child_id, $term->taxonomy );
2014 if ( $child->count ) {
2020 // It really is empty
2027 if ( 'id=>parent' == $_fields ) {
2028 foreach ( $terms as $term ) {
2029 $_terms[ $term->term_id ] = $term->parent;
2031 } elseif ( 'ids' == $_fields ) {
2032 foreach ( $terms as $term ) {
2033 $_terms[] = $term->term_id;
2035 } elseif ( 'names' == $_fields ) {
2036 foreach ( $terms as $term ) {
2037 $_terms[] = $term->name;
2039 } elseif ( 'id=>name' == $_fields ) {
2040 foreach ( $terms as $term ) {
2041 $_terms[ $term->term_id ] = $term->name;
2043 } elseif ( 'id=>slug' == $_fields ) {
2044 foreach ( $terms as $term ) {
2045 $_terms[ $term->term_id ] = $term->slug;
2049 if ( ! empty( $_terms ) ) {
2053 if ( $number && is_array( $terms ) && count( $terms ) > $number ) {
2054 $terms = array_slice( $terms, $offset, $number );
2057 wp_cache_add( $cache_key, $terms, 'terms', DAY_IN_SECONDS );
2059 /** This filter is documented in wp-includes/taxonomy */
2060 $terms = apply_filters( 'get_terms', $terms, $taxonomies, $args );
2065 * Check if Term exists.
2067 * Formerly is_term(), introduced in 2.3.0.
2071 * @global wpdb $wpdb WordPress database abstraction object.
2073 * @param int|string $term The term to check
2074 * @param string $taxonomy The taxonomy name to use
2075 * @param int $parent Optional. ID of parent term under which to confine the exists search.
2076 * @return mixed Returns null if the term does not exist. Returns the term ID
2077 * if no taxonomy is specified and the term ID exists. Returns
2078 * an array of the term ID and the term taxonomy ID the taxonomy
2079 * is specified and the pairing exists.
2081 function term_exists( $term, $taxonomy = '', $parent = null ) {
2084 $select = "SELECT term_id FROM $wpdb->terms as t WHERE ";
2085 $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 ";
2087 if ( is_int($term) ) {
2090 $where = 't.term_id = %d';
2091 if ( !empty($taxonomy) )
2092 return $wpdb->get_row( $wpdb->prepare( $tax_select . $where . " AND tt.taxonomy = %s", $term, $taxonomy ), ARRAY_A );
2094 return $wpdb->get_var( $wpdb->prepare( $select . $where, $term ) );
2097 $term = trim( wp_unslash( $term ) );
2098 $slug = sanitize_title( $term );
2100 $where = 't.slug = %s';
2101 $else_where = 't.name = %s';
2102 $where_fields = array($slug);
2103 $else_where_fields = array($term);
2104 $orderby = 'ORDER BY t.term_id ASC';
2106 if ( !empty($taxonomy) ) {
2107 if ( is_numeric( $parent ) ) {
2108 $parent = (int) $parent;
2109 $where_fields[] = $parent;
2110 $else_where_fields[] = $parent;
2111 $where .= ' AND tt.parent = %d';
2112 $else_where .= ' AND tt.parent = %d';
2115 $where_fields[] = $taxonomy;
2116 $else_where_fields[] = $taxonomy;
2118 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) )
2121 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);
2124 if ( $result = $wpdb->get_var( $wpdb->prepare("SELECT term_id FROM $wpdb->terms as t WHERE $where $orderby $limit", $where_fields) ) )
2127 return $wpdb->get_var( $wpdb->prepare("SELECT term_id FROM $wpdb->terms as t WHERE $else_where $orderby $limit", $else_where_fields) );
2131 * Check if a term is an ancestor of another term.
2133 * You can use either an id or the term object for both parameters.
2137 * @param int|object $term1 ID or object to check if this is the parent term.
2138 * @param int|object $term2 The child term.
2139 * @param string $taxonomy Taxonomy name that $term1 and $term2 belong to.
2140 * @return bool Whether $term2 is child of $term1
2142 function term_is_ancestor_of( $term1, $term2, $taxonomy ) {
2143 if ( ! isset( $term1->term_id ) )
2144 $term1 = get_term( $term1, $taxonomy );
2145 if ( ! isset( $term2->parent ) )
2146 $term2 = get_term( $term2, $taxonomy );
2148 if ( empty( $term1->term_id ) || empty( $term2->parent ) )
2150 if ( $term2->parent == $term1->term_id )
2153 return term_is_ancestor_of( $term1, get_term( $term2->parent, $taxonomy ), $taxonomy );
2157 * Sanitize Term all fields.
2159 * Relies on sanitize_term_field() to sanitize the term. The difference is that
2160 * this function will sanitize <strong>all</strong> fields. The context is based
2161 * on sanitize_term_field().
2163 * The $term is expected to be either an array or an object.
2167 * @param array|object $term The term to check
2168 * @param string $taxonomy The taxonomy name to use
2169 * @param string $context Default is 'display'.
2170 * @return array|object Term with all fields sanitized
2172 function sanitize_term($term, $taxonomy, $context = 'display') {
2174 $fields = array( 'term_id', 'name', 'description', 'slug', 'count', 'parent', 'term_group', 'term_taxonomy_id', 'object_id' );
2176 $do_object = is_object( $term );
2178 $term_id = $do_object ? $term->term_id : (isset($term['term_id']) ? $term['term_id'] : 0);
2180 foreach ( (array) $fields as $field ) {
2182 if ( isset($term->$field) )
2183 $term->$field = sanitize_term_field($field, $term->$field, $term_id, $taxonomy, $context);
2185 if ( isset($term[$field]) )
2186 $term[$field] = sanitize_term_field($field, $term[$field], $term_id, $taxonomy, $context);
2191 $term->filter = $context;
2193 $term['filter'] = $context;
2199 * Cleanse the field value in the term based on the context.
2201 * Passing a term field value through the function should be assumed to have
2202 * cleansed the value for whatever context the term field is going to be used.
2204 * If no context or an unsupported context is given, then default filters will
2207 * There are enough filters for each context to support a custom filtering
2208 * without creating your own filter function. Simply create a function that
2209 * hooks into the filter you need.
2213 * @global wpdb $wpdb WordPress database abstraction object.
2215 * @param string $field Term field to sanitize
2216 * @param string $value Search for this term value
2217 * @param int $term_id Term ID
2218 * @param string $taxonomy Taxonomy Name
2219 * @param string $context Either edit, db, display, attribute, or js.
2220 * @return mixed sanitized field
2222 function sanitize_term_field($field, $value, $term_id, $taxonomy, $context) {
2223 $int_fields = array( 'parent', 'term_id', 'count', 'term_group', 'term_taxonomy_id', 'object_id' );
2224 if ( in_array( $field, $int_fields ) ) {
2225 $value = (int) $value;
2230 if ( 'raw' == $context )
2233 if ( 'edit' == $context ) {
2236 * Filter a term field to edit before it is sanitized.
2238 * The dynamic portion of the filter name, `$field`, refers to the term field.
2242 * @param mixed $value Value of the term field.
2243 * @param int $term_id Term ID.
2244 * @param string $taxonomy Taxonomy slug.
2246 $value = apply_filters( "edit_term_{$field}", $value, $term_id, $taxonomy );
2249 * Filter the taxonomy field to edit before it is sanitized.
2251 * The dynamic portions of the filter name, `$taxonomy` and `$field`, refer
2252 * to the taxonomy slug and taxonomy field, respectively.
2256 * @param mixed $value Value of the taxonomy field to edit.
2257 * @param int $term_id Term ID.
2259 $value = apply_filters( "edit_{$taxonomy}_{$field}", $value, $term_id );
2260 if ( 'description' == $field )
2261 $value = esc_html($value); // textarea_escaped
2263 $value = esc_attr($value);
2264 } elseif ( 'db' == $context ) {
2267 * Filter a term field value before it is sanitized.
2269 * The dynamic portion of the filter name, `$field`, refers to the term field.
2273 * @param mixed $value Value of the term field.
2274 * @param string $taxonomy Taxonomy slug.
2276 $value = apply_filters( "pre_term_{$field}", $value, $taxonomy );
2279 * Filter a taxonomy field before it is sanitized.
2281 * The dynamic portions of the filter name, `$taxonomy` and `$field`, refer
2282 * to the taxonomy slug and field name, respectively.
2286 * @param mixed $value Value of the taxonomy field.
2288 $value = apply_filters( "pre_{$taxonomy}_{$field}", $value );
2289 // Back compat filters
2290 if ( 'slug' == $field ) {
2292 * Filter the category nicename before it is sanitized.
2294 * Use the pre_{$taxonomy}_{$field} hook instead.
2298 * @param string $value The category nicename.
2300 $value = apply_filters( 'pre_category_nicename', $value );
2303 } elseif ( 'rss' == $context ) {
2306 * Filter the term field for use in RSS.
2308 * The dynamic portion of the filter name, `$field`, refers to the term field.
2312 * @param mixed $value Value of the term field.
2313 * @param string $taxonomy Taxonomy slug.
2315 $value = apply_filters( "term_{$field}_rss", $value, $taxonomy );
2318 * Filter the taxonomy field for use in RSS.
2320 * The dynamic portions of the hook name, `$taxonomy`, and $field, refer
2321 * to the taxonomy slug and field name, respectively.
2325 * @param mixed $value Value of the taxonomy field.
2327 $value = apply_filters( "{$taxonomy}_{$field}_rss", $value );
2329 // Use display filters by default.
2332 * Filter the term field sanitized for display.
2334 * The dynamic portion of the filter name, `$field`, refers to the term field name.
2338 * @param mixed $value Value of the term field.
2339 * @param int $term_id Term ID.
2340 * @param string $taxonomy Taxonomy slug.
2341 * @param string $context Context to retrieve the term field value.
2343 $value = apply_filters( "term_{$field}", $value, $term_id, $taxonomy, $context );
2346 * Filter the taxonomy field sanitized for display.
2348 * The dynamic portions of the filter name, `$taxonomy`, and $field, refer
2349 * to the taxonomy slug and taxonomy field, respectively.
2353 * @param mixed $value Value of the taxonomy field.
2354 * @param int $term_id Term ID.
2355 * @param string $context Context to retrieve the taxonomy field value.
2357 $value = apply_filters( "{$taxonomy}_{$field}", $value, $term_id, $context );
2360 if ( 'attribute' == $context ) {
2361 $value = esc_attr($value);
2362 } elseif ( 'js' == $context ) {
2363 $value = esc_js($value);
2369 * Count how many terms are in Taxonomy.
2371 * Default $args is 'hide_empty' which can be 'hide_empty=true' or array('hide_empty' => true).
2375 * @param string $taxonomy Taxonomy name
2376 * @param array|string $args Overwrite defaults. See get_terms()
2377 * @return int|WP_Error How many terms are in $taxonomy. WP_Error if $taxonomy does not exist.
2379 function wp_count_terms( $taxonomy, $args = array() ) {
2380 $defaults = array('hide_empty' => false);
2381 $args = wp_parse_args($args, $defaults);
2383 // backwards compatibility
2384 if ( isset($args['ignore_empty']) ) {
2385 $args['hide_empty'] = $args['ignore_empty'];
2386 unset($args['ignore_empty']);
2389 $args['fields'] = 'count';
2391 return get_terms($taxonomy, $args);
2395 * Will unlink the object from the taxonomy or taxonomies.
2397 * Will remove all relationships between the object and any terms in
2398 * a particular taxonomy or taxonomies. Does not remove the term or
2403 * @param int $object_id The term Object Id that refers to the term
2404 * @param string|array $taxonomies List of Taxonomy Names or single Taxonomy name.
2406 function wp_delete_object_term_relationships( $object_id, $taxonomies ) {
2407 $object_id = (int) $object_id;
2409 if ( !is_array($taxonomies) )
2410 $taxonomies = array($taxonomies);
2412 foreach ( (array) $taxonomies as $taxonomy ) {
2413 $term_ids = wp_get_object_terms( $object_id, $taxonomy, array( 'fields' => 'ids' ) );
2414 $term_ids = array_map( 'intval', $term_ids );
2415 wp_remove_object_terms( $object_id, $term_ids, $taxonomy );
2420 * Removes a term from the database.
2422 * If the term is a parent of other terms, then the children will be updated to
2423 * that term's parent.
2425 * The $args 'default' will only override the terms found, if there is only one
2426 * term found. Any other and the found terms are used.
2428 * The $args 'force_default' will force the term supplied as default to be
2429 * assigned even if the object was not going to be termless
2433 * @global wpdb $wpdb WordPress database abstraction object.
2435 * @param int $term Term ID
2436 * @param string $taxonomy Taxonomy Name
2437 * @param array|string $args Optional. Change 'default' term id and override found term ids.
2438 * @return bool|WP_Error Returns false if not term; true if completes delete action.
2440 function wp_delete_term( $term, $taxonomy, $args = array() ) {
2443 $term = (int) $term;
2445 if ( ! $ids = term_exists($term, $taxonomy) )
2447 if ( is_wp_error( $ids ) )
2450 $tt_id = $ids['term_taxonomy_id'];
2452 $defaults = array();
2454 if ( 'category' == $taxonomy ) {
2455 $defaults['default'] = get_option( 'default_category' );
2456 if ( $defaults['default'] == $term )
2457 return 0; // Don't delete the default category
2460 $args = wp_parse_args($args, $defaults);
2462 if ( isset( $args['default'] ) ) {
2463 $default = (int) $args['default'];
2464 if ( ! term_exists( $default, $taxonomy ) ) {
2469 if ( isset( $args['force_default'] ) ) {
2470 $force_default = $args['force_default'];
2474 * Fires when deleting a term, before any modifications are made to posts or terms.
2478 * @param int $term Term ID.
2479 * @param string $taxonomy Taxonomy Name.
2481 do_action( 'pre_delete_term', $term, $taxonomy );
2483 // Update children to point to new parent
2484 if ( is_taxonomy_hierarchical($taxonomy) ) {
2485 $term_obj = get_term($term, $taxonomy);
2486 if ( is_wp_error( $term_obj ) )
2488 $parent = $term_obj->parent;
2490 $edit_ids = $wpdb->get_results( "SELECT term_id, term_taxonomy_id FROM $wpdb->term_taxonomy WHERE `parent` = " . (int)$term_obj->term_id );
2491 $edit_tt_ids = wp_list_pluck( $edit_ids, 'term_taxonomy_id' );
2494 * Fires immediately before a term to delete's children are reassigned a parent.
2498 * @param array $edit_tt_ids An array of term taxonomy IDs for the given term.
2500 do_action( 'edit_term_taxonomies', $edit_tt_ids );
2501 $wpdb->update( $wpdb->term_taxonomy, compact( 'parent' ), array( 'parent' => $term_obj->term_id) + compact( 'taxonomy' ) );
2503 // Clean the cache for all child terms.
2504 $edit_term_ids = wp_list_pluck( $edit_ids, 'term_id' );
2505 clean_term_cache( $edit_term_ids, $taxonomy );
2508 * Fires immediately after a term to delete's children are reassigned a parent.
2512 * @param array $edit_tt_ids An array of term taxonomy IDs for the given term.
2514 do_action( 'edited_term_taxonomies', $edit_tt_ids );
2517 $objects = $wpdb->get_col( $wpdb->prepare( "SELECT object_id FROM $wpdb->term_relationships WHERE term_taxonomy_id = %d", $tt_id ) );
2519 foreach ( (array) $objects as $object ) {
2520 $terms = wp_get_object_terms($object, $taxonomy, array('fields' => 'ids', 'orderby' => 'none'));
2521 if ( 1 == count($terms) && isset($default) ) {
2522 $terms = array($default);
2524 $terms = array_diff($terms, array($term));
2525 if (isset($default) && isset($force_default) && $force_default)
2526 $terms = array_merge($terms, array($default));
2528 $terms = array_map('intval', $terms);
2529 wp_set_object_terms($object, $terms, $taxonomy);
2532 // Clean the relationship caches for all object types using this term
2533 $tax_object = get_taxonomy( $taxonomy );
2534 foreach ( $tax_object->object_type as $object_type )
2535 clean_object_term_cache( $objects, $object_type );
2537 // Get the object before deletion so we can pass to actions below
2538 $deleted_term = get_term( $term, $taxonomy );
2541 * Fires immediately before a term taxonomy ID is deleted.
2545 * @param int $tt_id Term taxonomy ID.
2547 do_action( 'delete_term_taxonomy', $tt_id );
2548 $wpdb->delete( $wpdb->term_taxonomy, array( 'term_taxonomy_id' => $tt_id ) );
2551 * Fires immediately after a term taxonomy ID is deleted.
2555 * @param int $tt_id Term taxonomy ID.
2557 do_action( 'deleted_term_taxonomy', $tt_id );
2559 // Delete the term if no taxonomies use it.
2560 if ( !$wpdb->get_var( $wpdb->prepare( "SELECT COUNT(*) FROM $wpdb->term_taxonomy WHERE term_id = %d", $term) ) )
2561 $wpdb->delete( $wpdb->terms, array( 'term_id' => $term ) );
2563 clean_term_cache($term, $taxonomy);
2566 * Fires after a term is deleted from the database and the cache is cleaned.
2570 * @param int $term Term ID.
2571 * @param int $tt_id Term taxonomy ID.
2572 * @param string $taxonomy Taxonomy slug.
2573 * @param mixed $deleted_term Copy of the already-deleted term, in the form specified
2574 * by the parent function. WP_Error otherwise.
2576 do_action( 'delete_term', $term, $tt_id, $taxonomy, $deleted_term );
2579 * Fires after a term in a specific taxonomy is deleted.
2581 * The dynamic portion of the hook name, `$taxonomy`, refers to the specific
2582 * taxonomy the term belonged to.
2586 * @param int $term Term ID.
2587 * @param int $tt_id Term taxonomy ID.
2588 * @param mixed $deleted_term Copy of the already-deleted term, in the form specified
2589 * by the parent function. {@see WP_Error} otherwise.
2591 do_action( "delete_$taxonomy", $term, $tt_id, $deleted_term );
2597 * Deletes one existing category.
2601 * @param int $cat_ID
2602 * @return mixed Returns true if completes delete action; false if term doesn't exist;
2603 * Zero on attempted deletion of default Category; WP_Error object is also a possibility.
2605 function wp_delete_category( $cat_ID ) {
2606 return wp_delete_term( $cat_ID, 'category' );
2610 * Retrieves the terms associated with the given object(s), in the supplied taxonomies.
2613 * @since 4.2.0 Added support for 'taxonomy', 'parent', and 'term_taxonomy_id' values of `$orderby`.
2614 * Introduced `$parent` argument.
2616 * @global wpdb $wpdb WordPress database abstraction object.
2618 * @param int|array $object_ids The ID(s) of the object(s) to retrieve.
2619 * @param string|array $taxonomies The taxonomies to retrieve terms from.
2620 * @param array|string $args {
2621 * Array of arguments.
2622 * @type string $orderby Field by which results should be sorted. Accepts 'name', 'count', 'slug', 'term_group',
2623 * 'term_order', 'taxonomy', 'parent', or 'term_taxonomy_id'. Default 'name'.
2624 * @type string $order Sort order. Accepts 'ASC' or 'DESC'. Default 'ASC'.
2625 * @type string $fields Fields to return for matched terms. Accepts 'all', 'ids', 'names', and
2626 * 'all_with_object_id'. Note that 'all' or 'all_with_object_id' will result in an array of
2627 * term objects being returned, 'ids' will return an array of integers, and 'names' an array
2629 * @type int $parent Optional. Limit results to the direct children of a given term ID.
2631 * @return array|WP_Error The requested term data or empty array if no terms found.
2632 * WP_Error if any of the $taxonomies don't exist.
2634 function wp_get_object_terms($object_ids, $taxonomies, $args = array()) {
2637 if ( empty( $object_ids ) || empty( $taxonomies ) )
2640 if ( !is_array($taxonomies) )
2641 $taxonomies = array($taxonomies);
2643 foreach ( $taxonomies as $taxonomy ) {
2644 if ( ! taxonomy_exists($taxonomy) )
2645 return new WP_Error('invalid_taxonomy', __('Invalid taxonomy'));
2648 if ( !is_array($object_ids) )
2649 $object_ids = array($object_ids);
2650 $object_ids = array_map('intval', $object_ids);
2653 'orderby' => 'name',
2658 $args = wp_parse_args( $args, $defaults );
2661 if ( count($taxonomies) > 1 ) {
2662 foreach ( $taxonomies as $index => $taxonomy ) {
2663 $t = get_taxonomy($taxonomy);
2664 if ( isset($t->args) && is_array($t->args) && $args != array_merge($args, $t->args) ) {
2665 unset($taxonomies[$index]);
2666 $terms = array_merge($terms, wp_get_object_terms($object_ids, $taxonomy, array_merge($args, $t->args)));
2670 $t = get_taxonomy($taxonomies[0]);
2671 if ( isset($t->args) && is_array($t->args) )
2672 $args = array_merge($args, $t->args);
2675 $orderby = $args['orderby'];
2676 $order = $args['order'];
2677 $fields = $args['fields'];
2679 if ( in_array( $orderby, array( 'term_id', 'name', 'slug', 'term_group' ) ) ) {
2680 $orderby = "t.$orderby";
2681 } else if ( in_array( $orderby, array( 'count', 'parent', 'taxonomy', 'term_taxonomy_id' ) ) ) {
2682 $orderby = "tt.$orderby";
2683 } else if ( 'term_order' === $orderby ) {
2684 $orderby = 'tr.term_order';
2685 } else if ( 'none' === $orderby ) {
2689 $orderby = 't.term_id';
2692 // tt_ids queries can only be none or tr.term_taxonomy_id
2693 if ( ('tt_ids' == $fields) && !empty($orderby) )
2694 $orderby = 'tr.term_taxonomy_id';
2696 if ( !empty($orderby) )
2697 $orderby = "ORDER BY $orderby";
2699 $order = strtoupper( $order );
2700 if ( '' !== $order && ! in_array( $order, array( 'ASC', 'DESC' ) ) )
2703 $taxonomy_array = $taxonomies;
2704 $object_id_array = $object_ids;
2705 $taxonomies = "'" . implode("', '", $taxonomies) . "'";
2706 $object_ids = implode(', ', $object_ids);
2709 if ( 'all' == $fields ) {
2710 $select_this = 't.*, tt.*';
2711 } elseif ( 'ids' == $fields ) {
2712 $select_this = 't.term_id';
2713 } elseif ( 'names' == $fields ) {
2714 $select_this = 't.name';
2715 } elseif ( 'slugs' == $fields ) {
2716 $select_this = 't.slug';
2717 } elseif ( 'all_with_object_id' == $fields ) {
2718 $select_this = 't.*, tt.*, tr.object_id';
2722 "tt.taxonomy IN ($taxonomies)",
2723 "tr.object_id IN ($object_ids)",
2726 if ( '' !== $args['parent'] ) {
2727 $where[] = $wpdb->prepare( 'tt.parent = %d', $args['parent'] );
2730 $where = implode( ' AND ', $where );
2732 $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 $where $orderby $order";
2735 if ( 'all' == $fields || 'all_with_object_id' == $fields ) {
2736 $_terms = $wpdb->get_results( $query );
2737 foreach ( $_terms as $key => $term ) {
2738 $_terms[$key] = sanitize_term( $term, $taxonomy, 'raw' );
2740 $terms = array_merge( $terms, $_terms );
2741 update_term_cache( $terms );
2743 } elseif ( 'ids' == $fields || 'names' == $fields || 'slugs' == $fields ) {
2744 $_terms = $wpdb->get_col( $query );
2745 $_field = ( 'ids' == $fields ) ? 'term_id' : 'name';
2746 foreach ( $_terms as $key => $term ) {
2747 $_terms[$key] = sanitize_term_field( $_field, $term, $term, $taxonomy, 'raw' );
2749 $terms = array_merge( $terms, $_terms );
2750 } elseif ( 'tt_ids' == $fields ) {
2751 $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");
2752 foreach ( $terms as $key => $tt_id ) {
2753 $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.
2759 } elseif ( $objects && 'all_with_object_id' !== $fields ) {
2762 foreach ( $terms as $term ) {
2763 if ( in_array( $term->term_taxonomy_id, $_tt_ids ) ) {
2767 $_tt_ids[] = $term->term_taxonomy_id;
2771 } elseif ( ! $objects ) {
2772 $terms = array_values( array_unique( $terms ) );
2776 * Filter the terms for a given object or objects.
2780 * @param array $terms An array of terms for the given object or objects.
2781 * @param array $object_id_array Array of object IDs for which `$terms` were retrieved.
2782 * @param array $taxonomy_array Array of taxonomies from which `$terms` were retrieved.
2783 * @param array $args An array of arguments for retrieving terms for the given
2784 * object(s). See wp_get_object_terms() for details.
2786 $terms = apply_filters( 'get_object_terms', $terms, $object_id_array, $taxonomy_array, $args );
2789 * Filter the terms for a given object or objects.
2791 * The `$taxonomies` parameter passed to this filter is formatted as a SQL fragment. The
2792 * {@see 'get_object_terms'} filter is recommended as an alternative.
2796 * @param array $terms An array of terms for the given object or objects.
2797 * @param int|array $object_ids Object ID or array of IDs.
2798 * @param string $taxonomies SQL-formatted (comma-separated and quoted) list of taxonomy names.
2799 * @param array $args An array of arguments for retrieving terms for the given object(s).
2800 * See {@see wp_get_object_terms()} for details.
2802 return apply_filters( 'wp_get_object_terms', $terms, $object_ids, $taxonomies, $args );
2806 * Add a new term to the database.
2808 * A non-existent term is inserted in the following sequence:
2809 * 1. The term is added to the term table, then related to the taxonomy.
2810 * 2. If everything is correct, several actions are fired.
2811 * 3. The 'term_id_filter' is evaluated.
2812 * 4. The term cache is cleaned.
2813 * 5. Several more actions are fired.
2814 * 6. An array is returned containing the term_id and term_taxonomy_id.
2816 * If the 'slug' argument is not empty, then it is checked to see if the term
2817 * is invalid. If it is not a valid, existing term, it is added and the term_id
2820 * If the taxonomy is hierarchical, and the 'parent' argument is not empty,
2821 * the term is inserted and the term_id will be given.
2824 * If $taxonomy does not exist or $term is empty,
2825 * a WP_Error object will be returned.
2827 * If the term already exists on the same hierarchical level,
2828 * or the term slug and name are not unique, a WP_Error object will be returned.
2830 * @global wpdb $wpdb WordPress database abstraction object.
2834 * @param string $term The term to add or update.
2835 * @param string $taxonomy The taxonomy to which to add the term.
2836 * @param array|string $args {
2837 * Optional. Array or string of arguments for inserting a term.
2839 * @type string $alias_of Slug of the term to make this term an alias of.
2840 * Default empty string. Accepts a term slug.
2841 * @type string $description The term description. Default empty string.
2842 * @type int $parent The id of the parent term. Default 0.
2843 * @type string $slug The term slug to use. Default empty string.
2845 * @return array|WP_Error An array containing the `term_id` and `term_taxonomy_id`,
2846 * {@see WP_Error} otherwise.
2848 function wp_insert_term( $term, $taxonomy, $args = array() ) {
2851 if ( ! taxonomy_exists($taxonomy) ) {
2852 return new WP_Error('invalid_taxonomy', __('Invalid taxonomy'));
2855 * Filter a term before it is sanitized and inserted into the database.
2859 * @param string $term The term to add or update.
2860 * @param string $taxonomy Taxonomy slug.
2862 $term = apply_filters( 'pre_insert_term', $term, $taxonomy );
2863 if ( is_wp_error( $term ) ) {
2866 if ( is_int($term) && 0 == $term ) {
2867 return new WP_Error('invalid_term_id', __('Invalid term ID'));
2869 if ( '' == trim($term) ) {
2870 return new WP_Error('empty_term_name', __('A name is required for this term'));
2872 $defaults = array( 'alias_of' => '', 'description' => '', 'parent' => 0, 'slug' => '');
2873 $args = wp_parse_args( $args, $defaults );
2875 if ( $args['parent'] > 0 && ! term_exists( (int) $args['parent'] ) ) {
2876 return new WP_Error( 'missing_parent', __( 'Parent term does not exist.' ) );
2878 $args['name'] = $term;
2879 $args['taxonomy'] = $taxonomy;
2880 $args = sanitize_term($args, $taxonomy, 'db');
2882 // expected_slashed ($name)
2883 $name = wp_unslash( $args['name'] );
2884 $description = wp_unslash( $args['description'] );
2885 $parent = (int) $args['parent'];
2887 $slug_provided = ! empty( $args['slug'] );
2888 if ( ! $slug_provided ) {
2889 $slug = sanitize_title( $name );
2891 $slug = $args['slug'];
2895 if ( $args['alias_of'] ) {
2896 $alias = get_term_by( 'slug', $args['alias_of'], $taxonomy );
2897 if ( ! empty( $alias->term_group ) ) {
2898 // The alias we want is already in a group, so let's use that one.
2899 $term_group = $alias->term_group;
2900 } elseif ( ! empty( $alias->term_id ) ) {
2902 * The alias is not in a group, so we create a new one
2903 * and add the alias to it.
2905 $term_group = $wpdb->get_var("SELECT MAX(term_group) FROM $wpdb->terms") + 1;
2907 wp_update_term( $alias->term_id, $taxonomy, array(
2908 'term_group' => $term_group,
2914 * Prevent the creation of terms with duplicate names at the same level of a taxonomy hierarchy,
2915 * unless a unique slug has been explicitly provided.
2917 if ( $name_match = get_term_by( 'name', $name, $taxonomy ) ) {
2918 $slug_match = get_term_by( 'slug', $slug, $taxonomy );
2919 if ( ! $slug_provided || $name_match->slug === $slug || $slug_match ) {
2920 if ( is_taxonomy_hierarchical( $taxonomy ) ) {
2921 $siblings = get_terms( $taxonomy, array( 'get' => 'all', 'parent' => $parent ) );
2923 $existing_term = null;
2924 if ( $name_match->slug === $slug && in_array( $name, wp_list_pluck( $siblings, 'name' ) ) ) {
2925 $existing_term = $name_match;
2926 } elseif ( $slug_match && in_array( $slug, wp_list_pluck( $siblings, 'slug' ) ) ) {
2927 $existing_term = $slug_match;
2930 if ( $existing_term ) {
2931 return new WP_Error( 'term_exists', __( 'A term with the name already exists with this parent.' ), $existing_term->term_id );
2934 return new WP_Error( 'term_exists', __( 'A term with the name already exists in this taxonomy.' ), $name_match->term_id );
2939 $slug = wp_unique_term_slug( $slug, (object) $args );
2941 if ( false === $wpdb->insert( $wpdb->terms, compact( 'name', 'slug', 'term_group' ) ) ) {
2942 return new WP_Error( 'db_insert_error', __( 'Could not insert term into the database' ), $wpdb->last_error );
2945 $term_id = (int) $wpdb->insert_id;
2947 // Seems unreachable, However, Is used in the case that a term name is provided, which sanitizes to an empty string.
2948 if ( empty($slug) ) {
2949 $slug = sanitize_title($slug, $term_id);
2951 /** This action is documented in wp-includes/taxonomy.php */
2952 do_action( 'edit_terms', $term_id, $taxonomy );
2953 $wpdb->update( $wpdb->terms, compact( 'slug' ), compact( 'term_id' ) );
2955 /** This action is documented in wp-includes/taxonomy.php */
2956 do_action( 'edited_terms', $term_id, $taxonomy );
2959 $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 ) );
2961 if ( !empty($tt_id) ) {
2962 return array('term_id' => $term_id, 'term_taxonomy_id' => $tt_id);
2964 $wpdb->insert( $wpdb->term_taxonomy, compact( 'term_id', 'taxonomy', 'description', 'parent') + array( 'count' => 0 ) );
2965 $tt_id = (int) $wpdb->insert_id;
2968 * Sanity check: if we just created a term with the same parent + taxonomy + slug but a higher term_id than
2969 * an existing term, then we have unwittingly created a duplicate term. Delete the dupe, and use the term_id
2970 * and term_taxonomy_id of the older term instead. Then return out of the function so that the "create" hooks
2973 $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 ) );
2974 if ( $duplicate_term ) {
2975 $wpdb->delete( $wpdb->terms, array( 'term_id' => $term_id ) );
2976 $wpdb->delete( $wpdb->term_taxonomy, array( 'term_taxonomy_id' => $tt_id ) );
2978 $term_id = (int) $duplicate_term->term_id;
2979 $tt_id = (int) $duplicate_term->term_taxonomy_id;
2981 clean_term_cache( $term_id, $taxonomy );
2982 return array( 'term_id' => $term_id, 'term_taxonomy_id' => $tt_id );
2986 * Fires immediately after a new term is created, before the term cache is cleaned.
2990 * @param int $term_id Term ID.
2991 * @param int $tt_id Term taxonomy ID.
2992 * @param string $taxonomy Taxonomy slug.
2994 do_action( "create_term", $term_id, $tt_id, $taxonomy );
2997 * Fires after a new term is created for a specific taxonomy.
2999 * The dynamic portion of the hook name, `$taxonomy`, refers
3000 * to the slug of the taxonomy the term was created for.
3004 * @param int $term_id Term ID.
3005 * @param int $tt_id Term taxonomy ID.
3007 do_action( "create_$taxonomy", $term_id, $tt_id );
3010 * Filter the term ID after a new term is created.
3014 * @param int $term_id Term ID.
3015 * @param int $tt_id Taxonomy term ID.
3017 $term_id = apply_filters( 'term_id_filter', $term_id, $tt_id );
3019 clean_term_cache($term_id, $taxonomy);
3022 * Fires after a new term is created, and after the term cache has been cleaned.
3026 do_action( "created_term", $term_id, $tt_id, $taxonomy );
3029 * Fires after a new term in a specific taxonomy is created, and after the term
3030 * cache has been cleaned.
3034 * @param int $term_id Term ID.
3035 * @param int $tt_id Term taxonomy ID.
3037 do_action( "created_$taxonomy", $term_id, $tt_id );
3039 return array('term_id' => $term_id, 'term_taxonomy_id' => $tt_id);
3043 * Create Term and Taxonomy Relationships.
3045 * Relates an object (post, link etc) to a term and taxonomy type. Creates the
3046 * term and taxonomy relationship if it doesn't already exist. Creates a term if
3047 * it doesn't exist (using the slug).
3049 * A relationship means that the term is grouped in or belongs to the taxonomy.
3050 * A term has no meaning until it is given context by defining which taxonomy it
3055 * @param int $object_id The object to relate to.
3056 * @param array|int|string $terms A single term slug, single term id, or array of either term slugs or ids.
3057 * Will replace all existing related terms in this taxonomy.
3058 * @param string $taxonomy The context in which to relate the term to the object.
3059 * @param bool $append Optional. If false will delete difference of terms. Default false.
3060 * @return array|WP_Error Affected Term IDs.
3062 function wp_set_object_terms( $object_id, $terms, $taxonomy, $append = false ) {
3065 $object_id = (int) $object_id;
3067 if ( ! taxonomy_exists($taxonomy) )
3068 return new WP_Error('invalid_taxonomy', __('Invalid taxonomy'));
3070 if ( !is_array($terms) )
3071 $terms = array($terms);
3074 $old_tt_ids = wp_get_object_terms($object_id, $taxonomy, array('fields' => 'tt_ids', 'orderby' => 'none'));
3076 $old_tt_ids = array();
3079 $term_ids = array();
3080 $new_tt_ids = array();
3082 foreach ( (array) $terms as $term) {
3083 if ( !strlen(trim($term)) )
3086 if ( !$term_info = term_exists($term, $taxonomy) ) {
3087 // Skip if a non-existent term ID is passed.
3088 if ( is_int($term) )
3090 $term_info = wp_insert_term($term, $taxonomy);
3092 if ( is_wp_error($term_info) )
3094 $term_ids[] = $term_info['term_id'];
3095 $tt_id = $term_info['term_taxonomy_id'];
3098 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 ) ) )
3102 * Fires immediately before an object-term relationship is added.
3106 * @param int $object_id Object ID.
3107 * @param int $tt_id Term taxonomy ID.
3109 do_action( 'add_term_relationship', $object_id, $tt_id );
3110 $wpdb->insert( $wpdb->term_relationships, array( 'object_id' => $object_id, 'term_taxonomy_id' => $tt_id ) );
3113 * Fires immediately after an object-term relationship is added.
3117 * @param int $object_id Object ID.
3118 * @param int $tt_id Term taxonomy ID.
3120 do_action( 'added_term_relationship', $object_id, $tt_id );
3121 $new_tt_ids[] = $tt_id;
3125 wp_update_term_count( $new_tt_ids, $taxonomy );
3128 $delete_tt_ids = array_diff( $old_tt_ids, $tt_ids );
3130 if ( $delete_tt_ids ) {
3131 $in_delete_tt_ids = "'" . implode( "', '", $delete_tt_ids ) . "'";
3132 $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 ) );
3133 $delete_term_ids = array_map( 'intval', $delete_term_ids );
3135 $remove = wp_remove_object_terms( $object_id, $delete_term_ids, $taxonomy );
3136 if ( is_wp_error( $remove ) ) {
3142 $t = get_taxonomy($taxonomy);
3143 if ( ! $append && isset($t->sort) && $t->sort ) {
3146 $final_tt_ids = wp_get_object_terms($object_id, $taxonomy, array('fields' => 'tt_ids'));
3147 foreach ( $tt_ids as $tt_id )
3148 if ( in_array($tt_id, $final_tt_ids) )
3149 $values[] = $wpdb->prepare( "(%d, %d, %d)", $object_id, $tt_id, ++$term_order);
3151 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)" ) )
3152 return new WP_Error( 'db_insert_error', __( 'Could not insert term relationship into the database' ), $wpdb->last_error );
3155 wp_cache_delete( $object_id, $taxonomy . '_relationships' );
3158 * Fires after an object's terms have been set.
3162 * @param int $object_id Object ID.
3163 * @param array $terms An array of object terms.
3164 * @param array $tt_ids An array of term taxonomy IDs.
3165 * @param string $taxonomy Taxonomy slug.
3166 * @param bool $append Whether to append new terms to the old terms.
3167 * @param array $old_tt_ids Old array of term taxonomy IDs.
3169 do_action( 'set_object_terms', $object_id, $terms, $tt_ids, $taxonomy, $append, $old_tt_ids );
3174 * Add term(s) associated with a given object.
3178 * @param int $object_id The ID of the object to which the terms will be added.
3179 * @param array|int|string $terms The slug(s) or ID(s) of the term(s) to add.
3180 * @param array|string $taxonomy Taxonomy name.
3181 * @return array|WP_Error Affected Term IDs
3183 function wp_add_object_terms( $object_id, $terms, $taxonomy ) {
3184 return wp_set_object_terms( $object_id, $terms, $taxonomy, true );
3188 * Remove term(s) associated with a given object.
3192 * @global wpdb $wpdb WordPress database abstraction object.
3194 * @param int $object_id The ID of the object from which the terms will be removed.
3195 * @param array|int|string $terms The slug(s) or ID(s) of the term(s) to remove.
3196 * @param array|string $taxonomy Taxonomy name.
3197 * @return bool|WP_Error True on success, false or WP_Error on failure.
3199 function wp_remove_object_terms( $object_id, $terms, $taxonomy ) {
3202 $object_id = (int) $object_id;
3204 if ( ! taxonomy_exists( $taxonomy ) ) {
3205 return new WP_Error( 'invalid_taxonomy', __( 'Invalid Taxonomy' ) );
3208 if ( ! is_array( $terms ) ) {
3209 $terms = array( $terms );
3214 foreach ( (array) $terms as $term ) {
3215 if ( ! strlen( trim( $term ) ) ) {
3219 if ( ! $term_info = term_exists( $term, $taxonomy ) ) {
3220 // Skip if a non-existent term ID is passed.
3221 if ( is_int( $term ) ) {
3226 if ( is_wp_error( $term_info ) ) {
3230 $tt_ids[] = $term_info['term_taxonomy_id'];
3234 $in_tt_ids = "'" . implode( "', '", $tt_ids ) . "'";
3237 * Fires immediately before an object-term relationship is deleted.
3241 * @param int $object_id Object ID.
3242 * @param array $tt_ids An array of term taxonomy IDs.
3244 do_action( 'delete_term_relationships', $object_id, $tt_ids );
3245 $deleted = $wpdb->query( $wpdb->prepare( "DELETE FROM $wpdb->term_relationships WHERE object_id = %d AND term_taxonomy_id IN ($in_tt_ids)", $object_id ) );
3248 * Fires immediately after an object-term relationship is deleted.
3252 * @param int $object_id Object ID.
3253 * @param array $tt_ids An array of term taxonomy IDs.
3255 do_action( 'deleted_term_relationships', $object_id, $tt_ids );
3256 wp_update_term_count( $tt_ids, $taxonomy );
3258 return (bool) $deleted;
3265 * Will make slug unique, if it isn't already.
3267 * The $slug has to be unique global to every taxonomy, meaning that one
3268 * taxonomy term can't have a matching slug with another taxonomy term. Each
3269 * slug has to be globally unique for every taxonomy.
3271 * The way this works is that if the taxonomy that the term belongs to is
3272 * hierarchical and has a parent, it will append that parent to the $slug.
3274 * If that still doesn't return an unique slug, then it try to append a number
3275 * until it finds a number that is truly unique.
3277 * The only purpose for $term is for appending a parent, if one exists.
3281 * @global wpdb $wpdb WordPress database abstraction object.
3283 * @param string $slug The string that will be tried for a unique slug
3284 * @param object $term The term object that the $slug will belong too
3285 * @return string Will return a true unique slug.
3287 function wp_unique_term_slug($slug, $term) {
3290 if ( ! term_exists( $slug ) )
3293 // As of 4.1, duplicate slugs are allowed as long as they're in different taxonomies.
3294 if ( get_option( 'db_version' ) >= 30133 && ! get_term_by( 'slug', $slug, $term->taxonomy ) ) {
3298 // If the taxonomy supports hierarchy and the term has a parent, make the slug unique
3299 // by incorporating parent slugs.
3300 if ( is_taxonomy_hierarchical($term->taxonomy) && !empty($term->parent) ) {
3301 $the_parent = $term->parent;
3302 while ( ! empty($the_parent) ) {
3303 $parent_term = get_term($the_parent, $term->taxonomy);
3304 if ( is_wp_error($parent_term) || empty($parent_term) )
3306 $slug .= '-' . $parent_term->slug;
3307 if ( ! term_exists( $slug ) )
3310 if ( empty($parent_term->parent) )
3312 $the_parent = $parent_term->parent;
3316 // If we didn't get a unique slug, try appending a number to make it unique.
3317 if ( ! empty( $term->term_id ) )
3318 $query = $wpdb->prepare( "SELECT slug FROM $wpdb->terms WHERE slug = %s AND term_id != %d", $slug, $term->term_id );
3320 $query = $wpdb->prepare( "SELECT slug FROM $wpdb->terms WHERE slug = %s", $slug );
3322 if ( $wpdb->get_var( $query ) ) {
3325 $alt_slug = $slug . "-$num";
3327 $slug_check = $wpdb->get_var( $wpdb->prepare( "SELECT slug FROM $wpdb->terms WHERE slug = %s", $alt_slug ) );
3328 } while ( $slug_check );
3336 * Update term based on arguments provided.
3338 * The $args will indiscriminately override all values with the same field name.
3339 * Care must be taken to not override important information need to update or
3340 * update will fail (or perhaps create a new term, neither would be acceptable).
3342 * Defaults will set 'alias_of', 'description', 'parent', and 'slug' if not
3343 * defined in $args already.
3345 * 'alias_of' will create a term group, if it doesn't already exist, and update
3348 * If the 'slug' argument in $args is missing, then the 'name' in $args will be
3349 * used. It should also be noted that if you set 'slug' and it isn't unique then
3350 * a WP_Error will be passed back. If you don't pass any slug, then a unique one
3351 * will be created for you.
3353 * For what can be overrode in $args, check the term scheme can contain and stay
3354 * away from the term keys.
3358 * @global wpdb $wpdb WordPress database abstraction object.
3360 * @param int $term_id The ID of the term
3361 * @param string $taxonomy The context in which to relate the term to the object.
3362 * @param array|string $args Overwrite term field values
3363 * @return array|WP_Error Returns Term ID and Taxonomy Term ID
3365 function wp_update_term( $term_id, $taxonomy, $args = array() ) {
3368 if ( ! taxonomy_exists( $taxonomy ) ) {
3369 return new WP_Error( 'invalid_taxonomy', __( 'Invalid taxonomy' ) );
3372 $term_id = (int) $term_id;
3374 // First, get all of the original args
3375 $term = get_term( $term_id, $taxonomy, ARRAY_A );
3377 if ( is_wp_error( $term ) ) {
3382 return new WP_Error( 'invalid_term', __( 'Empty Term' ) );
3385 // Escape data pulled from DB.
3386 $term = wp_slash($term);
3388 // Merge old and new args with new args overwriting old ones.
3389 $args = array_merge($term, $args);
3391 $defaults = array( 'alias_of' => '', 'description' => '', 'parent' => 0, 'slug' => '');
3392 $args = wp_parse_args($args, $defaults);
3393 $args = sanitize_term($args, $taxonomy, 'db');
3394 $parsed_args = $args;
3396 // expected_slashed ($name)
3397 $name = wp_unslash( $args['name'] );
3398 $description = wp_unslash( $args['description'] );
3400 $parsed_args['name'] = $name;
3401 $parsed_args['description'] = $description;
3403 if ( '' == trim($name) )
3404 return new WP_Error('empty_term_name', __('A name is required for this term'));
3406 if ( $parsed_args['parent'] > 0 && ! term_exists( (int) $parsed_args['parent'] ) ) {
3407 return new WP_Error( 'missing_parent', __( 'Parent term does not exist.' ) );
3410 $empty_slug = false;
3411 if ( empty( $args['slug'] ) ) {
3413 $slug = sanitize_title($name);
3415 $slug = $args['slug'];
3418 $parsed_args['slug'] = $slug;
3420 $term_group = isset( $parsed_args['term_group'] ) ? $parsed_args['term_group'] : 0;
3421 if ( $args['alias_of'] ) {
3422 $alias = get_term_by( 'slug', $args['alias_of'], $taxonomy );
3423 if ( ! empty( $alias->term_group ) ) {
3424 // The alias we want is already in a group, so let's use that one.
3425 $term_group = $alias->term_group;
3426 } elseif ( ! empty( $alias->term_id ) ) {
3428 * The alias is not in a group, so we create a new one
3429 * and add the alias to it.
3431 $term_group = $wpdb->get_var("SELECT MAX(term_group) FROM $wpdb->terms") + 1;
3433 wp_update_term( $alias->term_id, $taxonomy, array(
3434 'term_group' => $term_group,
3438 $parsed_args['term_group'] = $term_group;
3442 * Filter the term parent.
3444 * Hook to this filter to see if it will cause a hierarchy loop.
3448 * @param int $parent ID of the parent term.
3449 * @param int $term_id Term ID.
3450 * @param string $taxonomy Taxonomy slug.
3451 * @param array $parsed_args An array of potentially altered update arguments for the given term.
3452 * @param array $args An array of update arguments for the given term.
3454 $parent = apply_filters( 'wp_update_term_parent', $args['parent'], $term_id, $taxonomy, $parsed_args, $args );
3456 // Check for duplicate slug
3457 $duplicate = get_term_by( 'slug', $slug, $taxonomy );
3458 if ( $duplicate && $duplicate->term_id != $term_id ) {
3459 // If an empty slug was passed or the parent changed, reset the slug to something unique.
3461 if ( $empty_slug || ( $parent != $term['parent']) )
3462 $slug = wp_unique_term_slug($slug, (object) $args);
3464 return new WP_Error('duplicate_term_slug', sprintf(__('The slug “%s” is already in use by another term'), $slug));
3467 $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) );
3469 // Check whether this is a shared term that needs splitting.
3470 $_term_id = _split_shared_term( $term_id, $tt_id );
3471 if ( ! is_wp_error( $_term_id ) ) {
3472 $term_id = $_term_id;
3476 * Fires immediately before the given terms are edited.
3480 * @param int $term_id Term ID.
3481 * @param string $taxonomy Taxonomy slug.
3483 do_action( 'edit_terms', $term_id, $taxonomy );
3484 $wpdb->update($wpdb->terms, compact( 'name', 'slug', 'term_group' ), compact( 'term_id' ) );
3485 if ( empty($slug) ) {
3486 $slug = sanitize_title($name, $term_id);
3487 $wpdb->update( $wpdb->terms, compact( 'slug' ), compact( 'term_id' ) );
3491 * Fires immediately after the given terms are edited.
3495 * @param int $term_id Term ID
3496 * @param string $taxonomy Taxonomy slug.
3498 do_action( 'edited_terms', $term_id, $taxonomy );
3501 * Fires immediate before a term-taxonomy relationship is updated.
3505 * @param int $tt_id Term taxonomy ID.
3506 * @param string $taxonomy Taxonomy slug.
3508 do_action( 'edit_term_taxonomy', $tt_id, $taxonomy );
3509 $wpdb->update( $wpdb->term_taxonomy, compact( 'term_id', 'taxonomy', 'description', 'parent' ), array( 'term_taxonomy_id' => $tt_id ) );
3512 * Fires immediately after a term-taxonomy relationship is updated.
3516 * @param int $tt_id Term taxonomy ID.
3517 * @param string $taxonomy Taxonomy slug.
3519 do_action( 'edited_term_taxonomy', $tt_id, $taxonomy );
3521 // Clean the relationship caches for all object types using this term
3522 $objects = $wpdb->get_col( $wpdb->prepare( "SELECT object_id FROM $wpdb->term_relationships WHERE term_taxonomy_id = %d", $tt_id ) );
3523 $tax_object = get_taxonomy( $taxonomy );
3524 foreach ( $tax_object->object_type as $object_type ) {
3525 clean_object_term_cache( $objects, $object_type );
3529 * Fires after a term has been updated, but before the term cache has been cleaned.
3533 * @param int $term_id Term ID.
3534 * @param int $tt_id Term taxonomy ID.
3535 * @param string $taxonomy Taxonomy slug.
3537 do_action( "edit_term", $term_id, $tt_id, $taxonomy );
3540 * Fires after a term in a specific taxonomy has been updated, but before the term
3541 * cache has been cleaned.
3543 * The dynamic portion of the hook name, `$taxonomy`, refers to the taxonomy slug.
3547 * @param int $term_id Term ID.
3548 * @param int $tt_id Term taxonomy ID.
3550 do_action( "edit_$taxonomy", $term_id, $tt_id );
3552 /** This filter is documented in wp-includes/taxonomy.php */
3553 $term_id = apply_filters( 'term_id_filter', $term_id, $tt_id );
3555 clean_term_cache($term_id, $taxonomy);
3558 * Fires after a term has been updated, and the term cache has been cleaned.
3562 * @param int $term_id Term ID.
3563 * @param int $tt_id Term taxonomy ID.
3564 * @param string $taxonomy Taxonomy slug.
3566 do_action( "edited_term", $term_id, $tt_id, $taxonomy );
3569 * Fires after a term for a specific taxonomy has been updated, and the term
3570 * cache has been cleaned.
3572 * The dynamic portion of the hook name, `$taxonomy`, refers to the taxonomy slug.
3576 * @param int $term_id Term ID.
3577 * @param int $tt_id Term taxonomy ID.
3579 do_action( "edited_$taxonomy", $term_id, $tt_id );
3581 return array('term_id' => $term_id, 'term_taxonomy_id' => $tt_id);
3585 * Enable or disable term counting.
3589 * @param bool $defer Optional. Enable if true, disable if false.
3590 * @return bool Whether term counting is enabled or disabled.
3592 function wp_defer_term_counting($defer=null) {
3593 static $_defer = false;
3595 if ( is_bool($defer) ) {
3597 // flush any deferred counts
3599 wp_update_term_count( null, null, true );
3606 * Updates the amount of terms in taxonomy.
3608 * If there is a taxonomy callback applied, then it will be called for updating
3611 * The default action is to count what the amount of terms have the relationship
3612 * of term ID. Once that is done, then update the database.
3616 * @global wpdb $wpdb WordPress database abstraction object.
3618 * @param int|array $terms The term_taxonomy_id of the terms
3619 * @param string $taxonomy The context of the term.
3620 * @return bool If no terms will return false, and if successful will return true.
3622 function wp_update_term_count( $terms, $taxonomy, $do_deferred=false ) {
3623 static $_deferred = array();
3625 if ( $do_deferred ) {
3626 foreach ( (array) array_keys($_deferred) as $tax ) {
3627 wp_update_term_count_now( $_deferred[$tax], $tax );
3628 unset( $_deferred[$tax] );
3632 if ( empty($terms) )
3635 if ( !is_array($terms) )
3636 $terms = array($terms);
3638 if ( wp_defer_term_counting() ) {
3639 if ( !isset($_deferred[$taxonomy]) )
3640 $_deferred[$taxonomy] = array();
3641 $_deferred[$taxonomy] = array_unique( array_merge($_deferred[$taxonomy], $terms) );
3645 return wp_update_term_count_now( $terms, $taxonomy );
3649 * Perform term count update immediately.
3653 * @param array $terms The term_taxonomy_id of terms to update.
3654 * @param string $taxonomy The context of the term.
3655 * @return bool Always true when complete.
3657 function wp_update_term_count_now( $terms, $taxonomy ) {
3658 $terms = array_map('intval', $terms);
3660 $taxonomy = get_taxonomy($taxonomy);
3661 if ( !empty($taxonomy->update_count_callback) ) {
3662 call_user_func($taxonomy->update_count_callback, $terms, $taxonomy);
3664 $object_types = (array) $taxonomy->object_type;
3665 foreach ( $object_types as &$object_type ) {
3666 if ( 0 === strpos( $object_type, 'attachment:' ) )
3667 list( $object_type ) = explode( ':', $object_type );
3670 if ( $object_types == array_filter( $object_types, 'post_type_exists' ) ) {
3671 // Only post types are attached to this taxonomy
3672 _update_post_term_count( $terms, $taxonomy );
3674 // Default count updater
3675 _update_generic_term_count( $terms, $taxonomy );
3679 clean_term_cache($terms, '', false);
3689 * Removes the taxonomy relationship to terms from the cache.
3691 * Will remove the entire taxonomy relationship containing term $object_id. The
3692 * term IDs have to exist within the taxonomy $object_type for the deletion to
3697 * @see get_object_taxonomies() for more on $object_type
3699 * @param int|array $object_ids Single or list of term object ID(s)
3700 * @param array|string $object_type The taxonomy object type
3702 function clean_object_term_cache($object_ids, $object_type) {
3703 if ( !is_array($object_ids) )
3704 $object_ids = array($object_ids);
3706 $taxonomies = get_object_taxonomies( $object_type );
3708 foreach ( $object_ids as $id ) {
3709 foreach ( $taxonomies as $taxonomy ) {
3710 wp_cache_delete($id, "{$taxonomy}_relationships");
3715 * Fires after the object term cache has been cleaned.
3719 * @param array $object_ids An array of object IDs.
3720 * @param string $objet_type Object type.
3722 do_action( 'clean_object_term_cache', $object_ids, $object_type );
3726 * Will remove all of the term ids from the cache.
3730 * @global wpdb $wpdb WordPress database abstraction object.
3732 * @param int|array $ids Single or list of Term IDs
3733 * @param string $taxonomy Can be empty and will assume tt_ids, else will use for context.
3734 * @param bool $clean_taxonomy Whether to clean taxonomy wide caches (true), or just individual term object caches (false). Default is true.
3736 function clean_term_cache($ids, $taxonomy = '', $clean_taxonomy = true) {
3739 if ( !is_array($ids) )
3742 $taxonomies = array();
3743 // If no taxonomy, assume tt_ids.
3744 if ( empty($taxonomy) ) {
3745 $tt_ids = array_map('intval', $ids);
3746 $tt_ids = implode(', ', $tt_ids);
3747 $terms = $wpdb->get_results("SELECT term_id, taxonomy FROM $wpdb->term_taxonomy WHERE term_taxonomy_id IN ($tt_ids)");
3749 foreach ( (array) $terms as $term ) {
3750 $taxonomies[] = $term->taxonomy;
3751 $ids[] = $term->term_id;
3752 wp_cache_delete($term->term_id, $term->taxonomy);
3754 $taxonomies = array_unique($taxonomies);
3756 $taxonomies = array($taxonomy);
3757 foreach ( $taxonomies as $taxonomy ) {
3758 foreach ( $ids as $id ) {
3759 wp_cache_delete($id, $taxonomy);
3764 foreach ( $taxonomies as $taxonomy ) {
3765 if ( $clean_taxonomy ) {
3766 wp_cache_delete('all_ids', $taxonomy);
3767 wp_cache_delete('get', $taxonomy);
3768 delete_option("{$taxonomy}_children");
3769 // Regenerate {$taxonomy}_children
3770 _get_term_hierarchy($taxonomy);
3774 * Fires once after each taxonomy's term cache has been cleaned.
3778 * @param array $ids An array of term IDs.
3779 * @param string $taxonomy Taxonomy slug.
3781 do_action( 'clean_term_cache', $ids, $taxonomy );
3784 wp_cache_set( 'last_changed', microtime(), 'terms' );
3788 * Retrieves the taxonomy relationship to the term object id.
3792 * @param int $id Term object ID
3793 * @param string $taxonomy Taxonomy Name
3794 * @return bool|array Empty array if $terms found, but not $taxonomy. False if nothing is in cache for $taxonomy and $id.
3796 function get_object_term_cache($id, $taxonomy) {
3797 $cache = wp_cache_get($id, "{$taxonomy}_relationships");
3802 * Updates the cache for the given term object ID(s).
3804 * Note: Due to performance concerns, great care should be taken to only update
3805 * term caches when necessary. Processing time can increase exponentially depending
3806 * on both the number of passed term IDs and the number of taxonomies those terms
3809 * Caches will only be updated for terms not already cached.
3813 * @param string|array $object_ids Comma-separated list or array of term object IDs..
3814 * @param array|string $object_type The taxonomy object type.
3815 * @return null|false Null if `$object_ids` is empty, false if all of the terms in
3816 * `$object_ids` are already cached.
3818 function update_object_term_cache($object_ids, $object_type) {
3819 if ( empty($object_ids) )
3822 if ( !is_array($object_ids) )
3823 $object_ids = explode(',', $object_ids);
3825 $object_ids = array_map('intval', $object_ids);
3827 $taxonomies = get_object_taxonomies($object_type);
3830 foreach ( (array) $object_ids as $id ) {
3831 foreach ( $taxonomies as $taxonomy ) {
3832 if ( false === wp_cache_get($id, "{$taxonomy}_relationships") ) {
3839 if ( empty( $ids ) )
3842 $terms = wp_get_object_terms($ids, $taxonomies, array('fields' => 'all_with_object_id'));
3844 $object_terms = array();
3845 foreach ( (array) $terms as $term )
3846 $object_terms[$term->object_id][$term->taxonomy][] = $term;
3848 foreach ( $ids as $id ) {
3849 foreach ( $taxonomies as $taxonomy ) {
3850 if ( ! isset($object_terms[$id][$taxonomy]) ) {
3851 if ( !isset($object_terms[$id]) )
3852 $object_terms[$id] = array();
3853 $object_terms[$id][$taxonomy] = array();
3858 foreach ( $object_terms as $id => $value ) {
3859 foreach ( $value as $taxonomy => $terms ) {
3860 wp_cache_add( $id, $terms, "{$taxonomy}_relationships" );
3866 * Updates Terms to Taxonomy in cache.
3870 * @param array $terms List of Term objects to change
3871 * @param string $taxonomy Optional. Update Term to this taxonomy in cache
3873 function update_term_cache($terms, $taxonomy = '') {
3874 foreach ( (array) $terms as $term ) {
3875 $term_taxonomy = $taxonomy;
3876 if ( empty($term_taxonomy) )
3877 $term_taxonomy = $term->taxonomy;
3879 wp_cache_add( $term->term_id, $term, $term_taxonomy );
3888 * Retrieves children of taxonomy as Term IDs.
3893 * @param string $taxonomy Taxonomy Name
3894 * @return array Empty if $taxonomy isn't hierarchical or returns children as Term IDs.
3896 function _get_term_hierarchy($taxonomy) {
3897 if ( !is_taxonomy_hierarchical($taxonomy) )
3899 $children = get_option("{$taxonomy}_children");
3901 if ( is_array($children) )
3903 $children = array();
3904 $terms = get_terms($taxonomy, array('get' => 'all', 'orderby' => 'id', 'fields' => 'id=>parent'));
3905 foreach ( $terms as $term_id => $parent ) {
3907 $children[$parent][] = $term_id;
3909 update_option("{$taxonomy}_children", $children);
3915 * Get the subset of $terms that are descendants of $term_id.
3917 * If $terms is an array of objects, then _get_term_children returns an array of objects.
3918 * If $terms is an array of IDs, then _get_term_children returns an array of IDs.
3923 * @param int $term_id The ancestor term: all returned terms should be descendants of $term_id.
3924 * @param array $terms The set of terms - either an array of term objects or term IDs - from which those that
3925 * are descendants of $term_id will be chosen.
3926 * @param string $taxonomy The taxonomy which determines the hierarchy of the terms.
3927 * @param array $ancestors Term ancestors that have already been identified. Passed by reference, to keep track of
3928 * found terms when recursing the hierarchy. The array of located ancestors is used to prevent
3929 * infinite recursion loops. For performance, term_ids are used as array keys, with 1 as value.
3930 * @return array The subset of $terms that are descendants of $term_id.
3932 function _get_term_children( $term_id, $terms, $taxonomy, &$ancestors = array() ) {
3933 $empty_array = array();
3934 if ( empty($terms) )
3935 return $empty_array;
3937 $term_list = array();
3938 $has_children = _get_term_hierarchy($taxonomy);
3940 if ( ( 0 != $term_id ) && ! isset($has_children[$term_id]) )
3941 return $empty_array;
3943 // Include the term itself in the ancestors array, so we can properly detect when a loop has occurred.
3944 if ( empty( $ancestors ) ) {
3945 $ancestors[ $term_id ] = 1;
3948 foreach ( (array) $terms as $term ) {
3950 if ( !is_object($term) ) {
3951 $term = get_term($term, $taxonomy);
3952 if ( is_wp_error( $term ) )
3957 // Don't recurse if we've already identified the term as a child - this indicates a loop.
3958 if ( isset( $ancestors[ $term->term_id ] ) ) {
3962 if ( $term->parent == $term_id ) {
3964 $term_list[] = $term->term_id;
3966 $term_list[] = $term;
3968 if ( !isset($has_children[$term->term_id]) )
3971 $ancestors[ $term->term_id ] = 1;
3973 if ( $children = _get_term_children( $term->term_id, $terms, $taxonomy, $ancestors) )
3974 $term_list = array_merge($term_list, $children);
3982 * Add count of children to parent count.
3984 * Recalculates term counts by including items from child terms. Assumes all
3985 * relevant children are already in the $terms argument.
3990 * @global wpdb $wpdb WordPress database abstraction object.
3992 * @param array $terms List of Term IDs
3993 * @param string $taxonomy Term Context
3994 * @return null Will break from function if conditions are not met.
3996 function _pad_term_counts(&$terms, $taxonomy) {
3999 // This function only works for hierarchical taxonomies like post categories.
4000 if ( !is_taxonomy_hierarchical( $taxonomy ) )
4003 $term_hier = _get_term_hierarchy($taxonomy);
4005 if ( empty($term_hier) )
4008 $term_items = array();
4009 $terms_by_id = array();
4010 $term_ids = array();
4012 foreach ( (array) $terms as $key => $term ) {
4013 $terms_by_id[$term->term_id] = & $terms[$key];
4014 $term_ids[$term->term_taxonomy_id] = $term->term_id;
4017 // Get the object and term ids and stick them in a lookup table
4018 $tax_obj = get_taxonomy($taxonomy);
4019 $object_types = esc_sql($tax_obj->object_type);
4020 $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'");
4021 foreach ( $results as $row ) {
4022 $id = $term_ids[$row->term_taxonomy_id];
4023 $term_items[$id][$row->object_id] = isset($term_items[$id][$row->object_id]) ? ++$term_items[$id][$row->object_id] : 1;
4026 // Touch every ancestor's lookup row for each post in each term
4027 foreach ( $term_ids as $term_id ) {
4029 $ancestors = array();
4030 while ( !empty( $terms_by_id[$child] ) && $parent = $terms_by_id[$child]->parent ) {
4031 $ancestors[] = $child;
4032 if ( !empty( $term_items[$term_id] ) )
4033 foreach ( $term_items[$term_id] as $item_id => $touches ) {
4034 $term_items[$parent][$item_id] = isset($term_items[$parent][$item_id]) ? ++$term_items[$parent][$item_id]: 1;
4038 if ( in_array( $parent, $ancestors ) ) {
4044 // Transfer the touched cells
4045 foreach ( (array) $term_items as $id => $items )
4046 if ( isset($terms_by_id[$id]) )
4047 $terms_by_id[$id]->count = count($items);
4051 // Default callbacks
4055 * Will update term count based on object types of the current taxonomy.
4057 * Private function for the default callback for post_tag and category
4063 * @global wpdb $wpdb WordPress database abstraction object.
4065 * @param array $terms List of Term taxonomy IDs
4066 * @param object $taxonomy Current taxonomy object of terms
4068 function _update_post_term_count( $terms, $taxonomy ) {
4071 $object_types = (array) $taxonomy->object_type;
4073 foreach ( $object_types as &$object_type )
4074 list( $object_type ) = explode( ':', $object_type );
4076 $object_types = array_unique( $object_types );
4078 if ( false !== ( $check_attachments = array_search( 'attachment', $object_types ) ) ) {
4079 unset( $object_types[ $check_attachments ] );
4080 $check_attachments = true;
4083 if ( $object_types )
4084 $object_types = esc_sql( array_filter( $object_types, 'post_type_exists' ) );
4086 foreach ( (array) $terms as $term ) {
4089 // Attachments can be 'inherit' status, we need to base count off the parent's status if so
4090 if ( $check_attachments )
4091 $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 ) );
4093 if ( $object_types )
4094 $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 ) );
4096 /** This action is documented in wp-includes/taxonomy.php */
4097 do_action( 'edit_term_taxonomy', $term, $taxonomy->name );
4098 $wpdb->update( $wpdb->term_taxonomy, compact( 'count' ), array( 'term_taxonomy_id' => $term ) );
4100 /** This action is documented in wp-includes/taxonomy.php */
4101 do_action( 'edited_term_taxonomy', $term, $taxonomy->name );
4106 * Will update term count based on number of objects.
4108 * Default callback for the link_category taxonomy.
4112 * @global wpdb $wpdb WordPress database abstraction object.
4114 * @param array $terms List of Term taxonomy IDs
4115 * @param object $taxonomy Current taxonomy object of terms
4117 function _update_generic_term_count( $terms, $taxonomy ) {
4120 foreach ( (array) $terms as $term ) {
4121 $count = $wpdb->get_var( $wpdb->prepare( "SELECT COUNT(*) FROM $wpdb->term_relationships WHERE term_taxonomy_id = %d", $term ) );
4123 /** This action is documented in wp-includes/taxonomy.php */
4124 do_action( 'edit_term_taxonomy', $term, $taxonomy->name );
4125 $wpdb->update( $wpdb->term_taxonomy, compact( 'count' ), array( 'term_taxonomy_id' => $term ) );
4127 /** This action is documented in wp-includes/taxonomy.php */
4128 do_action( 'edited_term_taxonomy', $term, $taxonomy->name );
4133 * Create a new term for a term_taxonomy item that currently shares its term with another term_taxonomy.
4138 * @param int $term_id ID of the shared term.
4139 * @param int $term_taxonomy_id ID of the term_taxonomy item to receive a new term.
4140 * @return int|WP_Error When the current term does not need to be split (or cannot be split on the current
4141 * database schema), `$term_id` is returned. When the term is successfully split, the
4142 * new term_id is returned. A WP_Error is returned for miscellaneous errors.
4144 function _split_shared_term( $term_id, $term_taxonomy_id ) {
4147 // Don't try to split terms if database schema does not support shared slugs.
4148 $current_db_version = get_option( 'db_version' );
4149 if ( $current_db_version < 30133 ) {
4153 // If there are no shared term_taxonomy rows, there's nothing to do here.
4154 $shared_tt_count = $wpdb->get_var( $wpdb->prepare( "SELECT COUNT(*) FROM $wpdb->term_taxonomy tt WHERE tt.term_id = %d AND tt.term_taxonomy_id != %d", $term_id, $term_taxonomy_id ) );
4155 if ( ! $shared_tt_count ) {
4159 // Pull up data about the currently shared slug, which we'll use to populate the new one.
4160 $shared_term = $wpdb->get_row( $wpdb->prepare( "SELECT t.* FROM $wpdb->terms t WHERE t.term_id = %d", $term_id ) );
4162 $new_term_data = array(
4163 'name' => $shared_term->name,
4164 'slug' => $shared_term->slug,
4165 'term_group' => $shared_term->term_group,
4168 if ( false === $wpdb->insert( $wpdb->terms, $new_term_data ) ) {
4169 return new WP_Error( 'db_insert_error', __( 'Could not split shared term.' ), $wpdb->last_error );
4172 $new_term_id = (int) $wpdb->insert_id;
4174 // Update the existing term_taxonomy to point to the newly created term.
4175 $wpdb->update( $wpdb->term_taxonomy,
4176 array( 'term_id' => $new_term_id ),
4177 array( 'term_taxonomy_id' => $term_taxonomy_id )
4180 // Reassign child terms to the new parent.
4181 $term_taxonomy = $wpdb->get_row( $wpdb->prepare( "SELECT * FROM $wpdb->term_taxonomy WHERE term_taxonomy_id = %d", $term_taxonomy_id ) );
4182 $children_tt_ids = $wpdb->get_col( $wpdb->prepare( "SELECT term_taxonomy_id FROM $wpdb->term_taxonomy WHERE taxonomy = %s AND parent = %d", $term_taxonomy->taxonomy, $term_id ) );
4184 if ( ! empty( $children_tt_ids ) ) {
4185 foreach ( $children_tt_ids as $child_tt_id ) {
4186 $wpdb->update( $wpdb->term_taxonomy,
4187 array( 'parent' => $new_term_id ),
4188 array( 'term_taxonomy_id' => $child_tt_id )
4190 clean_term_cache( $term_id, $term_taxonomy->taxonomy );
4193 // If the term has no children, we must force its taxonomy cache to be rebuilt separately.
4194 clean_term_cache( $new_term_id, $term_taxonomy->taxonomy );
4197 // Clean the cache for term taxonomies formerly shared with the current term.
4198 $shared_term_taxonomies = $wpdb->get_row( $wpdb->prepare( "SELECT taxonomy FROM $wpdb->term_taxonomy WHERE term_id = %d", $term_id ) );
4199 if ( $shared_term_taxonomies ) {
4200 foreach ( $shared_term_taxonomies as $shared_term_taxonomy ) {
4201 clean_term_cache( $term_id, $shared_term_taxonomy );
4205 // Keep a record of term_ids that have been split, keyed by old term_id. See {@see wp_get_split_term()}.
4206 $split_term_data = get_option( '_split_terms', array() );
4207 if ( ! isset( $split_term_data[ $term_id ] ) ) {
4208 $split_term_data[ $term_id ] = array();
4211 $split_term_data[ $term_id ][ $term_taxonomy->taxonomy ] = $new_term_id;
4213 update_option( '_split_terms', $split_term_data );
4216 * Fires after a previously shared taxonomy term is split into two separate terms.
4220 * @param int $term_id ID of the formerly shared term.
4221 * @param int $new_term_id ID of the new term created for the $term_taxonomy_id.
4222 * @param int $term_taxonomy_id ID for the term_taxonomy row affected by the split.
4223 * @param string $taxonomy Taxonomy for the split term.
4225 do_action( 'split_shared_term', $term_id, $new_term_id, $term_taxonomy_id, $term_taxonomy->taxonomy );
4227 return $new_term_id;
4231 * Check default categories when a term gets split to see if any of them need to be updated.
4236 * @param int $term_id ID of the formerly shared term.
4237 * @param int $new_term_id ID of the new term created for the $term_taxonomy_id.
4238 * @param int $term_taxonomy_id ID for the term_taxonomy row affected by the split.
4239 * @param string $taxonomy Taxonomy for the split term.
4241 function _wp_check_split_default_terms( $term_id, $new_term_id, $term_taxonomy_id, $taxonomy ) {
4242 if ( 'category' != $taxonomy ) {
4246 foreach ( array( 'default_category', 'default_link_category', 'default_email_category' ) as $option ) {
4247 if ( $term_id == get_option( $option, -1 ) ) {
4248 update_option( $option, $new_term_id );
4254 * Check menu items when a term gets split to see if any of them need to be updated.
4259 * @param int $term_id ID of the formerly shared term.
4260 * @param int $new_term_id ID of the new term created for the $term_taxonomy_id.
4261 * @param int $term_taxonomy_id ID for the term_taxonomy row affected by the split.
4262 * @param string $taxonomy Taxonomy for the split term.
4264 function _wp_check_split_terms_in_menus( $term_id, $new_term_id, $term_taxonomy_id, $taxonomy ) {
4266 $post_ids = $wpdb->get_col( $wpdb->prepare(
4268 FROM {$wpdb->postmeta} AS m1
4269 INNER JOIN {$wpdb->postmeta} AS m2 ON ( m2.post_id = m1.post_id )
4270 INNER JOIN {$wpdb->postmeta} AS m3 ON ( m3.post_id = m1.post_id )
4271 WHERE ( m1.meta_key = '_menu_item_type' AND m1.meta_value = 'taxonomy' )
4272 AND ( m2.meta_key = '_menu_item_object' AND m2.meta_value = '%s' )
4273 AND ( m3.meta_key = '_menu_item_object_id' AND m3.meta_value = %d )",
4279 foreach ( $post_ids as $post_id ) {
4280 update_post_meta( $post_id, '_menu_item_object_id', $new_term_id, $term_id );
4286 * Get data about terms that previously shared a single term_id, but have since been split.
4290 * @param int $old_term_id Term ID. This is the old, pre-split term ID.
4291 * @return array Array of new term IDs, keyed by taxonomy.
4293 function wp_get_split_terms( $old_term_id ) {
4294 $split_terms = get_option( '_split_terms', array() );
4297 if ( isset( $split_terms[ $old_term_id ] ) ) {
4298 $terms = $split_terms[ $old_term_id ];
4305 * Get the new term ID corresponding to a previously split term.
4309 * @param int $old_term_id Term ID. This is the old, pre-split term ID.
4310 * @param string $taxonomy Taxonomy that the term belongs to.
4311 * @return bool|int If a previously split term is found corresponding to the old term_id and taxonomy,
4312 * the new term_id will be returned. If no previously split term is found matching
4313 * the parameters, returns false.
4315 function wp_get_split_term( $old_term_id, $taxonomy ) {
4316 $split_terms = wp_get_split_terms( $old_term_id );
4319 if ( isset( $split_terms[ $taxonomy ] ) ) {
4320 $term_id = (int) $split_terms[ $taxonomy ];
4327 * Generate a permalink for a taxonomy term archive.
4331 * @param object|int|string $term The term object, ID, or slug whose link will be retrieved.
4332 * @param string $taxonomy Optional. Taxonomy. Default empty.
4333 * @return string|WP_Error HTML link to taxonomy term archive on success, WP_Error if term does not exist.
4335 function get_term_link( $term, $taxonomy = '') {
4338 if ( !is_object($term) ) {
4339 if ( is_int($term) ) {
4340 $term = get_term($term, $taxonomy);
4342 $term = get_term_by('slug', $term, $taxonomy);
4346 if ( !is_object($term) )
4347 $term = new WP_Error('invalid_term', __('Empty Term'));
4349 if ( is_wp_error( $term ) )
4352 $taxonomy = $term->taxonomy;
4354 $termlink = $wp_rewrite->get_extra_permastruct($taxonomy);
4356 $slug = $term->slug;
4357 $t = get_taxonomy($taxonomy);
4359 if ( empty($termlink) ) {
4360 if ( 'category' == $taxonomy )
4361 $termlink = '?cat=' . $term->term_id;
4362 elseif ( $t->query_var )
4363 $termlink = "?$t->query_var=$slug";
4365 $termlink = "?taxonomy=$taxonomy&term=$slug";
4366 $termlink = home_url($termlink);
4368 if ( $t->rewrite['hierarchical'] ) {
4369 $hierarchical_slugs = array();
4370 $ancestors = get_ancestors( $term->term_id, $taxonomy, 'taxonomy' );
4371 foreach ( (array)$ancestors as $ancestor ) {
4372 $ancestor_term = get_term($ancestor, $taxonomy);
4373 $hierarchical_slugs[] = $ancestor_term->slug;
4375 $hierarchical_slugs = array_reverse($hierarchical_slugs);
4376 $hierarchical_slugs[] = $slug;
4377 $termlink = str_replace("%$taxonomy%", implode('/', $hierarchical_slugs), $termlink);
4379 $termlink = str_replace("%$taxonomy%", $slug, $termlink);
4381 $termlink = home_url( user_trailingslashit($termlink, 'category') );
4383 // Back Compat filters.
4384 if ( 'post_tag' == $taxonomy ) {
4387 * Filter the tag link.
4390 * @deprecated 2.5.0 Use 'term_link' instead.
4392 * @param string $termlink Tag link URL.
4393 * @param int $term_id Term ID.
4395 $termlink = apply_filters( 'tag_link', $termlink, $term->term_id );
4396 } elseif ( 'category' == $taxonomy ) {
4399 * Filter the category link.
4402 * @deprecated 2.5.0 Use 'term_link' instead.
4404 * @param string $termlink Category link URL.
4405 * @param int $term_id Term ID.
4407 $termlink = apply_filters( 'category_link', $termlink, $term->term_id );
4411 * Filter the term link.
4415 * @param string $termlink Term link URL.
4416 * @param object $term Term object.
4417 * @param string $taxonomy Taxonomy slug.
4419 return apply_filters( 'term_link', $termlink, $term, $taxonomy );
4423 * Display the taxonomies of a post with available options.
4425 * This function can be used within the loop to display the taxonomies for a
4426 * post without specifying the Post ID. You can also use it outside the Loop to
4427 * display the taxonomies for a specific post.
4431 * @param array $args {
4432 * Arguments about which post to use and how to format the output. Shares all of the arguments supported by
4433 * {@link get_the_taxonomies()}, in addition to the following.
4435 * @type int|WP_Post $post Post ID or object to get taxonomies of. Default current post.
4436 * @type string $before Displays before the taxonomies. Default empty string.
4437 * @type string $sep Separates each taxonomy. Default is a space.
4438 * @type string $after Displays after the taxonomies. Default empty string.
4440 * @param array $args See {@link get_the_taxonomies()} for a description of arguments and their defaults.
4442 function the_taxonomies( $args = array() ) {
4450 $r = wp_parse_args( $args, $defaults );
4452 echo $r['before'] . join( $r['sep'], get_the_taxonomies( $r['post'], $r ) ) . $r['after'];
4456 * Retrieve all taxonomies associated with a post.
4458 * This function can be used within the loop. It will also return an array of
4459 * the taxonomies with links to the taxonomy and name.
4463 * @param int|WP_Post $post Optional. Post ID or WP_Post object. Default is global $post.
4464 * @param array $args {
4465 * Arguments about how to format the list of taxonomies.
4467 * @type string $template Template for displaying a taxonomy label and list of terms.
4468 * Default is "Label: Terms."
4469 * @type string $term_template Template for displaying a single term in the list. Default is the term name
4470 * linked to its archive.
4472 * @return array List of taxonomies.
4474 function get_the_taxonomies( $post = 0, $args = array() ) {
4475 $post = get_post( $post );
4477 $args = wp_parse_args( $args, array(
4478 /* translators: %s: taxonomy label, %l: list of terms formatted as per $term_template */
4479 'template' => __( '%s: %l.' ),
4480 'term_template' => '<a href="%1$s">%2$s</a>',
4483 $taxonomies = array();
4489 foreach ( get_object_taxonomies( $post ) as $taxonomy ) {
4490 $t = (array) get_taxonomy( $taxonomy );
4491 if ( empty( $t['label'] ) ) {
4492 $t['label'] = $taxonomy;
4494 if ( empty( $t['args'] ) ) {
4495 $t['args'] = array();
4497 if ( empty( $t['template'] ) ) {
4498 $t['template'] = $args['template'];
4500 if ( empty( $t['term_template'] ) ) {
4501 $t['term_template'] = $args['term_template'];
4504 $terms = get_object_term_cache( $post->ID, $taxonomy );
4505 if ( false === $terms ) {
4506 $terms = wp_get_object_terms( $post->ID, $taxonomy, $t['args'] );
4510 foreach ( $terms as $term ) {
4511 $links[] = wp_sprintf( $t['term_template'], esc_attr( get_term_link( $term ) ), $term->name );
4514 $taxonomies[$taxonomy] = wp_sprintf( $t['template'], $t['label'], $links, $terms );
4521 * Retrieve all taxonomies of a post with just the names.
4525 * @param int|WP_Post $post Optional. Post ID or WP_Post object. Default is global $post.
4528 function get_post_taxonomies( $post = 0 ) {
4529 $post = get_post( $post );
4531 return get_object_taxonomies($post);
4535 * Determine if the given object is associated with any of the given terms.
4537 * The given terms are checked against the object's terms' term_ids, names and slugs.
4538 * Terms given as integers will only be checked against the object's terms' term_ids.
4539 * If no terms are given, determines if object is associated with any terms in the given taxonomy.
4543 * @param int $object_id ID of the object (post ID, link ID, ...)
4544 * @param string $taxonomy Single taxonomy name
4545 * @param int|string|array $terms Optional. Term term_id, name, slug or array of said
4546 * @return bool|WP_Error WP_Error on input error.
4548 function is_object_in_term( $object_id, $taxonomy, $terms = null ) {
4549 if ( !$object_id = (int) $object_id )
4550 return new WP_Error( 'invalid_object', __( 'Invalid object ID' ) );
4552 $object_terms = get_object_term_cache( $object_id, $taxonomy );
4553 if ( false === $object_terms )
4554 $object_terms = wp_get_object_terms( $object_id, $taxonomy );
4556 if ( is_wp_error( $object_terms ) )
4557 return $object_terms;
4558 if ( empty( $object_terms ) )
4560 if ( empty( $terms ) )
4561 return ( !empty( $object_terms ) );
4563 $terms = (array) $terms;
4565 if ( $ints = array_filter( $terms, 'is_int' ) )
4566 $strs = array_diff( $terms, $ints );
4570 foreach ( $object_terms as $object_term ) {
4571 // If term is an int, check against term_ids only.
4572 if ( $ints && in_array( $object_term->term_id, $ints ) ) {
4577 // Only check numeric strings against term_id, to avoid false matches due to type juggling.
4578 $numeric_strs = array_map( 'intval', array_filter( $strs, 'is_numeric' ) );
4579 if ( in_array( $object_term->term_id, $numeric_strs, true ) ) {
4583 if ( in_array( $object_term->name, $strs ) ) return true;
4584 if ( in_array( $object_term->slug, $strs ) ) return true;
4592 * Determine if the given object type is associated with the given taxonomy.
4596 * @param string $object_type Object type string
4597 * @param string $taxonomy Single taxonomy name
4598 * @return bool True if object is associated with the taxonomy, otherwise false.
4600 function is_object_in_taxonomy($object_type, $taxonomy) {
4601 $taxonomies = get_object_taxonomies($object_type);
4603 if ( empty($taxonomies) )
4606 if ( in_array($taxonomy, $taxonomies) )
4613 * Get an array of ancestor IDs for a given object.
4616 * @since 4.1.0 Introduced the `$resource_type` argument.
4618 * @param int $object_id Optional. The ID of the object. Default 0.
4619 * @param string $object_type Optional. The type of object for which we'll be retrieving
4620 * ancestors. Accepts a post type or a taxonomy name. Default empty.
4621 * @param string $resource_type Optional. Type of resource $object_type is. Accepts 'post_type'
4622 * or 'taxonomy'. Default empty.
4623 * @return array An array of ancestors from lowest to highest in the hierarchy.
4625 function get_ancestors( $object_id = 0, $object_type = '', $resource_type = '' ) {
4626 $object_id = (int) $object_id;
4628 $ancestors = array();
4630 if ( empty( $object_id ) ) {
4632 /** This filter is documented in wp-includes/taxonomy.php */
4633 return apply_filters( 'get_ancestors', $ancestors, $object_id, $object_type, $resource_type );
4636 if ( ! $resource_type ) {
4637 if ( is_taxonomy_hierarchical( $object_type ) ) {
4638 $resource_type = 'taxonomy';
4639 } elseif ( post_type_exists( $object_type ) ) {
4640 $resource_type = 'post_type';
4644 if ( 'taxonomy' === $resource_type ) {
4645 $term = get_term($object_id, $object_type);
4646 while ( ! is_wp_error($term) && ! empty( $term->parent ) && ! in_array( $term->parent, $ancestors ) ) {
4647 $ancestors[] = (int) $term->parent;
4648 $term = get_term($term->parent, $object_type);
4650 } elseif ( 'post_type' === $resource_type ) {
4651 $ancestors = get_post_ancestors($object_id);
4655 * Filter a given object's ancestors.
4658 * @since 4.1.0 Introduced the `$resource_type` parameter.
4660 * @param array $ancestors An array of object ancestors.
4661 * @param int $object_id Object ID.
4662 * @param string $object_type Type of object.
4663 * @param string $resource_type Type of resource $object_type is.
4665 return apply_filters( 'get_ancestors', $ancestors, $object_id, $object_type, $resource_type );
4669 * Returns the term's parent's term_ID
4673 * @param int $term_id
4674 * @param string $taxonomy
4676 * @return int|bool false on error
4678 function wp_get_term_taxonomy_parent_id( $term_id, $taxonomy ) {
4679 $term = get_term( $term_id, $taxonomy );
4680 if ( !$term || is_wp_error( $term ) )
4682 return (int) $term->parent;
4686 * Checks the given subset of the term hierarchy for hierarchy loops.
4687 * Prevents loops from forming and breaks those that it finds.
4689 * Attached to the wp_update_term_parent filter.
4693 * @param int $parent term_id of the parent for the term we're checking.
4694 * @param int $term_id The term we're checking.
4695 * @param string $taxonomy The taxonomy of the term we're checking.
4697 * @return int The new parent for the term.
4699 function wp_check_term_hierarchy_for_loops( $parent, $term_id, $taxonomy ) {
4700 // Nothing fancy here - bail
4704 // Can't be its own parent
4705 if ( $parent == $term_id )
4708 // Now look for larger loops
4710 if ( !$loop = wp_find_hierarchy_loop( 'wp_get_term_taxonomy_parent_id', $term_id, $parent, array( $taxonomy ) ) )
4711 return $parent; // No loop
4713 // Setting $parent to the given value causes a loop
4714 if ( isset( $loop[$term_id] ) )
4717 // There's a loop, but it doesn't contain $term_id. Break the loop.
4718 foreach ( array_keys( $loop ) as $loop_member )
4719 wp_update_term( $loop_member, $taxonomy, array( 'parent' => 0 ) );