10 // Taxonomy Registration
14 * Creates the initial taxonomies.
16 * This function fires twice: in wp-settings.php before plugins are loaded (for
17 * backwards compatibility reasons), and again on the {@see 'init'} action. We must
18 * avoid registering rewrite rules before the {@see 'init'} action.
22 * @global WP_Rewrite $wp_rewrite The WordPress rewrite class.
24 function create_initial_taxonomies() {
27 if ( ! did_action( 'init' ) ) {
28 $rewrite = array( 'category' => false, 'post_tag' => false, 'post_format' => false );
32 * Filter the post formats rewrite base.
36 * @param string $context Context of the rewrite base. Default 'type'.
38 $post_format_base = apply_filters( 'post_format_rewrite_base', 'type' );
41 'hierarchical' => true,
42 'slug' => get_option('category_base') ? get_option('category_base') : 'category',
43 'with_front' => ! get_option('category_base') || $wp_rewrite->using_index_permalinks(),
44 'ep_mask' => EP_CATEGORIES,
47 'hierarchical' => false,
48 'slug' => get_option('tag_base') ? get_option('tag_base') : 'tag',
49 'with_front' => ! get_option('tag_base') || $wp_rewrite->using_index_permalinks(),
52 'post_format' => $post_format_base ? array( 'slug' => $post_format_base ) : false,
56 register_taxonomy( 'category', 'post', array(
57 'hierarchical' => true,
58 'query_var' => 'category_name',
59 'rewrite' => $rewrite['category'],
62 'show_admin_column' => true,
66 register_taxonomy( 'post_tag', 'post', array(
67 'hierarchical' => false,
69 'rewrite' => $rewrite['post_tag'],
72 'show_admin_column' => true,
76 register_taxonomy( 'nav_menu', 'nav_menu_item', array(
78 'hierarchical' => false,
80 'name' => __( 'Navigation Menus' ),
81 'singular_name' => __( 'Navigation Menu' ),
87 'show_in_nav_menus' => false,
90 register_taxonomy( 'link_category', 'link', array(
91 'hierarchical' => false,
93 'name' => __( 'Link Categories' ),
94 'singular_name' => __( 'Link Category' ),
95 'search_items' => __( 'Search Link Categories' ),
96 'popular_items' => null,
97 'all_items' => __( 'All Link Categories' ),
98 'edit_item' => __( 'Edit Link Category' ),
99 'update_item' => __( 'Update Link Category' ),
100 'add_new_item' => __( 'Add New Link Category' ),
101 'new_item_name' => __( 'New Link Category Name' ),
102 'separate_items_with_commas' => null,
103 'add_or_remove_items' => null,
104 'choose_from_most_used' => null,
106 'capabilities' => array(
107 'manage_terms' => 'manage_links',
108 'edit_terms' => 'manage_links',
109 'delete_terms' => 'manage_links',
110 'assign_terms' => 'manage_links',
112 'query_var' => false,
119 register_taxonomy( 'post_format', 'post', array(
121 'hierarchical' => false,
123 'name' => _x( 'Format', 'post format' ),
124 'singular_name' => _x( 'Format', 'post format' ),
127 'rewrite' => $rewrite['post_format'],
130 'show_in_nav_menus' => current_theme_supports( 'post-formats' ),
135 * Retrieves a list of registered taxonomy names or objects.
139 * @global array $wp_taxonomies The registered taxonomies.
141 * @param array $args Optional. An array of `key => value` arguments to match against the taxonomy objects.
142 * Default empty array.
143 * @param string $output Optional. The type of output to return in the array. Accepts either taxonomy 'names'
144 * or 'objects'. Default 'names'.
145 * @param string $operator Optional. The logical operation to perform. Accepts 'and' or 'or'. 'or' means only
146 * one element from the array needs to match; 'and' means all elements must match.
148 * @return array A list of taxonomy names or objects.
150 function get_taxonomies( $args = array(), $output = 'names', $operator = 'and' ) {
151 global $wp_taxonomies;
153 $field = ('names' == $output) ? 'name' : false;
155 return wp_filter_object_list($wp_taxonomies, $args, $operator, $field);
159 * Return all of the taxonomy names that are of $object_type.
161 * It appears that this function can be used to find all of the names inside of
162 * $wp_taxonomies global variable.
164 * `<?php $taxonomies = get_object_taxonomies('post'); ?>` Should
165 * result in `Array( 'category', 'post_tag' )`
169 * @global array $wp_taxonomies The registered taxonomies.
171 * @param array|string|WP_Post $object Name of the type of taxonomy object, or an object (row from posts)
172 * @param string $output Optional. The type of output to return in the array. Accepts either
173 * taxonomy 'names' or 'objects'. Default 'names'.
174 * @return array The names of all taxonomy of $object_type.
176 function get_object_taxonomies( $object, $output = 'names' ) {
177 global $wp_taxonomies;
179 if ( is_object($object) ) {
180 if ( $object->post_type == 'attachment' )
181 return get_attachment_taxonomies($object);
182 $object = $object->post_type;
185 $object = (array) $object;
187 $taxonomies = array();
188 foreach ( (array) $wp_taxonomies as $tax_name => $tax_obj ) {
189 if ( array_intersect($object, (array) $tax_obj->object_type) ) {
190 if ( 'names' == $output )
191 $taxonomies[] = $tax_name;
193 $taxonomies[ $tax_name ] = $tax_obj;
201 * Retrieves the taxonomy object of $taxonomy.
203 * The get_taxonomy function will first check that the parameter string given
204 * is a taxonomy object and if it is, it will return it.
208 * @global array $wp_taxonomies The registered taxonomies.
210 * @param string $taxonomy Name of taxonomy object to return.
211 * @return object|false The Taxonomy Object or false if $taxonomy doesn't exist.
213 function get_taxonomy( $taxonomy ) {
214 global $wp_taxonomies;
216 if ( ! taxonomy_exists( $taxonomy ) )
219 return $wp_taxonomies[$taxonomy];
223 * Checks that the taxonomy name exists.
225 * Formerly is_taxonomy(), introduced in 2.3.0.
229 * @global array $wp_taxonomies The registered taxonomies.
231 * @param string $taxonomy Name of taxonomy object.
232 * @return bool Whether the taxonomy exists.
234 function taxonomy_exists( $taxonomy ) {
235 global $wp_taxonomies;
237 return isset( $wp_taxonomies[$taxonomy] );
241 * Whether the taxonomy object is hierarchical.
243 * Checks to make sure that the taxonomy is an object first. Then Gets the
244 * object, and finally returns the hierarchical value in the object.
246 * A false return value might also mean that the taxonomy does not exist.
250 * @param string $taxonomy Name of taxonomy object.
251 * @return bool Whether the taxonomy is hierarchical.
253 function is_taxonomy_hierarchical($taxonomy) {
254 if ( ! taxonomy_exists($taxonomy) )
257 $taxonomy = get_taxonomy($taxonomy);
258 return $taxonomy->hierarchical;
262 * Creates or modifies a taxonomy object.
264 * Note: Do not use before the {@see 'init'} hook.
266 * A simple function for creating or modifying a taxonomy object based on the
267 * parameters given. The function will accept an array (third optional
268 * parameter), along with strings for the taxonomy name and another string for
272 * @since 4.2.0 Introduced `show_in_quick_edit` argument.
273 * @since 4.4.0 The `show_ui` argument is now enforced on the term editing screen.
274 * @since 4.4.0 The `public` argument now controls whether the taxonomy can be queried on the front-end.
276 * @global array $wp_taxonomies Registered taxonomies.
277 * @global WP $wp WP instance.
279 * @param string $taxonomy Taxonomy key, must not exceed 32 characters.
280 * @param array|string $object_type Name of the object type for the taxonomy object.
281 * @param array|string $args {
282 * Optional. Array or query string of arguments for registering a taxonomy.
284 * @type string $label Name of the taxonomy shown in the menu. Usually plural. If not set,
285 * `$labels['name']` will be used.
286 * @type array $labels An array of labels for this taxonomy. By default, Tag labels are used for
287 * non-hierarchical taxonmies, and Category labels are used for hierarchical
288 * taxonomies. See accepted values in get_taxonomy_labels().
289 * Default empty array.
290 * @type string $description A short descriptive summary of what the taxonomy is for. Default empty.
291 * @type bool $public Whether the taxonomy is publicly queryable. Default true.
292 * @type bool $hierarchical Whether the taxonomy is hierarchical. Default false.
293 * @type bool $show_ui Whether to generate and allow a UI for managing terms in this taxonomy in
294 * the admin. If not set, the default is inherited from `$public`
296 * @type bool $show_in_menu Whether to show the taxonomy in the admin menu. If true, the taxonomy is
297 * shown as a submenu of the object type menu. If false, no menu is shown.
298 * `$show_ui` must be true. If not set, default is inherited from `$show_ui`
300 * @type bool $show_in_nav_menus Makes this taxonomy available for selection in navigation menus. If not
301 * set, the default is inherited from `$public` (default true).
302 * @type bool $show_tagcloud Whether to list the taxonomy in the Tag Cloud Widget controls. If not set,
303 * the default is inherited from `$show_ui` (default true).
304 * @type bool $show_in_quick_edit Whether to show the taxonomy in the quick/bulk edit panel. It not set,
305 * the default is inherited from `$show_ui` (default true).
306 * @type bool $show_admin_column Whether to display a column for the taxonomy on its post type listing
307 * screens. Default false.
308 * @type bool|callable $meta_box_cb Provide a callback function for the meta box display. If not set,
309 * post_categories_meta_box() is used for hierarchical taxonomies, and
310 * post_tags_meta_box() is used for non-hierarchical. If false, no meta
312 * @type array $capabilities {
313 * Array of capabilities for this taxonomy.
315 * @type string $manage_terms Default 'manage_categories'.
316 * @type string $edit_terms Default 'manage_categories'.
317 * @type string $delete_terms Default 'manage_categories'.
318 * @type string $assign_terms Default 'edit_posts'.
320 * @type bool|array $rewrite {
321 * Triggers the handling of rewrites for this taxonomy. Default true, using $taxonomy as slug. To prevent
322 * rewrite, set to false. To specify rewrite rules, an array can be passed with any of these keys:
324 * @type string $slug Customize the permastruct slug. Default `$taxonomy` key.
325 * @type bool $with_front Should the permastruct be prepended with WP_Rewrite::$front. Default true.
326 * @type bool $hierarchical Either hierarchical rewrite tag or not. Default false.
327 * @type int $ep_mask Assign an endpoint mask. Default `EP_NONE`.
329 * @type string $query_var Sets the query var key for this taxonomy. Default `$taxonomy` key. If
330 * false, a taxonomy cannot be loaded at `?{query_var}={term_slug}`. If a
331 * string, the query `?{query_var}={term_slug}` will be valid.
332 * @type callable $update_count_callback Works much like a hook, in that it will be called when the count is
333 * updated. Default _update_post_term_count() for taxonomies attached
334 * to post types, which confirms that the objects are published before
335 * counting them. Default _update_generic_term_count() for taxonomies
336 * attached to other object types, such as users.
337 * @type bool $_builtin This taxonomy is a "built-in" taxonomy. INTERNAL USE ONLY!
340 * @return WP_Error|void WP_Error, if errors.
342 function register_taxonomy( $taxonomy, $object_type, $args = array() ) {
343 global $wp_taxonomies, $wp;
345 if ( ! is_array( $wp_taxonomies ) )
346 $wp_taxonomies = array();
348 $args = wp_parse_args( $args );
351 * Filter the arguments for registering a taxonomy.
355 * @param array $args Array of arguments for registering a taxonomy.
356 * @param array $object_type Array of names of object types for the taxonomy.
357 * @param string $taxonomy Taxonomy key.
359 $args = apply_filters( 'register_taxonomy_args', $args, $taxonomy, (array) $object_type );
365 'hierarchical' => false,
367 'show_in_menu' => null,
368 'show_in_nav_menus' => null,
369 'show_tagcloud' => null,
370 'show_in_quick_edit' => null,
371 'show_admin_column' => false,
372 'meta_box_cb' => null,
373 'capabilities' => array(),
375 'query_var' => $taxonomy,
376 'update_count_callback' => '',
379 $args = array_merge( $defaults, $args );
381 if ( empty( $taxonomy ) || strlen( $taxonomy ) > 32 ) {
382 _doing_it_wrong( __FUNCTION__, __( 'Taxonomy names must be between 1 and 32 characters in length.' ), '4.2' );
383 return new WP_Error( 'taxonomy_length_invalid', __( 'Taxonomy names must be between 1 and 32 characters in length.' ) );
386 // Non-public taxonomies should not register query vars, except in the admin.
387 if ( false !== $args['query_var'] && ( is_admin() || false !== $args['public'] ) && ! empty( $wp ) ) {
388 if ( true === $args['query_var'] )
389 $args['query_var'] = $taxonomy;
391 $args['query_var'] = sanitize_title_with_dashes( $args['query_var'] );
392 $wp->add_query_var( $args['query_var'] );
395 if ( false !== $args['rewrite'] && ( is_admin() || '' != get_option( 'permalink_structure' ) ) ) {
396 $args['rewrite'] = wp_parse_args( $args['rewrite'], array(
397 'with_front' => true,
398 'hierarchical' => false,
399 'ep_mask' => EP_NONE,
402 if ( empty( $args['rewrite']['slug'] ) )
403 $args['rewrite']['slug'] = sanitize_title_with_dashes( $taxonomy );
405 if ( $args['hierarchical'] && $args['rewrite']['hierarchical'] )
410 add_rewrite_tag( "%$taxonomy%", $tag, $args['query_var'] ? "{$args['query_var']}=" : "taxonomy=$taxonomy&term=" );
411 add_permastruct( $taxonomy, "{$args['rewrite']['slug']}/%$taxonomy%", $args['rewrite'] );
414 // If not set, default to the setting for public.
415 if ( null === $args['show_ui'] )
416 $args['show_ui'] = $args['public'];
418 // If not set, default to the setting for show_ui.
419 if ( null === $args['show_in_menu' ] || ! $args['show_ui'] )
420 $args['show_in_menu' ] = $args['show_ui'];
422 // If not set, default to the setting for public.
423 if ( null === $args['show_in_nav_menus'] )
424 $args['show_in_nav_menus'] = $args['public'];
426 // If not set, default to the setting for show_ui.
427 if ( null === $args['show_tagcloud'] )
428 $args['show_tagcloud'] = $args['show_ui'];
430 // If not set, default to the setting for show_ui.
431 if ( null === $args['show_in_quick_edit'] ) {
432 $args['show_in_quick_edit'] = $args['show_ui'];
435 $default_caps = array(
436 'manage_terms' => 'manage_categories',
437 'edit_terms' => 'manage_categories',
438 'delete_terms' => 'manage_categories',
439 'assign_terms' => 'edit_posts',
441 $args['cap'] = (object) array_merge( $default_caps, $args['capabilities'] );
442 unset( $args['capabilities'] );
444 $args['name'] = $taxonomy;
445 $args['object_type'] = array_unique( (array) $object_type );
447 $args['labels'] = get_taxonomy_labels( (object) $args );
448 $args['label'] = $args['labels']->name;
450 // If not set, use the default meta box
451 if ( null === $args['meta_box_cb'] ) {
452 if ( $args['hierarchical'] )
453 $args['meta_box_cb'] = 'post_categories_meta_box';
455 $args['meta_box_cb'] = 'post_tags_meta_box';
458 $wp_taxonomies[ $taxonomy ] = (object) $args;
460 // register callback handling for metabox
461 add_filter( 'wp_ajax_add-' . $taxonomy, '_wp_ajax_add_hierarchical_term' );
464 * Fires after a taxonomy is registered.
468 * @param string $taxonomy Taxonomy slug.
469 * @param array|string $object_type Object type or array of object types.
470 * @param array $args Array of taxonomy registration arguments.
472 do_action( 'registered_taxonomy', $taxonomy, $object_type, $args );
476 * Builds an object with all taxonomy labels out of a taxonomy object
478 * Accepted keys of the label array in the taxonomy object:
480 * - name - general name for the taxonomy, usually plural. The same as and overridden by $tax->label. Default is Tags/Categories
481 * - singular_name - name for one object of this taxonomy. Default is Tag/Category
482 * - search_items - Default is Search Tags/Search Categories
483 * - popular_items - This string isn't used on hierarchical taxonomies. Default is Popular Tags
484 * - all_items - Default is All Tags/All Categories
485 * - parent_item - This string isn't used on non-hierarchical taxonomies. In hierarchical ones the default is Parent Category
486 * - parent_item_colon - The same as `parent_item`, but with colon `:` in the end
487 * - edit_item - Default is Edit Tag/Edit Category
488 * - view_item - Default is View Tag/View Category
489 * - update_item - Default is Update Tag/Update Category
490 * - add_new_item - Default is Add New Tag/Add New Category
491 * - new_item_name - Default is New Tag Name/New Category Name
492 * - separate_items_with_commas - This string isn't used on hierarchical taxonomies. Default is "Separate tags with commas", used in the meta box.
493 * - 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.
494 * - 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.
495 * - not_found - Default is "No tags found"/"No categories found", used in the meta box and taxonomy list table.
496 * - no_terms - Default is "No tags"/"No categories", used in the posts and media list tables.
497 * - items_list_navigation - String for the table pagination hidden heading.
498 * - items_list - String for the table hidden heading.
500 * Above, the first default value is for non-hierarchical taxonomies (like tags) and the second one is for hierarchical taxonomies (like categories).
502 * @todo Better documentation for the labels array.
505 * @since 4.3.0 Added the `no_terms` label.
506 * @since 4.4.0 Added the `items_list_navigation` and `items_list` labels.
508 * @param object $tax Taxonomy object.
509 * @return object object with all the labels as member variables.
511 function get_taxonomy_labels( $tax ) {
512 $tax->labels = (array) $tax->labels;
514 if ( isset( $tax->helps ) && empty( $tax->labels['separate_items_with_commas'] ) )
515 $tax->labels['separate_items_with_commas'] = $tax->helps;
517 if ( isset( $tax->no_tagcloud ) && empty( $tax->labels['not_found'] ) )
518 $tax->labels['not_found'] = $tax->no_tagcloud;
520 $nohier_vs_hier_defaults = array(
521 'name' => array( _x( 'Tags', 'taxonomy general name' ), _x( 'Categories', 'taxonomy general name' ) ),
522 'singular_name' => array( _x( 'Tag', 'taxonomy singular name' ), _x( 'Category', 'taxonomy singular name' ) ),
523 'search_items' => array( __( 'Search Tags' ), __( 'Search Categories' ) ),
524 'popular_items' => array( __( 'Popular Tags' ), null ),
525 'all_items' => array( __( 'All Tags' ), __( 'All Categories' ) ),
526 'parent_item' => array( null, __( 'Parent Category' ) ),
527 'parent_item_colon' => array( null, __( 'Parent Category:' ) ),
528 'edit_item' => array( __( 'Edit Tag' ), __( 'Edit Category' ) ),
529 'view_item' => array( __( 'View Tag' ), __( 'View Category' ) ),
530 'update_item' => array( __( 'Update Tag' ), __( 'Update Category' ) ),
531 'add_new_item' => array( __( 'Add New Tag' ), __( 'Add New Category' ) ),
532 'new_item_name' => array( __( 'New Tag Name' ), __( 'New Category Name' ) ),
533 'separate_items_with_commas' => array( __( 'Separate tags with commas' ), null ),
534 'add_or_remove_items' => array( __( 'Add or remove tags' ), null ),
535 'choose_from_most_used' => array( __( 'Choose from the most used tags' ), null ),
536 'not_found' => array( __( 'No tags found.' ), __( 'No categories found.' ) ),
537 'no_terms' => array( __( 'No tags' ), __( 'No categories' ) ),
538 'items_list_navigation' => array( __( 'Tags list navigation' ), __( 'Categories list navigation' ) ),
539 'items_list' => array( __( 'Tags list' ), __( 'Categories list' ) ),
541 $nohier_vs_hier_defaults['menu_name'] = $nohier_vs_hier_defaults['name'];
543 $labels = _get_custom_object_labels( $tax, $nohier_vs_hier_defaults );
545 $taxonomy = $tax->name;
547 $default_labels = clone $labels;
550 * Filter the labels of a specific taxonomy.
552 * The dynamic portion of the hook name, `$taxonomy`, refers to the taxonomy slug.
556 * @see get_taxonomy_labels() for the full list of taxonomy labels.
558 * @param object $labels Object with labels for the taxonomy as member variables.
560 $labels = apply_filters( "taxonomy_labels_{$taxonomy}", $labels );
562 // Ensure that the filtered labels contain all required default values.
563 $labels = (object) array_merge( (array) $default_labels, (array) $labels );
569 * Add an already registered taxonomy to an object type.
573 * @global array $wp_taxonomies The registered taxonomies.
575 * @param string $taxonomy Name of taxonomy object.
576 * @param string $object_type Name of the object type.
577 * @return bool True if successful, false if not.
579 function register_taxonomy_for_object_type( $taxonomy, $object_type) {
580 global $wp_taxonomies;
582 if ( !isset($wp_taxonomies[$taxonomy]) )
585 if ( ! get_post_type_object($object_type) )
588 if ( ! in_array( $object_type, $wp_taxonomies[$taxonomy]->object_type ) )
589 $wp_taxonomies[$taxonomy]->object_type[] = $object_type;
591 // Filter out empties.
592 $wp_taxonomies[ $taxonomy ]->object_type = array_filter( $wp_taxonomies[ $taxonomy ]->object_type );
598 * Remove an already registered taxonomy from an object type.
602 * @global array $wp_taxonomies The registered taxonomies.
604 * @param string $taxonomy Name of taxonomy object.
605 * @param string $object_type Name of the object type.
606 * @return bool True if successful, false if not.
608 function unregister_taxonomy_for_object_type( $taxonomy, $object_type ) {
609 global $wp_taxonomies;
611 if ( ! isset( $wp_taxonomies[ $taxonomy ] ) )
614 if ( ! get_post_type_object( $object_type ) )
617 $key = array_search( $object_type, $wp_taxonomies[ $taxonomy ]->object_type, true );
618 if ( false === $key )
621 unset( $wp_taxonomies[ $taxonomy ]->object_type[ $key ] );
630 * Retrieve object_ids of valid taxonomy and term.
632 * The strings of $taxonomies must exist before this function will continue. On
633 * failure of finding a valid taxonomy, it will return an WP_Error class, kind
634 * of like Exceptions in PHP 5, except you can't catch them. Even so, you can
635 * still test for the WP_Error class and get the error message.
637 * The $terms aren't checked the same as $taxonomies, but still need to exist
638 * for $object_ids to be returned.
640 * It is possible to change the order that object_ids is returned by either
641 * using PHP sort family functions or using the database by using $args with
642 * either ASC or DESC array. The value should be in the key named 'order'.
646 * @global wpdb $wpdb WordPress database abstraction object.
648 * @param int|array $term_ids Term id or array of term ids of terms that will be used.
649 * @param string|array $taxonomies String of taxonomy name or Array of string values of taxonomy names.
650 * @param array|string $args Change the order of the object_ids, either ASC or DESC.
651 * @return WP_Error|array If the taxonomy does not exist, then WP_Error will be returned. On success.
652 * the array can be empty meaning that there are no $object_ids found or it will return the $object_ids found.
654 function get_objects_in_term( $term_ids, $taxonomies, $args = array() ) {
657 if ( ! is_array( $term_ids ) ) {
658 $term_ids = array( $term_ids );
660 if ( ! is_array( $taxonomies ) ) {
661 $taxonomies = array( $taxonomies );
663 foreach ( (array) $taxonomies as $taxonomy ) {
664 if ( ! taxonomy_exists( $taxonomy ) ) {
665 return new WP_Error( 'invalid_taxonomy', __( 'Invalid taxonomy' ) );
669 $defaults = array( 'order' => 'ASC' );
670 $args = wp_parse_args( $args, $defaults );
672 $order = ( 'desc' == strtolower( $args['order'] ) ) ? 'DESC' : 'ASC';
674 $term_ids = array_map('intval', $term_ids );
676 $taxonomies = "'" . implode( "', '", $taxonomies ) . "'";
677 $term_ids = "'" . implode( "', '", $term_ids ) . "'";
679 $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");
681 if ( ! $object_ids ){
688 * Given a taxonomy query, generates SQL to be appended to a main query.
694 * @param array $tax_query A compact tax query
695 * @param string $primary_table
696 * @param string $primary_id_column
699 function get_tax_sql( $tax_query, $primary_table, $primary_id_column ) {
700 $tax_query_obj = new WP_Tax_Query( $tax_query );
701 return $tax_query_obj->get_sql( $primary_table, $primary_id_column );
705 * Get all Term data from database by Term ID.
707 * The usage of the get_term function is to apply filters to a term object. It
708 * is possible to get a term object from the database before applying the
711 * $term ID must be part of $taxonomy, to get from the database. Failure, might
712 * be able to be captured by the hooks. Failure would be the same value as $wpdb
713 * returns for the get_row method.
715 * There are two hooks, one is specifically for each term, named 'get_term', and
716 * the second is for the taxonomy name, 'term_$taxonomy'. Both hooks gets the
717 * term object, and the taxonomy name as parameters. Both hooks are expected to
718 * return a Term object.
720 * {@see 'get_term'} hook - Takes two parameters the term Object and the taxonomy name.
721 * Must return term object. Used in get_term() as a catch-all filter for every
724 * {@see 'get_$taxonomy'} hook - Takes two parameters the term Object and the taxonomy
725 * name. Must return term object. $taxonomy will be the taxonomy name, so for
726 * example, if 'category', it would be 'get_category' as the filter name. Useful
727 * for custom taxonomies or plugging into default taxonomies.
729 * @todo Better formatting for DocBlock
732 * @since 4.4.0 Converted to return a WP_Term object if `$output` is `OBJECT`.
733 * The `$taxonomy` parameter was made optional.
735 * @global wpdb $wpdb WordPress database abstraction object.
736 * @see sanitize_term_field() The $context param lists the available values for get_term_by() $filter param.
738 * @param int|WP_Term|object $term If integer, term data will be fetched from the database, or from the cache if
739 * available. If stdClass object (as in the results of a database query), will apply
740 * filters and return a `WP_Term` object corresponding to the `$term` data. If `WP_Term`,
741 * will return `$term`.
742 * @param string $taxonomy Optional. Taxonomy name that $term is part of.
743 * @param string $output Constant OBJECT, ARRAY_A, or ARRAY_N
744 * @param string $filter Optional, default is raw or no WordPress defined filter will applied.
745 * @return mixed Type corresponding to `$output` on success or null on failure. When `$output` is `OBJECT`,
746 * a WP_Term instance is returned. If taxonomy does not exist then WP_Error will be returned.
748 function get_term( $term, $taxonomy = '', $output = OBJECT, $filter = 'raw' ) {
749 if ( empty( $term ) ) {
750 return new WP_Error( 'invalid_term', __( 'Empty Term' ) );
753 if ( $taxonomy && ! taxonomy_exists( $taxonomy ) ) {
754 return new WP_Error( 'invalid_taxonomy', __( 'Invalid taxonomy' ) );
757 if ( $term instanceof WP_Term ) {
759 } elseif ( is_object( $term ) ) {
760 if ( empty( $term->filter ) || 'raw' === $term->filter ) {
761 $_term = sanitize_term( $term, $taxonomy, 'raw' );
762 $_term = new WP_Term( $_term );
764 $_term = WP_Term::get_instance( $term->term_id );
767 $_term = WP_Term::get_instance( $term, $taxonomy );
770 if ( is_wp_error( $_term ) ) {
772 } elseif ( ! $_term ) {
780 * @since 4.4.0 `$_term` can now also be a WP_Term object.
782 * @param int|WP_Term $_term Term object or ID.
783 * @param string $taxonomy The taxonomy slug.
785 $_term = apply_filters( 'get_term', $_term, $taxonomy );
790 * The dynamic portion of the filter name, `$taxonomy`, refers
791 * to the taxonomy slug.
794 * @since 4.4.0 `$_term` can now also be a WP_Term object.
796 * @param int|WP_Term $_term Term object or ID.
797 * @param string $taxonomy The taxonomy slug.
799 $_term = apply_filters( "get_$taxonomy", $_term, $taxonomy );
801 // Sanitize term, according to the specified filter.
802 $_term->filter( $filter );
804 if ( $output == ARRAY_A ) {
805 return $_term->to_array();
806 } elseif ( $output == ARRAY_N ) {
807 return array_values( $_term->to_array() );
814 * Get all Term data from database by Term field and data.
816 * Warning: $value is not escaped for 'name' $field. You must do it yourself, if
819 * The default $field is 'id', therefore it is possible to also use null for
820 * field, but not recommended that you do so.
822 * If $value does not exist, the return value will be false. If $taxonomy exists
823 * and $field and $value combinations exist, the Term will be returned.
825 * @todo Better formatting for DocBlock.
828 * @since 4.4.0 `$taxonomy` is optional if `$field` is 'term_taxonomy_id'. Converted to return
829 * a WP_Term object if `$output` is `OBJECT`.
831 * @global wpdb $wpdb WordPress database abstraction object.
832 * @see sanitize_term_field() The $context param lists the available values for get_term_by() $filter param.
834 * @param string $field Either 'slug', 'name', 'id' (term_id), or 'term_taxonomy_id'
835 * @param string|int $value Search for this term value
836 * @param string $taxonomy Taxonomy name. Optional, if `$field` is 'term_taxonomy_id'.
837 * @param string $output Constant OBJECT, ARRAY_A, or ARRAY_N
838 * @param string $filter Optional, default is raw or no WordPress defined filter will applied.
839 * @return WP_Term|bool WP_Term instance on success. Will return false if `$taxonomy` does not exist
840 * or `$term` was not found.
842 function get_term_by( $field, $value, $taxonomy = '', $output = OBJECT, $filter = 'raw' ) {
845 // 'term_taxonomy_id' lookups don't require taxonomy checks.
846 if ( 'term_taxonomy_id' !== $field && ! taxonomy_exists( $taxonomy ) ) {
850 $tax_clause = $wpdb->prepare( "AND tt.taxonomy = %s", $taxonomy );
852 if ( 'slug' == $field ) {
854 $value = sanitize_title($value);
857 } elseif ( 'name' == $field ) {
858 // Assume already escaped
859 $value = wp_unslash($value);
861 } elseif ( 'term_taxonomy_id' == $field ) {
862 $value = (int) $value;
863 $_field = 'tt.term_taxonomy_id';
865 // No `taxonomy` clause when searching by 'term_taxonomy_id'.
868 $term = get_term( (int) $value, $taxonomy, $output, $filter );
869 if ( is_wp_error( $term ) || is_null( $term ) ) {
875 $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 $_field = %s $tax_clause LIMIT 1", $value ) );
879 // In the case of 'term_taxonomy_id', override the provided `$taxonomy` with whatever we find in the db.
880 if ( 'term_taxonomy_id' === $field ) {
881 $taxonomy = $term->taxonomy;
884 wp_cache_add( $term->term_id, $term, 'terms' );
886 return get_term( $term, $taxonomy, $output, $filter );
890 * Merge all term children into a single array of their IDs.
892 * This recursive function will merge all of the children of $term into the same
893 * array of term IDs. Only useful for taxonomies which are hierarchical.
895 * Will return an empty array if $term does not exist in $taxonomy.
899 * @param string $term_id ID of Term to get children.
900 * @param string $taxonomy Taxonomy Name.
901 * @return array|WP_Error List of Term IDs. WP_Error returned if `$taxonomy` does not exist.
903 function get_term_children( $term_id, $taxonomy ) {
904 if ( ! taxonomy_exists($taxonomy) )
905 return new WP_Error('invalid_taxonomy', __('Invalid taxonomy'));
907 $term_id = intval( $term_id );
909 $terms = _get_term_hierarchy($taxonomy);
911 if ( ! isset($terms[$term_id]) )
914 $children = $terms[$term_id];
916 foreach ( (array) $terms[$term_id] as $child ) {
917 if ( $term_id == $child ) {
921 if ( isset($terms[$child]) )
922 $children = array_merge($children, get_term_children($child, $taxonomy));
929 * Get sanitized Term field.
931 * The function is for contextual reasons and for simplicity of usage.
934 * @since 4.4.0 The `$taxonomy` parameter was made optional. `$term` can also now accept a WP_Term object.
936 * @see sanitize_term_field()
938 * @param string $field Term field to fetch.
939 * @param int|WP_Term $term Term ID or object.
940 * @param string $taxonomy Optional. Taxonomy Name. Default empty.
941 * @param string $context Optional, default is display. Look at sanitize_term_field() for available options.
942 * @return string|int|null|WP_Error Will return an empty string if $term is not an object or if $field is not set in $term.
944 function get_term_field( $field, $term, $taxonomy = '', $context = 'display' ) {
945 $term = get_term( $term, $taxonomy );
946 if ( is_wp_error($term) )
949 if ( !is_object($term) )
952 if ( !isset($term->$field) )
955 return sanitize_term_field( $field, $term->$field, $term->term_id, $term->taxonomy, $context );
959 * Sanitizes Term for editing.
961 * Return value is sanitize_term() and usage is for sanitizing the term for
962 * editing. Function is for contextual and simplicity.
966 * @param int|object $id Term ID or object.
967 * @param string $taxonomy Taxonomy name.
968 * @return string|int|null|WP_Error Will return empty string if $term is not an object.
970 function get_term_to_edit( $id, $taxonomy ) {
971 $term = get_term( $id, $taxonomy );
973 if ( is_wp_error($term) )
976 if ( !is_object($term) )
979 return sanitize_term($term, $taxonomy, 'edit');
983 * Retrieve the terms in a given taxonomy or list of taxonomies.
985 * You can fully inject any customizations to the query before it is sent, as
986 * well as control the output with a filter.
988 * The {@see 'get_terms'} filter will be called when the cache has the term and will
989 * pass the found term along with the array of $taxonomies and array of $args.
990 * This filter is also called before the array of terms is passed and will pass
991 * the array of terms, along with the $taxonomies and $args.
993 * The {@see 'list_terms_exclusions'} filter passes the compiled exclusions along with
996 * The {@see 'get_terms_orderby'} filter passes the `ORDER BY` clause for the query
997 * along with the $args array.
1000 * @since 4.2.0 Introduced 'name' and 'childless' parameters.
1001 * @since 4.4.0 Introduced the ability to pass 'term_id' as an alias of 'id' for the `orderby` parameter.
1002 * Introduced the 'meta_query' and 'update_term_meta_cache' parameters. Converted to return
1003 * a list of WP_Term objects.
1005 * @global wpdb $wpdb WordPress database abstraction object.
1006 * @global array $wp_filter
1008 * @param string|array $taxonomies Taxonomy name or list of Taxonomy names.
1009 * @param array|string $args {
1010 * Optional. Array or string of arguments to get terms.
1012 * @type string $orderby Field(s) to order terms by. Accepts term fields ('name', 'slug',
1013 * 'term_group', 'term_id', 'id', 'description'), 'count' for term
1014 * taxonomy count, 'include' to match the 'order' of the $include param,
1015 * or 'none' to skip ORDER BY. Defaults to 'name'.
1016 * @type string $order Whether to order terms in ascending or descending order.
1017 * Accepts 'ASC' (ascending) or 'DESC' (descending).
1019 * @type bool|int $hide_empty Whether to hide terms not assigned to any posts. Accepts
1020 * 1|true or 0|false. Default 1|true.
1021 * @type array|string $include Array or comma/space-separated string of term ids to include.
1022 * Default empty array.
1023 * @type array|string $exclude Array or comma/space-separated string of term ids to exclude.
1024 * If $include is non-empty, $exclude is ignored.
1025 * Default empty array.
1026 * @type array|string $exclude_tree Array or comma/space-separated string of term ids to exclude
1027 * along with all of their descendant terms. If $include is
1028 * non-empty, $exclude_tree is ignored. Default empty array.
1029 * @type int|string $number Maximum number of terms to return. Accepts ''|0 (all) or any
1030 * positive number. Default ''|0 (all).
1031 * @type int $offset The number by which to offset the terms query. Default empty.
1032 * @type string $fields Term fields to query for. Accepts 'all' (returns an array of complete
1033 * term objects), 'ids' (returns an array of ids), 'id=>parent' (returns
1034 * an associative array with ids as keys, parent term IDs as values),
1035 * 'names' (returns an array of term names), 'count' (returns the number
1036 * of matching terms), 'id=>name' (returns an associative array with ids
1037 * as keys, term names as values), or 'id=>slug' (returns an associative
1038 * array with ids as keys, term slugs as values). Default 'all'.
1039 * @type string|array $name Optional. Name or array of names to return term(s) for. Default empty.
1040 * @type string|array $slug Optional. Slug or array of slugs to return term(s) for. Default empty.
1041 * @type bool $hierarchical Whether to include terms that have non-empty descendants (even
1042 * if $hide_empty is set to true). Default true.
1043 * @type string $search Search criteria to match terms. Will be SQL-formatted with
1044 * wildcards before and after. Default empty.
1045 * @type string $name__like Retrieve terms with criteria by which a term is LIKE $name__like.
1047 * @type string $description__like Retrieve terms where the description is LIKE $description__like.
1049 * @type bool $pad_counts Whether to pad the quantity of a term's children in the quantity
1050 * of each term's "count" object variable. Default false.
1051 * @type string $get Whether to return terms regardless of ancestry or whether the terms
1052 * are empty. Accepts 'all' or empty (disabled). Default empty.
1053 * @type int $child_of Term ID to retrieve child terms of. If multiple taxonomies
1054 * are passed, $child_of is ignored. Default 0.
1055 * @type int|string $parent Parent term ID to retrieve direct-child terms of. Default empty.
1056 * @type bool $childless True to limit results to terms that have no children. This parameter
1057 * has no effect on non-hierarchical taxonomies. Default false.
1058 * @type string $cache_domain Unique cache key to be produced when this query is stored in an
1059 * object cache. Default is 'core'.
1060 * @type bool $update_term_meta_cache Whether to prime meta caches for matched terms. Default true.
1061 * @type array $meta_query Meta query clauses to limit retrieved terms by.
1062 * See `WP_Meta_Query`. Default empty.
1064 * @return array|int|WP_Error List of WP_Term instances and their children. Will return WP_Error, if any of $taxonomies
1067 function get_terms( $taxonomies, $args = '' ) {
1069 $empty_array = array();
1071 $single_taxonomy = ! is_array( $taxonomies ) || 1 === count( $taxonomies );
1072 if ( ! is_array( $taxonomies ) ) {
1073 $taxonomies = array( $taxonomies );
1076 foreach ( $taxonomies as $taxonomy ) {
1077 if ( ! taxonomy_exists($taxonomy) ) {
1078 return new WP_Error( 'invalid_taxonomy', __( 'Invalid taxonomy' ) );
1083 'orderby' => 'name',
1085 'hide_empty' => true,
1086 'include' => array(),
1087 'exclude' => array(),
1088 'exclude_tree' => array(),
1094 'hierarchical' => true,
1097 'description__like' => '',
1098 'pad_counts' => false,
1102 'childless' => false,
1103 'cache_domain' => 'core',
1104 'update_term_meta_cache' => true,
1109 * Filter the terms query default arguments.
1111 * Use 'get_terms_args' to filter the passed arguments.
1115 * @param array $defaults An array of default get_terms() arguments.
1116 * @param array $taxonomies An array of taxonomies.
1118 $args = wp_parse_args( $args, apply_filters( 'get_terms_defaults', $defaults, $taxonomies ) );
1120 $args['number'] = absint( $args['number'] );
1121 $args['offset'] = absint( $args['offset'] );
1123 // Save queries by not crawling the tree in the case of multiple taxes or a flat tax.
1124 $has_hierarchical_tax = false;
1125 foreach ( $taxonomies as $_tax ) {
1126 if ( is_taxonomy_hierarchical( $_tax ) ) {
1127 $has_hierarchical_tax = true;
1131 if ( ! $has_hierarchical_tax ) {
1132 $args['hierarchical'] = false;
1133 $args['pad_counts'] = false;
1136 // 'parent' overrides 'child_of'.
1137 if ( 0 < intval( $args['parent'] ) ) {
1138 $args['child_of'] = false;
1141 if ( 'all' == $args['get'] ) {
1142 $args['childless'] = false;
1143 $args['child_of'] = 0;
1144 $args['hide_empty'] = 0;
1145 $args['hierarchical'] = false;
1146 $args['pad_counts'] = false;
1150 * Filter the terms query arguments.
1154 * @param array $args An array of get_terms() arguments.
1155 * @param array $taxonomies An array of taxonomies.
1157 $args = apply_filters( 'get_terms_args', $args, $taxonomies );
1159 // Avoid the query if the queried parent/child_of term has no descendants.
1160 $child_of = $args['child_of'];
1161 $parent = $args['parent'];
1164 $_parent = $child_of;
1165 } elseif ( $parent ) {
1172 $in_hierarchy = false;
1173 foreach ( $taxonomies as $_tax ) {
1174 $hierarchy = _get_term_hierarchy( $_tax );
1176 if ( isset( $hierarchy[ $_parent ] ) ) {
1177 $in_hierarchy = true;
1181 if ( ! $in_hierarchy ) {
1182 return $empty_array;
1186 $_orderby = strtolower( $args['orderby'] );
1187 if ( 'count' == $_orderby ) {
1188 $orderby = 'tt.count';
1189 } elseif ( 'name' == $_orderby ) {
1190 $orderby = 't.name';
1191 } elseif ( 'slug' == $_orderby ) {
1192 $orderby = 't.slug';
1193 } elseif ( 'include' == $_orderby && ! empty( $args['include'] ) ) {
1194 $include = implode( ',', array_map( 'absint', $args['include'] ) );
1195 $orderby = "FIELD( t.term_id, $include )";
1196 } elseif ( 'term_group' == $_orderby ) {
1197 $orderby = 't.term_group';
1198 } elseif ( 'description' == $_orderby ) {
1199 $orderby = 'tt.description';
1200 } elseif ( 'none' == $_orderby ) {
1202 } elseif ( empty( $_orderby ) || 'id' == $_orderby || 'term_id' === $_orderby ) {
1203 $orderby = 't.term_id';
1205 $orderby = 't.name';
1209 * Filter the ORDERBY clause of the terms query.
1213 * @param string $orderby `ORDERBY` clause of the terms query.
1214 * @param array $args An array of terms query arguments.
1215 * @param array $taxonomies An array of taxonomies.
1217 $orderby = apply_filters( 'get_terms_orderby', $orderby, $args, $taxonomies );
1219 $order = strtoupper( $args['order'] );
1220 if ( ! empty( $orderby ) ) {
1221 $orderby = "ORDER BY $orderby";
1226 if ( '' !== $order && ! in_array( $order, array( 'ASC', 'DESC' ) ) ) {
1230 $where = "tt.taxonomy IN ('" . implode("', '", $taxonomies) . "')";
1232 $exclude = $args['exclude'];
1233 $exclude_tree = $args['exclude_tree'];
1234 $include = $args['include'];
1237 if ( ! empty( $include ) ) {
1240 $inclusions = implode( ',', wp_parse_id_list( $include ) );
1243 if ( ! empty( $inclusions ) ) {
1244 $inclusions = ' AND t.term_id IN ( ' . $inclusions . ' )';
1245 $where .= $inclusions;
1248 $exclusions = array();
1249 if ( ! empty( $exclude_tree ) ) {
1250 $exclude_tree = wp_parse_id_list( $exclude_tree );
1251 $excluded_children = $exclude_tree;
1252 foreach ( $exclude_tree as $extrunk ) {
1253 $excluded_children = array_merge(
1255 (array) get_terms( $taxonomies[0], array( 'child_of' => intval( $extrunk ), 'fields' => 'ids', 'hide_empty' => 0 ) )
1258 $exclusions = array_merge( $excluded_children, $exclusions );
1261 if ( ! empty( $exclude ) ) {
1262 $exclusions = array_merge( wp_parse_id_list( $exclude ), $exclusions );
1265 // 'childless' terms are those without an entry in the flattened term hierarchy.
1266 $childless = (bool) $args['childless'];
1268 foreach ( $taxonomies as $_tax ) {
1269 $term_hierarchy = _get_term_hierarchy( $_tax );
1270 $exclusions = array_merge( array_keys( $term_hierarchy ), $exclusions );
1274 if ( ! empty( $exclusions ) ) {
1275 $exclusions = ' AND t.term_id NOT IN (' . implode( ',', array_map( 'intval', $exclusions ) ) . ')';
1281 * Filter the terms to exclude from the terms query.
1285 * @param string $exclusions `NOT IN` clause of the terms query.
1286 * @param array $args An array of terms query arguments.
1287 * @param array $taxonomies An array of taxonomies.
1289 $exclusions = apply_filters( 'list_terms_exclusions', $exclusions, $args, $taxonomies );
1291 if ( ! empty( $exclusions ) ) {
1292 $where .= $exclusions;
1295 if ( ! empty( $args['name'] ) ) {
1296 $names = (array) $args['name'];
1297 foreach ( $names as &$_name ) {
1298 $_name = sanitize_term_field( 'name', $_name, 0, reset( $taxonomies ), 'db' );
1301 $where .= " AND t.name IN ('" . implode( "', '", array_map( 'esc_sql', $names ) ) . "')";
1304 if ( ! empty( $args['slug'] ) ) {
1305 if ( is_array( $args['slug'] ) ) {
1306 $slug = array_map( 'sanitize_title', $args['slug'] );
1307 $where .= " AND t.slug IN ('" . implode( "', '", $slug ) . "')";
1309 $slug = sanitize_title( $args['slug'] );
1310 $where .= " AND t.slug = '$slug'";
1314 if ( ! empty( $args['name__like'] ) ) {
1315 $where .= $wpdb->prepare( " AND t.name LIKE %s", '%' . $wpdb->esc_like( $args['name__like'] ) . '%' );
1318 if ( ! empty( $args['description__like'] ) ) {
1319 $where .= $wpdb->prepare( " AND tt.description LIKE %s", '%' . $wpdb->esc_like( $args['description__like'] ) . '%' );
1322 if ( '' !== $parent ) {
1323 $parent = (int) $parent;
1324 $where .= " AND tt.parent = '$parent'";
1327 $hierarchical = $args['hierarchical'];
1328 if ( 'count' == $args['fields'] ) {
1329 $hierarchical = false;
1331 if ( $args['hide_empty'] && !$hierarchical ) {
1332 $where .= ' AND tt.count > 0';
1335 $number = $args['number'];
1336 $offset = $args['offset'];
1338 // Don't limit the query results when we have to descend the family tree.
1339 if ( $number && ! $hierarchical && ! $child_of && '' === $parent ) {
1341 $limits = 'LIMIT ' . $offset . ',' . $number;
1343 $limits = 'LIMIT ' . $number;
1349 if ( ! empty( $args['search'] ) ) {
1350 $like = '%' . $wpdb->esc_like( $args['search'] ) . '%';
1351 $where .= $wpdb->prepare( ' AND ((t.name LIKE %s) OR (t.slug LIKE %s))', $like, $like );
1354 // Meta query support.
1356 if ( ! empty( $args['meta_query'] ) ) {
1357 $mquery = new WP_Meta_Query( $args['meta_query'] );
1358 $mq_sql = $mquery->get_sql( 'term', 't', 'term_id' );
1360 $join .= $mq_sql['join'];
1361 $where .= $mq_sql['where'];
1365 switch ( $args['fields'] ) {
1367 $selects = array( 't.*', 'tt.*' );
1371 $selects = array( 't.term_id', 'tt.parent', 'tt.count', 'tt.taxonomy' );
1374 $selects = array( 't.term_id', 'tt.parent', 'tt.count', 't.name', 'tt.taxonomy' );
1379 $selects = array( 'COUNT(*)' );
1382 $selects = array( 't.term_id', 't.name', 'tt.count', 'tt.taxonomy' );
1385 $selects = array( 't.term_id', 't.slug', 'tt.count', 'tt.taxonomy' );
1389 $_fields = $args['fields'];
1392 * Filter the fields to select in the terms query.
1394 * Field lists modified using this filter will only modify the term fields returned
1395 * by the function when the `$fields` parameter set to 'count' or 'all'. In all other
1396 * cases, the term fields in the results array will be determined by the `$fields`
1399 * Use of this filter can result in unpredictable behavior, and is not recommended.
1403 * @param array $selects An array of fields to select for the terms query.
1404 * @param array $args An array of term query arguments.
1405 * @param array $taxonomies An array of taxonomies.
1407 $fields = implode( ', ', apply_filters( 'get_terms_fields', $selects, $args, $taxonomies ) );
1409 $join .= " INNER JOIN $wpdb->term_taxonomy AS tt ON t.term_id = tt.term_id";
1411 $pieces = array( 'fields', 'join', 'where', 'orderby', 'order', 'limits' );
1414 * Filter the terms query SQL clauses.
1418 * @param array $pieces Terms query SQL clauses.
1419 * @param array $taxonomies An array of taxonomies.
1420 * @param array $args An array of terms query arguments.
1422 $clauses = apply_filters( 'terms_clauses', compact( $pieces ), $taxonomies, $args );
1424 $fields = isset( $clauses[ 'fields' ] ) ? $clauses[ 'fields' ] : '';
1425 $join = isset( $clauses[ 'join' ] ) ? $clauses[ 'join' ] : '';
1426 $where = isset( $clauses[ 'where' ] ) ? $clauses[ 'where' ] : '';
1427 $orderby = isset( $clauses[ 'orderby' ] ) ? $clauses[ 'orderby' ] : '';
1428 $order = isset( $clauses[ 'order' ] ) ? $clauses[ 'order' ] : '';
1429 $limits = isset( $clauses[ 'limits' ] ) ? $clauses[ 'limits' ] : '';
1431 $query = "SELECT $fields FROM $wpdb->terms AS t $join WHERE $where $orderby $order $limits";
1433 // $args can be anything. Only use the args defined in defaults to compute the key.
1434 $key = md5( serialize( wp_array_slice_assoc( $args, array_keys( $defaults ) ) ) . serialize( $taxonomies ) . $query );
1435 $last_changed = wp_cache_get( 'last_changed', 'terms' );
1436 if ( ! $last_changed ) {
1437 $last_changed = microtime();
1438 wp_cache_set( 'last_changed', $last_changed, 'terms' );
1440 $cache_key = "get_terms:$key:$last_changed";
1441 $cache = wp_cache_get( $cache_key, 'terms' );
1442 if ( false !== $cache ) {
1443 if ( 'all' === $_fields ) {
1444 $cache = array_map( 'get_term', $cache );
1448 * Filter the given taxonomy's terms cache.
1452 * @param array $cache Cached array of terms for the given taxonomy.
1453 * @param array $taxonomies An array of taxonomies.
1454 * @param array $args An array of get_terms() arguments.
1456 return apply_filters( 'get_terms', $cache, $taxonomies, $args );
1459 if ( 'count' == $_fields ) {
1460 return $wpdb->get_var( $query );
1463 $terms = $wpdb->get_results($query);
1464 if ( 'all' == $_fields ) {
1465 update_term_cache( $terms );
1468 // Prime termmeta cache.
1469 if ( $args['update_term_meta_cache'] ) {
1470 $term_ids = wp_list_pluck( $terms, 'term_id' );
1471 update_termmeta_cache( $term_ids );
1474 if ( empty($terms) ) {
1475 wp_cache_add( $cache_key, array(), 'terms', DAY_IN_SECONDS );
1477 /** This filter is documented in wp-includes/taxonomy.php */
1478 return apply_filters( 'get_terms', array(), $taxonomies, $args );
1482 foreach ( $taxonomies as $_tax ) {
1483 $children = _get_term_hierarchy( $_tax );
1484 if ( ! empty( $children ) ) {
1485 $terms = _get_term_children( $child_of, $terms, $_tax );
1490 // Update term counts to include children.
1491 if ( $args['pad_counts'] && 'all' == $_fields ) {
1492 foreach ( $taxonomies as $_tax ) {
1493 _pad_term_counts( $terms, $_tax );
1497 // Make sure we show empty categories that have children.
1498 if ( $hierarchical && $args['hide_empty'] && is_array( $terms ) ) {
1499 foreach ( $terms as $k => $term ) {
1500 if ( ! $term->count ) {
1501 $children = get_term_children( $term->term_id, $term->taxonomy );
1502 if ( is_array( $children ) ) {
1503 foreach ( $children as $child_id ) {
1504 $child = get_term( $child_id, $term->taxonomy );
1505 if ( $child->count ) {
1511 // It really is empty.
1518 if ( 'id=>parent' == $_fields ) {
1519 foreach ( $terms as $term ) {
1520 $_terms[ $term->term_id ] = $term->parent;
1522 } elseif ( 'ids' == $_fields ) {
1523 foreach ( $terms as $term ) {
1524 $_terms[] = $term->term_id;
1526 } elseif ( 'names' == $_fields ) {
1527 foreach ( $terms as $term ) {
1528 $_terms[] = $term->name;
1530 } elseif ( 'id=>name' == $_fields ) {
1531 foreach ( $terms as $term ) {
1532 $_terms[ $term->term_id ] = $term->name;
1534 } elseif ( 'id=>slug' == $_fields ) {
1535 foreach ( $terms as $term ) {
1536 $_terms[ $term->term_id ] = $term->slug;
1540 if ( ! empty( $_terms ) ) {
1544 if ( $number && is_array( $terms ) && count( $terms ) > $number ) {
1545 $terms = array_slice( $terms, $offset, $number );
1548 wp_cache_add( $cache_key, $terms, 'terms', DAY_IN_SECONDS );
1550 if ( 'all' === $_fields ) {
1551 $terms = array_map( 'get_term', $terms );
1554 /** This filter is documented in wp-includes/taxonomy.php */
1555 return apply_filters( 'get_terms', $terms, $taxonomies, $args );
1559 * Adds metadata to a term.
1563 * @param int $term_id Term ID.
1564 * @param string $meta_key Metadata name.
1565 * @param mixed $meta_value Metadata value.
1566 * @param bool $unique Optional. Whether to bail if an entry with the same key is found for the term.
1568 * @return int|WP_Error|bool Meta ID on success. WP_Error when term_id is ambiguous between taxonomies.
1571 function add_term_meta( $term_id, $meta_key, $meta_value, $unique = false ) {
1572 // Bail if term meta table is not installed.
1573 if ( get_option( 'db_version' ) < 34370 ) {
1577 if ( wp_term_is_shared( $term_id ) ) {
1578 return new WP_Error( 'ambiguous_term_id', __( 'Term meta cannot be added to terms that are shared between taxonomies.'), $term_id );
1581 $added = add_metadata( 'term', $term_id, $meta_key, $meta_value, $unique );
1583 // Bust term query cache.
1585 wp_cache_set( 'last_changed', microtime(), 'terms' );
1592 * Removes metadata matching criteria from a term.
1596 * @param int $term_id Term ID.
1597 * @param string $meta_key Metadata name.
1598 * @param mixed $meta_value Optional. Metadata value. If provided, rows will only be removed that match the value.
1599 * @return bool True on success, false on failure.
1601 function delete_term_meta( $term_id, $meta_key, $meta_value = '' ) {
1602 // Bail if term meta table is not installed.
1603 if ( get_option( 'db_version' ) < 34370 ) {
1607 $deleted = delete_metadata( 'term', $term_id, $meta_key, $meta_value );
1609 // Bust term query cache.
1611 wp_cache_set( 'last_changed', microtime(), 'terms' );
1618 * Retrieves metadata for a term.
1622 * @param int $term_id Term ID.
1623 * @param string $key Optional. The meta key to retrieve. If no key is provided, fetches all metadata for the term.
1624 * @param bool $single Whether to return a single value. If false, an array of all values matching the
1625 * `$term_id`/`$key` pair will be returned. Default: false.
1626 * @return mixed If `$single` is false, an array of metadata values. If `$single` is true, a single metadata value.
1628 function get_term_meta( $term_id, $key = '', $single = false ) {
1629 // Bail if term meta table is not installed.
1630 if ( get_option( 'db_version' ) < 34370 ) {
1634 return get_metadata( 'term', $term_id, $key, $single );
1638 * Updates term metadata.
1640 * Use the `$prev_value` parameter to differentiate between meta fields with the same key and term ID.
1642 * If the meta field for the term does not exist, it will be added.
1646 * @param int $term_id Term ID.
1647 * @param string $meta_key Metadata key.
1648 * @param mixed $meta_value Metadata value.
1649 * @param mixed $prev_value Optional. Previous value to check before removing.
1650 * @return int|WP_Error|bool Meta ID if the key didn't previously exist. True on successful update.
1651 * WP_Error when term_id is ambiguous between taxonomies. False on failure.
1653 function update_term_meta( $term_id, $meta_key, $meta_value, $prev_value = '' ) {
1654 // Bail if term meta table is not installed.
1655 if ( get_option( 'db_version' ) < 34370 ) {
1659 if ( wp_term_is_shared( $term_id ) ) {
1660 return new WP_Error( 'ambiguous_term_id', __( 'Term meta cannot be added to terms that are shared between taxonomies.'), $term_id );
1663 $updated = update_metadata( 'term', $term_id, $meta_key, $meta_value, $prev_value );
1665 // Bust term query cache.
1667 wp_cache_set( 'last_changed', microtime(), 'terms' );
1674 * Updates metadata cache for list of term IDs.
1676 * Performs SQL query to retrieve all metadata for the terms matching `$term_ids` and stores them in the cache.
1677 * Subsequent calls to `get_term_meta()` will not need to query the database.
1681 * @param array $term_ids List of term IDs.
1682 * @return array|false Returns false if there is nothing to update. Returns an array of metadata on success.
1684 function update_termmeta_cache( $term_ids ) {
1685 // Bail if term meta table is not installed.
1686 if ( get_option( 'db_version' ) < 34370 ) {
1690 return update_meta_cache( 'term', $term_ids );
1694 * Check if Term exists.
1696 * Formerly is_term(), introduced in 2.3.0.
1700 * @global wpdb $wpdb WordPress database abstraction object.
1702 * @param int|string $term The term to check
1703 * @param string $taxonomy The taxonomy name to use
1704 * @param int $parent Optional. ID of parent term under which to confine the exists search.
1705 * @return mixed Returns null if the term does not exist. Returns the term ID
1706 * if no taxonomy is specified and the term ID exists. Returns
1707 * an array of the term ID and the term taxonomy ID the taxonomy
1708 * is specified and the pairing exists.
1710 function term_exists( $term, $taxonomy = '', $parent = null ) {
1713 $select = "SELECT term_id FROM $wpdb->terms as t WHERE ";
1714 $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 ";
1716 if ( is_int($term) ) {
1719 $where = 't.term_id = %d';
1720 if ( !empty($taxonomy) )
1721 return $wpdb->get_row( $wpdb->prepare( $tax_select . $where . " AND tt.taxonomy = %s", $term, $taxonomy ), ARRAY_A );
1723 return $wpdb->get_var( $wpdb->prepare( $select . $where, $term ) );
1726 $term = trim( wp_unslash( $term ) );
1727 $slug = sanitize_title( $term );
1729 $where = 't.slug = %s';
1730 $else_where = 't.name = %s';
1731 $where_fields = array($slug);
1732 $else_where_fields = array($term);
1733 $orderby = 'ORDER BY t.term_id ASC';
1735 if ( !empty($taxonomy) ) {
1736 if ( is_numeric( $parent ) ) {
1737 $parent = (int) $parent;
1738 $where_fields[] = $parent;
1739 $else_where_fields[] = $parent;
1740 $where .= ' AND tt.parent = %d';
1741 $else_where .= ' AND tt.parent = %d';
1744 $where_fields[] = $taxonomy;
1745 $else_where_fields[] = $taxonomy;
1747 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) )
1750 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);
1753 if ( $result = $wpdb->get_var( $wpdb->prepare("SELECT term_id FROM $wpdb->terms as t WHERE $where $orderby $limit", $where_fields) ) )
1756 return $wpdb->get_var( $wpdb->prepare("SELECT term_id FROM $wpdb->terms as t WHERE $else_where $orderby $limit", $else_where_fields) );
1760 * Check if a term is an ancestor of another term.
1762 * You can use either an id or the term object for both parameters.
1766 * @param int|object $term1 ID or object to check if this is the parent term.
1767 * @param int|object $term2 The child term.
1768 * @param string $taxonomy Taxonomy name that $term1 and `$term2` belong to.
1769 * @return bool Whether `$term2` is a child of `$term1`.
1771 function term_is_ancestor_of( $term1, $term2, $taxonomy ) {
1772 if ( ! isset( $term1->term_id ) )
1773 $term1 = get_term( $term1, $taxonomy );
1774 if ( ! isset( $term2->parent ) )
1775 $term2 = get_term( $term2, $taxonomy );
1777 if ( empty( $term1->term_id ) || empty( $term2->parent ) )
1779 if ( $term2->parent == $term1->term_id )
1782 return term_is_ancestor_of( $term1, get_term( $term2->parent, $taxonomy ), $taxonomy );
1786 * Sanitize Term all fields.
1788 * Relies on sanitize_term_field() to sanitize the term. The difference is that
1789 * this function will sanitize <strong>all</strong> fields. The context is based
1790 * on sanitize_term_field().
1792 * The $term is expected to be either an array or an object.
1796 * @param array|object $term The term to check.
1797 * @param string $taxonomy The taxonomy name to use.
1798 * @param string $context Optional. Context in which to sanitize the term. Accepts 'edit', 'db',
1799 * 'display', 'attribute', or 'js'. Default 'display'.
1800 * @return array|object Term with all fields sanitized.
1802 function sanitize_term($term, $taxonomy, $context = 'display') {
1803 $fields = array( 'term_id', 'name', 'description', 'slug', 'count', 'parent', 'term_group', 'term_taxonomy_id', 'object_id' );
1805 $do_object = is_object( $term );
1807 $term_id = $do_object ? $term->term_id : (isset($term['term_id']) ? $term['term_id'] : 0);
1809 foreach ( (array) $fields as $field ) {
1811 if ( isset($term->$field) )
1812 $term->$field = sanitize_term_field($field, $term->$field, $term_id, $taxonomy, $context);
1814 if ( isset($term[$field]) )
1815 $term[$field] = sanitize_term_field($field, $term[$field], $term_id, $taxonomy, $context);
1820 $term->filter = $context;
1822 $term['filter'] = $context;
1828 * Cleanse the field value in the term based on the context.
1830 * Passing a term field value through the function should be assumed to have
1831 * cleansed the value for whatever context the term field is going to be used.
1833 * If no context or an unsupported context is given, then default filters will
1836 * There are enough filters for each context to support a custom filtering
1837 * without creating your own filter function. Simply create a function that
1838 * hooks into the filter you need.
1842 * @param string $field Term field to sanitize.
1843 * @param string $value Search for this term value.
1844 * @param int $term_id Term ID.
1845 * @param string $taxonomy Taxonomy Name.
1846 * @param string $context Context in which to sanitize the term field. Accepts 'edit', 'db', 'display',
1847 * 'attribute', or 'js'.
1848 * @return mixed Sanitized field.
1850 function sanitize_term_field($field, $value, $term_id, $taxonomy, $context) {
1851 $int_fields = array( 'parent', 'term_id', 'count', 'term_group', 'term_taxonomy_id', 'object_id' );
1852 if ( in_array( $field, $int_fields ) ) {
1853 $value = (int) $value;
1858 if ( 'raw' == $context )
1861 if ( 'edit' == $context ) {
1864 * Filter a term field to edit before it is sanitized.
1866 * The dynamic portion of the filter name, `$field`, refers to the term field.
1870 * @param mixed $value Value of the term field.
1871 * @param int $term_id Term ID.
1872 * @param string $taxonomy Taxonomy slug.
1874 $value = apply_filters( "edit_term_{$field}", $value, $term_id, $taxonomy );
1877 * Filter the taxonomy field to edit before it is sanitized.
1879 * The dynamic portions of the filter name, `$taxonomy` and `$field`, refer
1880 * to the taxonomy slug and taxonomy field, respectively.
1884 * @param mixed $value Value of the taxonomy field to edit.
1885 * @param int $term_id Term ID.
1887 $value = apply_filters( "edit_{$taxonomy}_{$field}", $value, $term_id );
1889 if ( 'description' == $field )
1890 $value = esc_html($value); // textarea_escaped
1892 $value = esc_attr($value);
1893 } elseif ( 'db' == $context ) {
1896 * Filter a term field value before it is sanitized.
1898 * The dynamic portion of the filter name, `$field`, refers to the term field.
1902 * @param mixed $value Value of the term field.
1903 * @param string $taxonomy Taxonomy slug.
1905 $value = apply_filters( "pre_term_{$field}", $value, $taxonomy );
1908 * Filter a taxonomy field before it is sanitized.
1910 * The dynamic portions of the filter name, `$taxonomy` and `$field`, refer
1911 * to the taxonomy slug and field name, respectively.
1915 * @param mixed $value Value of the taxonomy field.
1917 $value = apply_filters( "pre_{$taxonomy}_{$field}", $value );
1919 // Back compat filters
1920 if ( 'slug' == $field ) {
1922 * Filter the category nicename before it is sanitized.
1924 * Use the pre_{$taxonomy}_{$field} hook instead.
1928 * @param string $value The category nicename.
1930 $value = apply_filters( 'pre_category_nicename', $value );
1933 } elseif ( 'rss' == $context ) {
1936 * Filter the term field for use in RSS.
1938 * The dynamic portion of the filter name, `$field`, refers to the term field.
1942 * @param mixed $value Value of the term field.
1943 * @param string $taxonomy Taxonomy slug.
1945 $value = apply_filters( "term_{$field}_rss", $value, $taxonomy );
1948 * Filter the taxonomy field for use in RSS.
1950 * The dynamic portions of the hook name, `$taxonomy`, and `$field`, refer
1951 * to the taxonomy slug and field name, respectively.
1955 * @param mixed $value Value of the taxonomy field.
1957 $value = apply_filters( "{$taxonomy}_{$field}_rss", $value );
1959 // Use display filters by default.
1962 * Filter the term field sanitized for display.
1964 * The dynamic portion of the filter name, `$field`, refers to the term field name.
1968 * @param mixed $value Value of the term field.
1969 * @param int $term_id Term ID.
1970 * @param string $taxonomy Taxonomy slug.
1971 * @param string $context Context to retrieve the term field value.
1973 $value = apply_filters( "term_{$field}", $value, $term_id, $taxonomy, $context );
1976 * Filter the taxonomy field sanitized for display.
1978 * The dynamic portions of the filter name, `$taxonomy`, and `$field`, refer
1979 * to the taxonomy slug and taxonomy field, respectively.
1983 * @param mixed $value Value of the taxonomy field.
1984 * @param int $term_id Term ID.
1985 * @param string $context Context to retrieve the taxonomy field value.
1987 $value = apply_filters( "{$taxonomy}_{$field}", $value, $term_id, $context );
1990 if ( 'attribute' == $context ) {
1991 $value = esc_attr($value);
1992 } elseif ( 'js' == $context ) {
1993 $value = esc_js($value);
1999 * Count how many terms are in Taxonomy.
2001 * Default $args is 'hide_empty' which can be 'hide_empty=true' or array('hide_empty' => true).
2003 * @todo Document $args as a hash notation.
2007 * @param string $taxonomy Taxonomy name
2008 * @param array|string $args Overwrite defaults. See get_terms()
2009 * @return array|int|WP_Error How many terms are in $taxonomy. WP_Error if $taxonomy does not exist.
2011 function wp_count_terms( $taxonomy, $args = array() ) {
2012 $defaults = array('hide_empty' => false);
2013 $args = wp_parse_args($args, $defaults);
2015 // backwards compatibility
2016 if ( isset($args['ignore_empty']) ) {
2017 $args['hide_empty'] = $args['ignore_empty'];
2018 unset($args['ignore_empty']);
2021 $args['fields'] = 'count';
2023 return get_terms($taxonomy, $args);
2027 * Will unlink the object from the taxonomy or taxonomies.
2029 * Will remove all relationships between the object and any terms in
2030 * a particular taxonomy or taxonomies. Does not remove the term or
2035 * @param int $object_id The term Object Id that refers to the term.
2036 * @param string|array $taxonomies List of Taxonomy Names or single Taxonomy name.
2038 function wp_delete_object_term_relationships( $object_id, $taxonomies ) {
2039 $object_id = (int) $object_id;
2041 if ( !is_array($taxonomies) )
2042 $taxonomies = array($taxonomies);
2044 foreach ( (array) $taxonomies as $taxonomy ) {
2045 $term_ids = wp_get_object_terms( $object_id, $taxonomy, array( 'fields' => 'ids' ) );
2046 $term_ids = array_map( 'intval', $term_ids );
2047 wp_remove_object_terms( $object_id, $term_ids, $taxonomy );
2052 * Removes a term from the database.
2054 * If the term is a parent of other terms, then the children will be updated to
2055 * that term's parent.
2057 * Metadata associated with the term will be deleted.
2059 * The `$args` 'default' will only override the terms found, if there is only one
2060 * term found. Any other and the found terms are used.
2062 * The $args 'force_default' will force the term supplied as default to be
2063 * assigned even if the object was not going to be termless
2065 * @todo Document $args as a hash notation.
2069 * @global wpdb $wpdb WordPress database abstraction object.
2071 * @param int $term Term ID.
2072 * @param string $taxonomy Taxonomy Name.
2073 * @param array|string $args Optional. Change 'default' term id and override found term ids.
2074 * @return bool|int|WP_Error Returns false if not term; true if completes delete action.
2076 function wp_delete_term( $term, $taxonomy, $args = array() ) {
2079 $term = (int) $term;
2081 if ( ! $ids = term_exists($term, $taxonomy) )
2083 if ( is_wp_error( $ids ) )
2086 $tt_id = $ids['term_taxonomy_id'];
2088 $defaults = array();
2090 if ( 'category' == $taxonomy ) {
2091 $defaults['default'] = get_option( 'default_category' );
2092 if ( $defaults['default'] == $term )
2093 return 0; // Don't delete the default category
2096 $args = wp_parse_args($args, $defaults);
2098 if ( isset( $args['default'] ) ) {
2099 $default = (int) $args['default'];
2100 if ( ! term_exists( $default, $taxonomy ) ) {
2105 if ( isset( $args['force_default'] ) ) {
2106 $force_default = $args['force_default'];
2110 * Fires when deleting a term, before any modifications are made to posts or terms.
2114 * @param int $term Term ID.
2115 * @param string $taxonomy Taxonomy Name.
2117 do_action( 'pre_delete_term', $term, $taxonomy );
2119 // Update children to point to new parent
2120 if ( is_taxonomy_hierarchical($taxonomy) ) {
2121 $term_obj = get_term($term, $taxonomy);
2122 if ( is_wp_error( $term_obj ) )
2124 $parent = $term_obj->parent;
2126 $edit_ids = $wpdb->get_results( "SELECT term_id, term_taxonomy_id FROM $wpdb->term_taxonomy WHERE `parent` = " . (int)$term_obj->term_id );
2127 $edit_tt_ids = wp_list_pluck( $edit_ids, 'term_taxonomy_id' );
2130 * Fires immediately before a term to delete's children are reassigned a parent.
2134 * @param array $edit_tt_ids An array of term taxonomy IDs for the given term.
2136 do_action( 'edit_term_taxonomies', $edit_tt_ids );
2138 $wpdb->update( $wpdb->term_taxonomy, compact( 'parent' ), array( 'parent' => $term_obj->term_id) + compact( 'taxonomy' ) );
2140 // Clean the cache for all child terms.
2141 $edit_term_ids = wp_list_pluck( $edit_ids, 'term_id' );
2142 clean_term_cache( $edit_term_ids, $taxonomy );
2145 * Fires immediately after a term to delete's children are reassigned a parent.
2149 * @param array $edit_tt_ids An array of term taxonomy IDs for the given term.
2151 do_action( 'edited_term_taxonomies', $edit_tt_ids );
2154 // Get the term before deleting it or its term relationships so we can pass to actions below.
2155 $deleted_term = get_term( $term, $taxonomy );
2157 $objects = $wpdb->get_col( $wpdb->prepare( "SELECT object_id FROM $wpdb->term_relationships WHERE term_taxonomy_id = %d", $tt_id ) );
2159 foreach ( (array) $objects as $object ) {
2160 $terms = wp_get_object_terms($object, $taxonomy, array('fields' => 'ids', 'orderby' => 'none'));
2161 if ( 1 == count($terms) && isset($default) ) {
2162 $terms = array($default);
2164 $terms = array_diff($terms, array($term));
2165 if (isset($default) && isset($force_default) && $force_default)
2166 $terms = array_merge($terms, array($default));
2168 $terms = array_map('intval', $terms);
2169 wp_set_object_terms($object, $terms, $taxonomy);
2172 // Clean the relationship caches for all object types using this term.
2173 $tax_object = get_taxonomy( $taxonomy );
2174 foreach ( $tax_object->object_type as $object_type )
2175 clean_object_term_cache( $objects, $object_type );
2177 $term_meta_ids = $wpdb->get_col( $wpdb->prepare( "SELECT meta_id FROM $wpdb->termmeta WHERE term_id = %d ", $term ) );
2178 foreach ( $term_meta_ids as $mid ) {
2179 delete_metadata_by_mid( 'term', $mid );
2183 * Fires immediately before a term taxonomy ID is deleted.
2187 * @param int $tt_id Term taxonomy ID.
2189 do_action( 'delete_term_taxonomy', $tt_id );
2190 $wpdb->delete( $wpdb->term_taxonomy, array( 'term_taxonomy_id' => $tt_id ) );
2193 * Fires immediately after a term taxonomy ID is deleted.
2197 * @param int $tt_id Term taxonomy ID.
2199 do_action( 'deleted_term_taxonomy', $tt_id );
2201 // Delete the term if no taxonomies use it.
2202 if ( !$wpdb->get_var( $wpdb->prepare( "SELECT COUNT(*) FROM $wpdb->term_taxonomy WHERE term_id = %d", $term) ) )
2203 $wpdb->delete( $wpdb->terms, array( 'term_id' => $term ) );
2205 clean_term_cache($term, $taxonomy);
2208 * Fires after a term is deleted from the database and the cache is cleaned.
2212 * @param int $term Term ID.
2213 * @param int $tt_id Term taxonomy ID.
2214 * @param string $taxonomy Taxonomy slug.
2215 * @param mixed $deleted_term Copy of the already-deleted term, in the form specified
2216 * by the parent function. WP_Error otherwise.
2218 do_action( 'delete_term', $term, $tt_id, $taxonomy, $deleted_term );
2221 * Fires after a term in a specific taxonomy is deleted.
2223 * The dynamic portion of the hook name, `$taxonomy`, refers to the specific
2224 * taxonomy the term belonged to.
2228 * @param int $term Term ID.
2229 * @param int $tt_id Term taxonomy ID.
2230 * @param mixed $deleted_term Copy of the already-deleted term, in the form specified
2231 * by the parent function. WP_Error otherwise.
2233 do_action( "delete_$taxonomy", $term, $tt_id, $deleted_term );
2239 * Deletes one existing category.
2243 * @param int $cat_ID
2244 * @return bool|int|WP_Error Returns true if completes delete action; false if term doesn't exist;
2245 * Zero on attempted deletion of default Category; WP_Error object is also a possibility.
2247 function wp_delete_category( $cat_ID ) {
2248 return wp_delete_term( $cat_ID, 'category' );
2252 * Retrieves the terms associated with the given object(s), in the supplied taxonomies.
2255 * @since 4.2.0 Added support for 'taxonomy', 'parent', and 'term_taxonomy_id' values of `$orderby`.
2256 * Introduced `$parent` argument.
2257 * @since 4.4.0 Introduced `$meta_query` and `$update_term_meta_cache` arguments. When `$fields` is 'all' or
2258 * 'all_with_object_id', an array of `WP_Term` objects will be returned.
2260 * @global wpdb $wpdb WordPress database abstraction object.
2262 * @param int|array $object_ids The ID(s) of the object(s) to retrieve.
2263 * @param string|array $taxonomies The taxonomies to retrieve terms from.
2264 * @param array|string $args {
2265 * Array of arguments.
2266 * @type string $orderby Field by which results should be sorted. Accepts 'name', 'count', 'slug',
2267 * 'term_group', 'term_order', 'taxonomy', 'parent', or 'term_taxonomy_id'.
2269 * @type string $order Sort order. Accepts 'ASC' or 'DESC'. Default 'ASC'.
2270 * @type string $fields Fields to return for matched terms. Accepts 'all', 'ids', 'names', and
2271 * 'all_with_object_id'. Note that 'all' or 'all_with_object_id' will result
2272 * in an array of term objects being returned, 'ids' will return an array of
2273 * integers, and 'names' an array of strings.
2274 * @type int $parent Optional. Limit results to the direct children of a given term ID.
2275 * @type bool $update_term_meta_cache Whether to prime termmeta cache for matched terms. Only applies when
2276 * `$fields` is 'all', 'all_with_object_id', or 'term_id'. Default true.
2277 * @type array $meta_query Meta query clauses to limit retrieved terms by. See `WP_Meta_Query`.
2280 * @return array|WP_Error The requested term data or empty array if no terms found.
2281 * WP_Error if any of the $taxonomies don't exist.
2283 function wp_get_object_terms($object_ids, $taxonomies, $args = array()) {
2286 if ( empty( $object_ids ) || empty( $taxonomies ) )
2289 if ( !is_array($taxonomies) )
2290 $taxonomies = array($taxonomies);
2292 foreach ( $taxonomies as $taxonomy ) {
2293 if ( ! taxonomy_exists($taxonomy) )
2294 return new WP_Error('invalid_taxonomy', __('Invalid taxonomy'));
2297 if ( !is_array($object_ids) )
2298 $object_ids = array($object_ids);
2299 $object_ids = array_map('intval', $object_ids);
2302 'orderby' => 'name',
2306 'update_term_meta_cache' => true,
2309 $args = wp_parse_args( $args, $defaults );
2312 if ( count($taxonomies) > 1 ) {
2313 foreach ( $taxonomies as $index => $taxonomy ) {
2314 $t = get_taxonomy($taxonomy);
2315 if ( isset($t->args) && is_array($t->args) && $args != array_merge($args, $t->args) ) {
2316 unset($taxonomies[$index]);
2317 $terms = array_merge($terms, wp_get_object_terms($object_ids, $taxonomy, array_merge($args, $t->args)));
2321 $t = get_taxonomy($taxonomies[0]);
2322 if ( isset($t->args) && is_array($t->args) )
2323 $args = array_merge($args, $t->args);
2326 $orderby = $args['orderby'];
2327 $order = $args['order'];
2328 $fields = $args['fields'];
2330 if ( in_array( $orderby, array( 'term_id', 'name', 'slug', 'term_group' ) ) ) {
2331 $orderby = "t.$orderby";
2332 } elseif ( in_array( $orderby, array( 'count', 'parent', 'taxonomy', 'term_taxonomy_id' ) ) ) {
2333 $orderby = "tt.$orderby";
2334 } elseif ( 'term_order' === $orderby ) {
2335 $orderby = 'tr.term_order';
2336 } elseif ( 'none' === $orderby ) {
2340 $orderby = 't.term_id';
2343 // tt_ids queries can only be none or tr.term_taxonomy_id
2344 if ( ('tt_ids' == $fields) && !empty($orderby) )
2345 $orderby = 'tr.term_taxonomy_id';
2347 if ( !empty($orderby) )
2348 $orderby = "ORDER BY $orderby";
2350 $order = strtoupper( $order );
2351 if ( '' !== $order && ! in_array( $order, array( 'ASC', 'DESC' ) ) )
2354 $taxonomy_array = $taxonomies;
2355 $object_id_array = $object_ids;
2356 $taxonomies = "'" . implode("', '", $taxonomies) . "'";
2357 $object_ids = implode(', ', $object_ids);
2360 if ( 'all' == $fields ) {
2361 $select_this = 't.*, tt.*';
2362 } elseif ( 'ids' == $fields ) {
2363 $select_this = 't.term_id';
2364 } elseif ( 'names' == $fields ) {
2365 $select_this = 't.name';
2366 } elseif ( 'slugs' == $fields ) {
2367 $select_this = 't.slug';
2368 } elseif ( 'all_with_object_id' == $fields ) {
2369 $select_this = 't.*, tt.*, tr.object_id';
2373 "tt.taxonomy IN ($taxonomies)",
2374 "tr.object_id IN ($object_ids)",
2377 if ( '' !== $args['parent'] ) {
2378 $where[] = $wpdb->prepare( 'tt.parent = %d', $args['parent'] );
2381 // Meta query support.
2382 $meta_query_join = '';
2383 if ( ! empty( $args['meta_query'] ) ) {
2384 $mquery = new WP_Meta_Query( $args['meta_query'] );
2385 $mq_sql = $mquery->get_sql( 'term', 't', 'term_id' );
2387 $meta_query_join .= $mq_sql['join'];
2389 // Strip leading AND.
2390 $where[] = preg_replace( '/^\s*AND/', '', $mq_sql['where'] );
2393 $where = implode( ' AND ', $where );
2395 $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 $meta_query_join WHERE $where $orderby $order";
2398 if ( 'all' == $fields || 'all_with_object_id' == $fields ) {
2399 $_terms = $wpdb->get_results( $query );
2400 $object_id_index = array();
2401 foreach ( $_terms as $key => $term ) {
2402 $term = sanitize_term( $term, $taxonomy, 'raw' );
2403 $_terms[ $key ] = $term;
2405 if ( isset( $term->object_id ) ) {
2406 $object_id_index[ $key ] = $term->object_id;
2410 update_term_cache( $_terms );
2411 $_terms = array_map( 'get_term', $_terms );
2413 // Re-add the object_id data, which is lost when fetching terms from cache.
2414 if ( 'all_with_object_id' === $fields ) {
2415 foreach ( $_terms as $key => $_term ) {
2416 if ( isset( $object_id_index[ $key ] ) ) {
2417 $_term->object_id = $object_id_index[ $key ];
2422 $terms = array_merge( $terms, $_terms );
2425 } elseif ( 'ids' == $fields || 'names' == $fields || 'slugs' == $fields ) {
2426 $_terms = $wpdb->get_col( $query );
2427 $_field = ( 'ids' == $fields ) ? 'term_id' : 'name';
2428 foreach ( $_terms as $key => $term ) {
2429 $_terms[$key] = sanitize_term_field( $_field, $term, $term, $taxonomy, 'raw' );
2431 $terms = array_merge( $terms, $_terms );
2432 } elseif ( 'tt_ids' == $fields ) {
2433 $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");
2434 foreach ( $terms as $key => $tt_id ) {
2435 $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.
2439 // Update termmeta cache, if necessary.
2440 if ( $args['update_term_meta_cache'] && ( 'all' === $fields || 'all_with_object_ids' === $fields || 'term_id' === $fields ) ) {
2441 if ( 'term_id' === $fields ) {
2442 $term_ids = $fields;
2444 $term_ids = wp_list_pluck( $terms, 'term_id' );
2447 update_termmeta_cache( $term_ids );
2452 } elseif ( $objects && 'all_with_object_id' !== $fields ) {
2455 foreach ( $terms as $term ) {
2456 if ( in_array( $term->term_taxonomy_id, $_tt_ids ) ) {
2460 $_tt_ids[] = $term->term_taxonomy_id;
2464 } elseif ( ! $objects ) {
2465 $terms = array_values( array_unique( $terms ) );
2469 * Filter the terms for a given object or objects.
2473 * @param array $terms An array of terms for the given object or objects.
2474 * @param array $object_id_array Array of object IDs for which `$terms` were retrieved.
2475 * @param array $taxonomy_array Array of taxonomies from which `$terms` were retrieved.
2476 * @param array $args An array of arguments for retrieving terms for the given
2477 * object(s). See wp_get_object_terms() for details.
2479 $terms = apply_filters( 'get_object_terms', $terms, $object_id_array, $taxonomy_array, $args );
2482 * Filter the terms for a given object or objects.
2484 * The `$taxonomies` parameter passed to this filter is formatted as a SQL fragment. The
2485 * {@see 'get_object_terms'} filter is recommended as an alternative.
2489 * @param array $terms An array of terms for the given object or objects.
2490 * @param int|array $object_ids Object ID or array of IDs.
2491 * @param string $taxonomies SQL-formatted (comma-separated and quoted) list of taxonomy names.
2492 * @param array $args An array of arguments for retrieving terms for the given object(s).
2493 * See {@see wp_get_object_terms()} for details.
2495 return apply_filters( 'wp_get_object_terms', $terms, $object_ids, $taxonomies, $args );
2499 * Add a new term to the database.
2501 * A non-existent term is inserted in the following sequence:
2502 * 1. The term is added to the term table, then related to the taxonomy.
2503 * 2. If everything is correct, several actions are fired.
2504 * 3. The 'term_id_filter' is evaluated.
2505 * 4. The term cache is cleaned.
2506 * 5. Several more actions are fired.
2507 * 6. An array is returned containing the term_id and term_taxonomy_id.
2509 * If the 'slug' argument is not empty, then it is checked to see if the term
2510 * is invalid. If it is not a valid, existing term, it is added and the term_id
2513 * If the taxonomy is hierarchical, and the 'parent' argument is not empty,
2514 * the term is inserted and the term_id will be given.
2517 * If $taxonomy does not exist or $term is empty,
2518 * a WP_Error object will be returned.
2520 * If the term already exists on the same hierarchical level,
2521 * or the term slug and name are not unique, a WP_Error object will be returned.
2523 * @global wpdb $wpdb WordPress database abstraction object.
2527 * @param string $term The term to add or update.
2528 * @param string $taxonomy The taxonomy to which to add the term.
2529 * @param array|string $args {
2530 * Optional. Array or string of arguments for inserting a term.
2532 * @type string $alias_of Slug of the term to make this term an alias of.
2533 * Default empty string. Accepts a term slug.
2534 * @type string $description The term description. Default empty string.
2535 * @type int $parent The id of the parent term. Default 0.
2536 * @type string $slug The term slug to use. Default empty string.
2538 * @return array|WP_Error An array containing the `term_id` and `term_taxonomy_id`,
2539 * {@see WP_Error} otherwise.
2541 function wp_insert_term( $term, $taxonomy, $args = array() ) {
2544 if ( ! taxonomy_exists($taxonomy) ) {
2545 return new WP_Error('invalid_taxonomy', __('Invalid taxonomy'));
2548 * Filter a term before it is sanitized and inserted into the database.
2552 * @param string $term The term to add or update.
2553 * @param string $taxonomy Taxonomy slug.
2555 $term = apply_filters( 'pre_insert_term', $term, $taxonomy );
2556 if ( is_wp_error( $term ) ) {
2559 if ( is_int($term) && 0 == $term ) {
2560 return new WP_Error('invalid_term_id', __('Invalid term ID'));
2562 if ( '' == trim($term) ) {
2563 return new WP_Error('empty_term_name', __('A name is required for this term'));
2565 $defaults = array( 'alias_of' => '', 'description' => '', 'parent' => 0, 'slug' => '');
2566 $args = wp_parse_args( $args, $defaults );
2568 if ( $args['parent'] > 0 && ! term_exists( (int) $args['parent'] ) ) {
2569 return new WP_Error( 'missing_parent', __( 'Parent term does not exist.' ) );
2571 $args['name'] = $term;
2572 $args['taxonomy'] = $taxonomy;
2573 $args = sanitize_term($args, $taxonomy, 'db');
2575 // expected_slashed ($name)
2576 $name = wp_unslash( $args['name'] );
2577 $description = wp_unslash( $args['description'] );
2578 $parent = (int) $args['parent'];
2580 $slug_provided = ! empty( $args['slug'] );
2581 if ( ! $slug_provided ) {
2582 $slug = sanitize_title( $name );
2584 $slug = $args['slug'];
2588 if ( $args['alias_of'] ) {
2589 $alias = get_term_by( 'slug', $args['alias_of'], $taxonomy );
2590 if ( ! empty( $alias->term_group ) ) {
2591 // The alias we want is already in a group, so let's use that one.
2592 $term_group = $alias->term_group;
2593 } elseif ( ! empty( $alias->term_id ) ) {
2595 * The alias is not in a group, so we create a new one
2596 * and add the alias to it.
2598 $term_group = $wpdb->get_var("SELECT MAX(term_group) FROM $wpdb->terms") + 1;
2600 wp_update_term( $alias->term_id, $taxonomy, array(
2601 'term_group' => $term_group,
2607 * Prevent the creation of terms with duplicate names at the same level of a taxonomy hierarchy,
2608 * unless a unique slug has been explicitly provided.
2610 $name_matches = get_terms( $taxonomy, array(
2612 'hide_empty' => false,
2616 * The `name` match in `get_terms()` doesn't differentiate accented characters,
2617 * so we do a stricter comparison here.
2620 if ( $name_matches ) {
2621 foreach ( $name_matches as $_match ) {
2622 if ( strtolower( $name ) === strtolower( $_match->name ) ) {
2623 $name_match = $_match;
2629 if ( $name_match ) {
2630 $slug_match = get_term_by( 'slug', $slug, $taxonomy );
2631 if ( ! $slug_provided || $name_match->slug === $slug || $slug_match ) {
2632 if ( is_taxonomy_hierarchical( $taxonomy ) ) {
2633 $siblings = get_terms( $taxonomy, array( 'get' => 'all', 'parent' => $parent ) );
2635 $existing_term = null;
2636 if ( $name_match->slug === $slug && in_array( $name, wp_list_pluck( $siblings, 'name' ) ) ) {
2637 $existing_term = $name_match;
2638 } elseif ( $slug_match && in_array( $slug, wp_list_pluck( $siblings, 'slug' ) ) ) {
2639 $existing_term = $slug_match;
2642 if ( $existing_term ) {
2643 return new WP_Error( 'term_exists', __( 'A term with the name provided already exists with this parent.' ), $existing_term->term_id );
2646 return new WP_Error( 'term_exists', __( 'A term with the name provided already exists in this taxonomy.' ), $name_match->term_id );
2651 $slug = wp_unique_term_slug( $slug, (object) $args );
2653 if ( false === $wpdb->insert( $wpdb->terms, compact( 'name', 'slug', 'term_group' ) ) ) {
2654 return new WP_Error( 'db_insert_error', __( 'Could not insert term into the database' ), $wpdb->last_error );
2657 $term_id = (int) $wpdb->insert_id;
2659 // Seems unreachable, However, Is used in the case that a term name is provided, which sanitizes to an empty string.
2660 if ( empty($slug) ) {
2661 $slug = sanitize_title($slug, $term_id);
2663 /** This action is documented in wp-includes/taxonomy.php */
2664 do_action( 'edit_terms', $term_id, $taxonomy );
2665 $wpdb->update( $wpdb->terms, compact( 'slug' ), compact( 'term_id' ) );
2667 /** This action is documented in wp-includes/taxonomy.php */
2668 do_action( 'edited_terms', $term_id, $taxonomy );
2671 $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 ) );
2673 if ( !empty($tt_id) ) {
2674 return array('term_id' => $term_id, 'term_taxonomy_id' => $tt_id);
2676 $wpdb->insert( $wpdb->term_taxonomy, compact( 'term_id', 'taxonomy', 'description', 'parent') + array( 'count' => 0 ) );
2677 $tt_id = (int) $wpdb->insert_id;
2680 * Sanity check: if we just created a term with the same parent + taxonomy + slug but a higher term_id than
2681 * an existing term, then we have unwittingly created a duplicate term. Delete the dupe, and use the term_id
2682 * and term_taxonomy_id of the older term instead. Then return out of the function so that the "create" hooks
2685 $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 ) );
2686 if ( $duplicate_term ) {
2687 $wpdb->delete( $wpdb->terms, array( 'term_id' => $term_id ) );
2688 $wpdb->delete( $wpdb->term_taxonomy, array( 'term_taxonomy_id' => $tt_id ) );
2690 $term_id = (int) $duplicate_term->term_id;
2691 $tt_id = (int) $duplicate_term->term_taxonomy_id;
2693 clean_term_cache( $term_id, $taxonomy );
2694 return array( 'term_id' => $term_id, 'term_taxonomy_id' => $tt_id );
2698 * Fires immediately after a new term is created, before the term cache is cleaned.
2702 * @param int $term_id Term ID.
2703 * @param int $tt_id Term taxonomy ID.
2704 * @param string $taxonomy Taxonomy slug.
2706 do_action( "create_term", $term_id, $tt_id, $taxonomy );
2709 * Fires after a new term is created for a specific taxonomy.
2711 * The dynamic portion of the hook name, `$taxonomy`, refers
2712 * to the slug of the taxonomy the term was created for.
2716 * @param int $term_id Term ID.
2717 * @param int $tt_id Term taxonomy ID.
2719 do_action( "create_$taxonomy", $term_id, $tt_id );
2722 * Filter the term ID after a new term is created.
2726 * @param int $term_id Term ID.
2727 * @param int $tt_id Taxonomy term ID.
2729 $term_id = apply_filters( 'term_id_filter', $term_id, $tt_id );
2731 clean_term_cache($term_id, $taxonomy);
2734 * Fires after a new term is created, and after the term cache has been cleaned.
2738 * @param int $term_id Term ID.
2739 * @param int $tt_id Term taxonomy ID.
2740 * @param string $taxonomy Taxonomy slug.
2742 do_action( 'created_term', $term_id, $tt_id, $taxonomy );
2745 * Fires after a new term in a specific taxonomy is created, and after the term
2746 * cache has been cleaned.
2748 * The dynamic portion of the hook name, `$taxonomy`, refers to the taxonomy slug.
2752 * @param int $term_id Term ID.
2753 * @param int $tt_id Term taxonomy ID.
2755 do_action( "created_$taxonomy", $term_id, $tt_id );
2757 return array('term_id' => $term_id, 'term_taxonomy_id' => $tt_id);
2761 * Create Term and Taxonomy Relationships.
2763 * Relates an object (post, link etc) to a term and taxonomy type. Creates the
2764 * term and taxonomy relationship if it doesn't already exist. Creates a term if
2765 * it doesn't exist (using the slug).
2767 * A relationship means that the term is grouped in or belongs to the taxonomy.
2768 * A term has no meaning until it is given context by defining which taxonomy it
2773 * @global wpdb $wpdb The WordPress database abstraction object.
2775 * @param int $object_id The object to relate to.
2776 * @param array|int|string $terms A single term slug, single term id, or array of either term slugs or ids.
2777 * Will replace all existing related terms in this taxonomy.
2778 * @param string $taxonomy The context in which to relate the term to the object.
2779 * @param bool $append Optional. If false will delete difference of terms. Default false.
2780 * @return array|WP_Error Affected Term IDs.
2782 function wp_set_object_terms( $object_id, $terms, $taxonomy, $append = false ) {
2785 $object_id = (int) $object_id;
2787 if ( ! taxonomy_exists($taxonomy) )
2788 return new WP_Error('invalid_taxonomy', __('Invalid taxonomy'));
2790 if ( !is_array($terms) )
2791 $terms = array($terms);
2794 $old_tt_ids = wp_get_object_terms($object_id, $taxonomy, array('fields' => 'tt_ids', 'orderby' => 'none'));
2796 $old_tt_ids = array();
2799 $term_ids = array();
2800 $new_tt_ids = array();
2802 foreach ( (array) $terms as $term) {
2803 if ( !strlen(trim($term)) )
2806 if ( !$term_info = term_exists($term, $taxonomy) ) {
2807 // Skip if a non-existent term ID is passed.
2808 if ( is_int($term) )
2810 $term_info = wp_insert_term($term, $taxonomy);
2812 if ( is_wp_error($term_info) )
2814 $term_ids[] = $term_info['term_id'];
2815 $tt_id = $term_info['term_taxonomy_id'];
2818 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 ) ) )
2822 * Fires immediately before an object-term relationship is added.
2826 * @param int $object_id Object ID.
2827 * @param int $tt_id Term taxonomy ID.
2829 do_action( 'add_term_relationship', $object_id, $tt_id );
2830 $wpdb->insert( $wpdb->term_relationships, array( 'object_id' => $object_id, 'term_taxonomy_id' => $tt_id ) );
2833 * Fires immediately after an object-term relationship is added.
2837 * @param int $object_id Object ID.
2838 * @param int $tt_id Term taxonomy ID.
2840 do_action( 'added_term_relationship', $object_id, $tt_id );
2841 $new_tt_ids[] = $tt_id;
2845 wp_update_term_count( $new_tt_ids, $taxonomy );
2848 $delete_tt_ids = array_diff( $old_tt_ids, $tt_ids );
2850 if ( $delete_tt_ids ) {
2851 $in_delete_tt_ids = "'" . implode( "', '", $delete_tt_ids ) . "'";
2852 $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 ) );
2853 $delete_term_ids = array_map( 'intval', $delete_term_ids );
2855 $remove = wp_remove_object_terms( $object_id, $delete_term_ids, $taxonomy );
2856 if ( is_wp_error( $remove ) ) {
2862 $t = get_taxonomy($taxonomy);
2863 if ( ! $append && isset($t->sort) && $t->sort ) {
2866 $final_tt_ids = wp_get_object_terms($object_id, $taxonomy, array('fields' => 'tt_ids'));
2867 foreach ( $tt_ids as $tt_id )
2868 if ( in_array($tt_id, $final_tt_ids) )
2869 $values[] = $wpdb->prepare( "(%d, %d, %d)", $object_id, $tt_id, ++$term_order);
2871 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)" ) )
2872 return new WP_Error( 'db_insert_error', __( 'Could not insert term relationship into the database' ), $wpdb->last_error );
2875 wp_cache_delete( $object_id, $taxonomy . '_relationships' );
2878 * Fires after an object's terms have been set.
2882 * @param int $object_id Object ID.
2883 * @param array $terms An array of object terms.
2884 * @param array $tt_ids An array of term taxonomy IDs.
2885 * @param string $taxonomy Taxonomy slug.
2886 * @param bool $append Whether to append new terms to the old terms.
2887 * @param array $old_tt_ids Old array of term taxonomy IDs.
2889 do_action( 'set_object_terms', $object_id, $terms, $tt_ids, $taxonomy, $append, $old_tt_ids );
2894 * Add term(s) associated with a given object.
2898 * @param int $object_id The ID of the object to which the terms will be added.
2899 * @param array|int|string $terms The slug(s) or ID(s) of the term(s) to add.
2900 * @param array|string $taxonomy Taxonomy name.
2901 * @return array|WP_Error Affected Term IDs
2903 function wp_add_object_terms( $object_id, $terms, $taxonomy ) {
2904 return wp_set_object_terms( $object_id, $terms, $taxonomy, true );
2908 * Remove term(s) associated with a given object.
2912 * @global wpdb $wpdb WordPress database abstraction object.
2914 * @param int $object_id The ID of the object from which the terms will be removed.
2915 * @param array|int|string $terms The slug(s) or ID(s) of the term(s) to remove.
2916 * @param array|string $taxonomy Taxonomy name.
2917 * @return bool|WP_Error True on success, false or WP_Error on failure.
2919 function wp_remove_object_terms( $object_id, $terms, $taxonomy ) {
2922 $object_id = (int) $object_id;
2924 if ( ! taxonomy_exists( $taxonomy ) ) {
2925 return new WP_Error( 'invalid_taxonomy', __( 'Invalid Taxonomy' ) );
2928 if ( ! is_array( $terms ) ) {
2929 $terms = array( $terms );
2934 foreach ( (array) $terms as $term ) {
2935 if ( ! strlen( trim( $term ) ) ) {
2939 if ( ! $term_info = term_exists( $term, $taxonomy ) ) {
2940 // Skip if a non-existent term ID is passed.
2941 if ( is_int( $term ) ) {
2946 if ( is_wp_error( $term_info ) ) {
2950 $tt_ids[] = $term_info['term_taxonomy_id'];
2954 $in_tt_ids = "'" . implode( "', '", $tt_ids ) . "'";
2957 * Fires immediately before an object-term relationship is deleted.
2961 * @param int $object_id Object ID.
2962 * @param array $tt_ids An array of term taxonomy IDs.
2964 do_action( 'delete_term_relationships', $object_id, $tt_ids );
2965 $deleted = $wpdb->query( $wpdb->prepare( "DELETE FROM $wpdb->term_relationships WHERE object_id = %d AND term_taxonomy_id IN ($in_tt_ids)", $object_id ) );
2967 wp_cache_delete( $object_id, $taxonomy . '_relationships' );
2970 * Fires immediately after an object-term relationship is deleted.
2974 * @param int $object_id Object ID.
2975 * @param array $tt_ids An array of term taxonomy IDs.
2977 do_action( 'deleted_term_relationships', $object_id, $tt_ids );
2979 wp_update_term_count( $tt_ids, $taxonomy );
2981 return (bool) $deleted;
2988 * Will make slug unique, if it isn't already.
2990 * The `$slug` has to be unique global to every taxonomy, meaning that one
2991 * taxonomy term can't have a matching slug with another taxonomy term. Each
2992 * slug has to be globally unique for every taxonomy.
2994 * The way this works is that if the taxonomy that the term belongs to is
2995 * hierarchical and has a parent, it will append that parent to the $slug.
2997 * If that still doesn't return an unique slug, then it try to append a number
2998 * until it finds a number that is truly unique.
3000 * The only purpose for `$term` is for appending a parent, if one exists.
3004 * @global wpdb $wpdb WordPress database abstraction object.
3006 * @param string $slug The string that will be tried for a unique slug.
3007 * @param object $term The term object that the `$slug` will belong to.
3008 * @return string Will return a true unique slug.
3010 function wp_unique_term_slug( $slug, $term ) {
3013 $needs_suffix = true;
3014 $original_slug = $slug;
3016 // As of 4.1, duplicate slugs are allowed as long as they're in different taxonomies.
3017 if ( ! term_exists( $slug ) || get_option( 'db_version' ) >= 30133 && ! get_term_by( 'slug', $slug, $term->taxonomy ) ) {
3018 $needs_suffix = false;
3022 * If the taxonomy supports hierarchy and the term has a parent, make the slug unique
3023 * by incorporating parent slugs.
3025 $parent_suffix = '';
3026 if ( $needs_suffix && is_taxonomy_hierarchical( $term->taxonomy ) && ! empty( $term->parent ) ) {
3027 $the_parent = $term->parent;
3028 while ( ! empty($the_parent) ) {
3029 $parent_term = get_term($the_parent, $term->taxonomy);
3030 if ( is_wp_error($parent_term) || empty($parent_term) )
3032 $parent_suffix .= '-' . $parent_term->slug;
3033 if ( ! term_exists( $slug . $parent_suffix ) ) {
3037 if ( empty($parent_term->parent) )
3039 $the_parent = $parent_term->parent;
3043 // If we didn't get a unique slug, try appending a number to make it unique.
3046 * Filter whether the proposed unique term slug is bad.
3050 * @param bool $needs_suffix Whether the slug needs to be made unique with a suffix.
3051 * @param string $slug The slug.
3052 * @param object $term Term object.
3054 if ( apply_filters( 'wp_unique_term_slug_is_bad_slug', $needs_suffix, $slug, $term ) ) {
3055 if ( $parent_suffix ) {
3056 $slug .= $parent_suffix;
3058 if ( ! empty( $term->term_id ) )
3059 $query = $wpdb->prepare( "SELECT slug FROM $wpdb->terms WHERE slug = %s AND term_id != %d", $slug, $term->term_id );
3061 $query = $wpdb->prepare( "SELECT slug FROM $wpdb->terms WHERE slug = %s", $slug );
3063 if ( $wpdb->get_var( $query ) ) {
3066 $alt_slug = $slug . "-$num";
3068 $slug_check = $wpdb->get_var( $wpdb->prepare( "SELECT slug FROM $wpdb->terms WHERE slug = %s", $alt_slug ) );
3069 } while ( $slug_check );
3076 * Filter the unique term slug.
3080 * @param string $slug Unique term slug.
3081 * @param object $term Term object.
3082 * @param string $original_slug Slug originally passed to the function for testing.
3084 return apply_filters( 'wp_unique_term_slug', $slug, $term, $original_slug );
3088 * Update term based on arguments provided.
3090 * The $args will indiscriminately override all values with the same field name.
3091 * Care must be taken to not override important information need to update or
3092 * update will fail (or perhaps create a new term, neither would be acceptable).
3094 * Defaults will set 'alias_of', 'description', 'parent', and 'slug' if not
3095 * defined in $args already.
3097 * 'alias_of' will create a term group, if it doesn't already exist, and update
3100 * If the 'slug' argument in $args is missing, then the 'name' in $args will be
3101 * used. It should also be noted that if you set 'slug' and it isn't unique then
3102 * a WP_Error will be passed back. If you don't pass any slug, then a unique one
3103 * will be created for you.
3105 * For what can be overrode in `$args`, check the term scheme can contain and stay
3106 * away from the term keys.
3110 * @global wpdb $wpdb WordPress database abstraction object.
3112 * @param int $term_id The ID of the term
3113 * @param string $taxonomy The context in which to relate the term to the object.
3114 * @param array|string $args Optional. Array of get_terms() arguments. Default empty array.
3115 * @return array|WP_Error Returns Term ID and Taxonomy Term ID
3117 function wp_update_term( $term_id, $taxonomy, $args = array() ) {
3120 if ( ! taxonomy_exists( $taxonomy ) ) {
3121 return new WP_Error( 'invalid_taxonomy', __( 'Invalid taxonomy' ) );
3124 $term_id = (int) $term_id;
3126 // First, get all of the original args
3127 $term = get_term( $term_id, $taxonomy );
3129 if ( is_wp_error( $term ) ) {
3134 return new WP_Error( 'invalid_term', __( 'Empty Term' ) );
3137 $term = (array) $term->data;
3139 // Escape data pulled from DB.
3140 $term = wp_slash( $term );
3142 // Merge old and new args with new args overwriting old ones.
3143 $args = array_merge($term, $args);
3145 $defaults = array( 'alias_of' => '', 'description' => '', 'parent' => 0, 'slug' => '');
3146 $args = wp_parse_args($args, $defaults);
3147 $args = sanitize_term($args, $taxonomy, 'db');
3148 $parsed_args = $args;
3150 // expected_slashed ($name)
3151 $name = wp_unslash( $args['name'] );
3152 $description = wp_unslash( $args['description'] );
3154 $parsed_args['name'] = $name;
3155 $parsed_args['description'] = $description;
3157 if ( '' == trim($name) )
3158 return new WP_Error('empty_term_name', __('A name is required for this term'));
3160 if ( $parsed_args['parent'] > 0 && ! term_exists( (int) $parsed_args['parent'] ) ) {
3161 return new WP_Error( 'missing_parent', __( 'Parent term does not exist.' ) );
3164 $empty_slug = false;
3165 if ( empty( $args['slug'] ) ) {
3167 $slug = sanitize_title($name);
3169 $slug = $args['slug'];
3172 $parsed_args['slug'] = $slug;
3174 $term_group = isset( $parsed_args['term_group'] ) ? $parsed_args['term_group'] : 0;
3175 if ( $args['alias_of'] ) {
3176 $alias = get_term_by( 'slug', $args['alias_of'], $taxonomy );
3177 if ( ! empty( $alias->term_group ) ) {
3178 // The alias we want is already in a group, so let's use that one.
3179 $term_group = $alias->term_group;
3180 } elseif ( ! empty( $alias->term_id ) ) {
3182 * The alias is not in a group, so we create a new one
3183 * and add the alias to it.
3185 $term_group = $wpdb->get_var("SELECT MAX(term_group) FROM $wpdb->terms") + 1;
3187 wp_update_term( $alias->term_id, $taxonomy, array(
3188 'term_group' => $term_group,
3192 $parsed_args['term_group'] = $term_group;
3196 * Filter the term parent.
3198 * Hook to this filter to see if it will cause a hierarchy loop.
3202 * @param int $parent ID of the parent term.
3203 * @param int $term_id Term ID.
3204 * @param string $taxonomy Taxonomy slug.
3205 * @param array $parsed_args An array of potentially altered update arguments for the given term.
3206 * @param array $args An array of update arguments for the given term.
3208 $parent = apply_filters( 'wp_update_term_parent', $args['parent'], $term_id, $taxonomy, $parsed_args, $args );
3210 // Check for duplicate slug
3211 $duplicate = get_term_by( 'slug', $slug, $taxonomy );
3212 if ( $duplicate && $duplicate->term_id != $term_id ) {
3213 // If an empty slug was passed or the parent changed, reset the slug to something unique.
3215 if ( $empty_slug || ( $parent != $term['parent']) )
3216 $slug = wp_unique_term_slug($slug, (object) $args);
3218 return new WP_Error('duplicate_term_slug', sprintf(__('The slug “%s” is already in use by another term'), $slug));
3221 $tt_id = (int) $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) );
3223 // Check whether this is a shared term that needs splitting.
3224 $_term_id = _split_shared_term( $term_id, $tt_id );
3225 if ( ! is_wp_error( $_term_id ) ) {
3226 $term_id = $_term_id;
3230 * Fires immediately before the given terms are edited.
3234 * @param int $term_id Term ID.
3235 * @param string $taxonomy Taxonomy slug.
3237 do_action( 'edit_terms', $term_id, $taxonomy );
3238 $wpdb->update($wpdb->terms, compact( 'name', 'slug', 'term_group' ), compact( 'term_id' ) );
3239 if ( empty($slug) ) {
3240 $slug = sanitize_title($name, $term_id);
3241 $wpdb->update( $wpdb->terms, compact( 'slug' ), compact( 'term_id' ) );
3245 * Fires immediately after the given terms are edited.
3249 * @param int $term_id Term ID
3250 * @param string $taxonomy Taxonomy slug.
3252 do_action( 'edited_terms', $term_id, $taxonomy );
3255 * Fires immediate before a term-taxonomy relationship is updated.
3259 * @param int $tt_id Term taxonomy ID.
3260 * @param string $taxonomy Taxonomy slug.
3262 do_action( 'edit_term_taxonomy', $tt_id, $taxonomy );
3264 $wpdb->update( $wpdb->term_taxonomy, compact( 'term_id', 'taxonomy', 'description', 'parent' ), array( 'term_taxonomy_id' => $tt_id ) );
3267 * Fires immediately after a term-taxonomy relationship is updated.
3271 * @param int $tt_id Term taxonomy ID.
3272 * @param string $taxonomy Taxonomy slug.
3274 do_action( 'edited_term_taxonomy', $tt_id, $taxonomy );
3276 // Clean the relationship caches for all object types using this term.
3277 $objects = $wpdb->get_col( $wpdb->prepare( "SELECT object_id FROM $wpdb->term_relationships WHERE term_taxonomy_id = %d", $tt_id ) );
3278 $tax_object = get_taxonomy( $taxonomy );
3279 foreach ( $tax_object->object_type as $object_type ) {
3280 clean_object_term_cache( $objects, $object_type );
3284 * Fires after a term has been updated, but before the term cache has been cleaned.
3288 * @param int $term_id Term ID.
3289 * @param int $tt_id Term taxonomy ID.
3290 * @param string $taxonomy Taxonomy slug.
3292 do_action( "edit_term", $term_id, $tt_id, $taxonomy );
3295 * Fires after a term in a specific taxonomy has been updated, but before the term
3296 * cache has been cleaned.
3298 * The dynamic portion of the hook name, `$taxonomy`, refers to the taxonomy slug.
3302 * @param int $term_id Term ID.
3303 * @param int $tt_id Term taxonomy ID.
3305 do_action( "edit_$taxonomy", $term_id, $tt_id );
3307 /** This filter is documented in wp-includes/taxonomy.php */
3308 $term_id = apply_filters( 'term_id_filter', $term_id, $tt_id );
3310 clean_term_cache($term_id, $taxonomy);
3313 * Fires after a term has been updated, and the term cache has been cleaned.
3317 * @param int $term_id Term ID.
3318 * @param int $tt_id Term taxonomy ID.
3319 * @param string $taxonomy Taxonomy slug.
3321 do_action( "edited_term", $term_id, $tt_id, $taxonomy );
3324 * Fires after a term for a specific taxonomy has been updated, and the term
3325 * cache has been cleaned.
3327 * The dynamic portion of the hook name, `$taxonomy`, refers to the taxonomy slug.
3331 * @param int $term_id Term ID.
3332 * @param int $tt_id Term taxonomy ID.
3334 do_action( "edited_$taxonomy", $term_id, $tt_id );
3336 return array('term_id' => $term_id, 'term_taxonomy_id' => $tt_id);
3340 * Enable or disable term counting.
3344 * @staticvar bool $_defer
3346 * @param bool $defer Optional. Enable if true, disable if false.
3347 * @return bool Whether term counting is enabled or disabled.
3349 function wp_defer_term_counting($defer=null) {
3350 static $_defer = false;
3352 if ( is_bool($defer) ) {
3354 // flush any deferred counts
3356 wp_update_term_count( null, null, true );
3363 * Updates the amount of terms in taxonomy.
3365 * If there is a taxonomy callback applied, then it will be called for updating
3368 * The default action is to count what the amount of terms have the relationship
3369 * of term ID. Once that is done, then update the database.
3373 * @staticvar array $_deferred
3375 * @param int|array $terms The term_taxonomy_id of the terms.
3376 * @param string $taxonomy The context of the term.
3377 * @return bool If no terms will return false, and if successful will return true.
3379 function wp_update_term_count( $terms, $taxonomy, $do_deferred=false ) {
3380 static $_deferred = array();
3382 if ( $do_deferred ) {
3383 foreach ( (array) array_keys($_deferred) as $tax ) {
3384 wp_update_term_count_now( $_deferred[$tax], $tax );
3385 unset( $_deferred[$tax] );
3389 if ( empty($terms) )
3392 if ( !is_array($terms) )
3393 $terms = array($terms);
3395 if ( wp_defer_term_counting() ) {
3396 if ( !isset($_deferred[$taxonomy]) )
3397 $_deferred[$taxonomy] = array();
3398 $_deferred[$taxonomy] = array_unique( array_merge($_deferred[$taxonomy], $terms) );
3402 return wp_update_term_count_now( $terms, $taxonomy );
3406 * Perform term count update immediately.
3410 * @param array $terms The term_taxonomy_id of terms to update.
3411 * @param string $taxonomy The context of the term.
3412 * @return true Always true when complete.
3414 function wp_update_term_count_now( $terms, $taxonomy ) {
3415 $terms = array_map('intval', $terms);
3417 $taxonomy = get_taxonomy($taxonomy);
3418 if ( !empty($taxonomy->update_count_callback) ) {
3419 call_user_func($taxonomy->update_count_callback, $terms, $taxonomy);
3421 $object_types = (array) $taxonomy->object_type;
3422 foreach ( $object_types as &$object_type ) {
3423 if ( 0 === strpos( $object_type, 'attachment:' ) )
3424 list( $object_type ) = explode( ':', $object_type );
3427 if ( $object_types == array_filter( $object_types, 'post_type_exists' ) ) {
3428 // Only post types are attached to this taxonomy
3429 _update_post_term_count( $terms, $taxonomy );
3431 // Default count updater
3432 _update_generic_term_count( $terms, $taxonomy );
3436 clean_term_cache($terms, '', false);
3446 * Removes the taxonomy relationship to terms from the cache.
3448 * Will remove the entire taxonomy relationship containing term `$object_id`. The
3449 * term IDs have to exist within the taxonomy `$object_type` for the deletion to
3454 * @see get_object_taxonomies() for more on $object_type.
3456 * @param int|array $object_ids Single or list of term object ID(s).
3457 * @param array|string $object_type The taxonomy object type.
3459 function clean_object_term_cache($object_ids, $object_type) {
3460 if ( !is_array($object_ids) )
3461 $object_ids = array($object_ids);
3463 $taxonomies = get_object_taxonomies( $object_type );
3465 foreach ( $object_ids as $id ) {
3466 foreach ( $taxonomies as $taxonomy ) {
3467 wp_cache_delete($id, "{$taxonomy}_relationships");
3472 * Fires after the object term cache has been cleaned.
3476 * @param array $object_ids An array of object IDs.
3477 * @param string $objet_type Object type.
3479 do_action( 'clean_object_term_cache', $object_ids, $object_type );
3483 * Will remove all of the term ids from the cache.
3487 * @global wpdb $wpdb WordPress database abstraction object.
3488 * @global bool $_wp_suspend_cache_invalidation
3490 * @param int|array $ids Single or list of Term IDs.
3491 * @param string $taxonomy Optional. Can be empty and will assume `tt_ids`, else will use for context.
3493 * @param bool $clean_taxonomy Optional. Whether to clean taxonomy wide caches (true), or just individual
3494 * term object caches (false). Default true.
3496 function clean_term_cache($ids, $taxonomy = '', $clean_taxonomy = true) {
3497 global $wpdb, $_wp_suspend_cache_invalidation;
3499 if ( ! empty( $_wp_suspend_cache_invalidation ) ) {
3503 if ( !is_array($ids) )
3506 $taxonomies = array();
3507 // If no taxonomy, assume tt_ids.
3508 if ( empty($taxonomy) ) {
3509 $tt_ids = array_map('intval', $ids);
3510 $tt_ids = implode(', ', $tt_ids);
3511 $terms = $wpdb->get_results("SELECT term_id, taxonomy FROM $wpdb->term_taxonomy WHERE term_taxonomy_id IN ($tt_ids)");
3513 foreach ( (array) $terms as $term ) {
3514 $taxonomies[] = $term->taxonomy;
3515 $ids[] = $term->term_id;
3516 wp_cache_delete( $term->term_id, 'terms' );
3518 $taxonomies = array_unique($taxonomies);
3520 $taxonomies = array($taxonomy);
3521 foreach ( $taxonomies as $taxonomy ) {
3522 foreach ( $ids as $id ) {
3523 wp_cache_delete( $id, 'terms' );
3528 foreach ( $taxonomies as $taxonomy ) {
3529 if ( $clean_taxonomy ) {
3530 wp_cache_delete('all_ids', $taxonomy);
3531 wp_cache_delete('get', $taxonomy);
3532 delete_option("{$taxonomy}_children");
3533 // Regenerate {$taxonomy}_children
3534 _get_term_hierarchy($taxonomy);
3538 * Fires once after each taxonomy's term cache has been cleaned.
3542 * @param array $ids An array of term IDs.
3543 * @param string $taxonomy Taxonomy slug.
3545 do_action( 'clean_term_cache', $ids, $taxonomy );
3548 wp_cache_set( 'last_changed', microtime(), 'terms' );
3552 * Retrieves the taxonomy relationship to the term object id.
3556 * @param int $id Term object ID.
3557 * @param string $taxonomy Taxonomy name.
3558 * @return bool|mixed Empty array if $terms found, but not `$taxonomy`. False if nothing is in cache
3559 * for `$taxonomy` and `$id`.
3561 function get_object_term_cache( $id, $taxonomy ) {
3562 return wp_cache_get( $id, "{$taxonomy}_relationships" );
3566 * Updates the cache for the given term object ID(s).
3568 * Note: Due to performance concerns, great care should be taken to only update
3569 * term caches when necessary. Processing time can increase exponentially depending
3570 * on both the number of passed term IDs and the number of taxonomies those terms
3573 * Caches will only be updated for terms not already cached.
3577 * @param string|array $object_ids Comma-separated list or array of term object IDs.
3578 * @param array|string $object_type The taxonomy object type.
3579 * @return void|false False if all of the terms in `$object_ids` are already cached.
3581 function update_object_term_cache($object_ids, $object_type) {
3582 if ( empty($object_ids) )
3585 if ( !is_array($object_ids) )
3586 $object_ids = explode(',', $object_ids);
3588 $object_ids = array_map('intval', $object_ids);
3590 $taxonomies = get_object_taxonomies($object_type);
3593 foreach ( (array) $object_ids as $id ) {
3594 foreach ( $taxonomies as $taxonomy ) {
3595 if ( false === wp_cache_get($id, "{$taxonomy}_relationships") ) {
3602 if ( empty( $ids ) )
3605 $terms = wp_get_object_terms( $ids, $taxonomies, array(
3606 'fields' => 'all_with_object_id',
3607 'orderby' => 'none',
3608 'update_term_meta_cache' => false,
3611 $object_terms = array();
3612 foreach ( (array) $terms as $term )
3613 $object_terms[$term->object_id][$term->taxonomy][] = $term;
3615 foreach ( $ids as $id ) {
3616 foreach ( $taxonomies as $taxonomy ) {
3617 if ( ! isset($object_terms[$id][$taxonomy]) ) {
3618 if ( !isset($object_terms[$id]) )
3619 $object_terms[$id] = array();
3620 $object_terms[$id][$taxonomy] = array();
3625 foreach ( $object_terms as $id => $value ) {
3626 foreach ( $value as $taxonomy => $terms ) {
3627 wp_cache_add( $id, $terms, "{$taxonomy}_relationships" );
3633 * Updates Terms to Taxonomy in cache.
3637 * @param array $terms List of term objects to change.
3638 * @param string $taxonomy Optional. Update Term to this taxonomy in cache. Default empty.
3640 function update_term_cache( $terms, $taxonomy = '' ) {
3641 foreach ( (array) $terms as $term ) {
3642 // Create a copy in case the array was passed by reference.
3645 // Object ID should not be cached.
3646 unset( $_term->object_id );
3648 wp_cache_add( $term->term_id, $_term, 'terms' );
3657 * Retrieves children of taxonomy as Term IDs.
3662 * @param string $taxonomy Taxonomy name.
3663 * @return array Empty if $taxonomy isn't hierarchical or returns children as Term IDs.
3665 function _get_term_hierarchy( $taxonomy ) {
3666 if ( !is_taxonomy_hierarchical($taxonomy) )
3668 $children = get_option("{$taxonomy}_children");
3670 if ( is_array($children) )
3672 $children = array();
3673 $terms = get_terms($taxonomy, array('get' => 'all', 'orderby' => 'id', 'fields' => 'id=>parent'));
3674 foreach ( $terms as $term_id => $parent ) {
3676 $children[$parent][] = $term_id;
3678 update_option("{$taxonomy}_children", $children);
3684 * Get the subset of $terms that are descendants of $term_id.
3686 * If `$terms` is an array of objects, then _get_term_children() returns an array of objects.
3687 * If `$terms` is an array of IDs, then _get_term_children() returns an array of IDs.
3692 * @param int $term_id The ancestor term: all returned terms should be descendants of `$term_id`.
3693 * @param array $terms The set of terms - either an array of term objects or term IDs - from which those that
3694 * are descendants of $term_id will be chosen.
3695 * @param string $taxonomy The taxonomy which determines the hierarchy of the terms.
3696 * @param array $ancestors Optional. Term ancestors that have already been identified. Passed by reference, to keep
3697 * track of found terms when recursing the hierarchy. The array of located ancestors is used
3698 * to prevent infinite recursion loops. For performance, `term_ids` are used as array keys,
3699 * with 1 as value. Default empty array.
3700 * @return array|WP_Error The subset of $terms that are descendants of $term_id.
3702 function _get_term_children( $term_id, $terms, $taxonomy, &$ancestors = array() ) {
3703 $empty_array = array();
3704 if ( empty($terms) )
3705 return $empty_array;
3707 $term_list = array();
3708 $has_children = _get_term_hierarchy($taxonomy);
3710 if ( ( 0 != $term_id ) && ! isset($has_children[$term_id]) )
3711 return $empty_array;
3713 // Include the term itself in the ancestors array, so we can properly detect when a loop has occurred.
3714 if ( empty( $ancestors ) ) {
3715 $ancestors[ $term_id ] = 1;
3718 foreach ( (array) $terms as $term ) {
3720 if ( !is_object($term) ) {
3721 $term = get_term($term, $taxonomy);
3722 if ( is_wp_error( $term ) )
3727 // Don't recurse if we've already identified the term as a child - this indicates a loop.
3728 if ( isset( $ancestors[ $term->term_id ] ) ) {
3732 if ( $term->parent == $term_id ) {
3734 $term_list[] = $term->term_id;
3736 $term_list[] = $term;
3738 if ( !isset($has_children[$term->term_id]) )
3741 $ancestors[ $term->term_id ] = 1;
3743 if ( $children = _get_term_children( $term->term_id, $terms, $taxonomy, $ancestors) )
3744 $term_list = array_merge($term_list, $children);
3752 * Add count of children to parent count.
3754 * Recalculates term counts by including items from child terms. Assumes all
3755 * relevant children are already in the $terms argument.
3760 * @global wpdb $wpdb WordPress database abstraction object.
3762 * @param array $terms List of term objects, passed by reference.
3763 * @param string $taxonomy Term context.
3765 function _pad_term_counts( &$terms, $taxonomy ) {
3768 // This function only works for hierarchical taxonomies like post categories.
3769 if ( !is_taxonomy_hierarchical( $taxonomy ) )
3772 $term_hier = _get_term_hierarchy($taxonomy);
3774 if ( empty($term_hier) )
3777 $term_items = array();
3778 $terms_by_id = array();
3779 $term_ids = array();
3781 foreach ( (array) $terms as $key => $term ) {
3782 $terms_by_id[$term->term_id] = & $terms[$key];
3783 $term_ids[$term->term_taxonomy_id] = $term->term_id;
3786 // Get the object and term ids and stick them in a lookup table.
3787 $tax_obj = get_taxonomy($taxonomy);
3788 $object_types = esc_sql($tax_obj->object_type);
3789 $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'");
3790 foreach ( $results as $row ) {
3791 $id = $term_ids[$row->term_taxonomy_id];
3792 $term_items[$id][$row->object_id] = isset($term_items[$id][$row->object_id]) ? ++$term_items[$id][$row->object_id] : 1;
3795 // Touch every ancestor's lookup row for each post in each term.
3796 foreach ( $term_ids as $term_id ) {
3798 $ancestors = array();
3799 while ( !empty( $terms_by_id[$child] ) && $parent = $terms_by_id[$child]->parent ) {
3800 $ancestors[] = $child;
3801 if ( !empty( $term_items[$term_id] ) )
3802 foreach ( $term_items[$term_id] as $item_id => $touches ) {
3803 $term_items[$parent][$item_id] = isset($term_items[$parent][$item_id]) ? ++$term_items[$parent][$item_id]: 1;
3807 if ( in_array( $parent, $ancestors ) ) {
3813 // Transfer the touched cells.
3814 foreach ( (array) $term_items as $id => $items )
3815 if ( isset($terms_by_id[$id]) )
3816 $terms_by_id[$id]->count = count($items);
3820 // Default callbacks
3824 * Will update term count based on object types of the current taxonomy.
3826 * Private function for the default callback for post_tag and category
3832 * @global wpdb $wpdb WordPress database abstraction object.
3834 * @param array $terms List of Term taxonomy IDs.
3835 * @param object $taxonomy Current taxonomy object of terms.
3837 function _update_post_term_count( $terms, $taxonomy ) {
3840 $object_types = (array) $taxonomy->object_type;
3842 foreach ( $object_types as &$object_type )
3843 list( $object_type ) = explode( ':', $object_type );
3845 $object_types = array_unique( $object_types );
3847 if ( false !== ( $check_attachments = array_search( 'attachment', $object_types ) ) ) {
3848 unset( $object_types[ $check_attachments ] );
3849 $check_attachments = true;
3852 if ( $object_types )
3853 $object_types = esc_sql( array_filter( $object_types, 'post_type_exists' ) );
3855 foreach ( (array) $terms as $term ) {
3858 // Attachments can be 'inherit' status, we need to base count off the parent's status if so.
3859 if ( $check_attachments )
3860 $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 ) );
3862 if ( $object_types )
3863 $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 ) );
3865 /** This action is documented in wp-includes/taxonomy.php */
3866 do_action( 'edit_term_taxonomy', $term, $taxonomy->name );
3867 $wpdb->update( $wpdb->term_taxonomy, compact( 'count' ), array( 'term_taxonomy_id' => $term ) );
3869 /** This action is documented in wp-includes/taxonomy.php */
3870 do_action( 'edited_term_taxonomy', $term, $taxonomy->name );
3875 * Will update term count based on number of objects.
3877 * Default callback for the 'link_category' taxonomy.
3881 * @global wpdb $wpdb WordPress database abstraction object.
3883 * @param array $terms List of term taxonomy IDs.
3884 * @param object $taxonomy Current taxonomy object of terms.
3886 function _update_generic_term_count( $terms, $taxonomy ) {
3889 foreach ( (array) $terms as $term ) {
3890 $count = $wpdb->get_var( $wpdb->prepare( "SELECT COUNT(*) FROM $wpdb->term_relationships WHERE term_taxonomy_id = %d", $term ) );
3892 /** This action is documented in wp-includes/taxonomy.php */
3893 do_action( 'edit_term_taxonomy', $term, $taxonomy->name );
3894 $wpdb->update( $wpdb->term_taxonomy, compact( 'count' ), array( 'term_taxonomy_id' => $term ) );
3896 /** This action is documented in wp-includes/taxonomy.php */
3897 do_action( 'edited_term_taxonomy', $term, $taxonomy->name );
3902 * Create a new term for a term_taxonomy item that currently shares its term
3903 * with another term_taxonomy.
3907 * @since 4.3.0 Introduced `$record` parameter. Also, `$term_id` and
3908 * `$term_taxonomy_id` can now accept objects.
3910 * @global wpdb $wpdb WordPress database abstraction object.
3912 * @param int|object $term_id ID of the shared term, or the shared term object.
3913 * @param int|object $term_taxonomy_id ID of the term_taxonomy item to receive a new term, or the term_taxonomy object
3914 * (corresponding to a row from the term_taxonomy table).
3915 * @param bool $record Whether to record data about the split term in the options table. The recording
3916 * process has the potential to be resource-intensive, so during batch operations
3917 * it can be beneficial to skip inline recording and do it just once, after the
3918 * batch is processed. Only set this to `false` if you know what you are doing.
3920 * @return int|WP_Error When the current term does not need to be split (or cannot be split on the current
3921 * database schema), `$term_id` is returned. When the term is successfully split, the
3922 * new term_id is returned. A WP_Error is returned for miscellaneous errors.
3924 function _split_shared_term( $term_id, $term_taxonomy_id, $record = true ) {
3927 if ( is_object( $term_id ) ) {
3928 $shared_term = $term_id;
3929 $term_id = intval( $shared_term->term_id );
3932 if ( is_object( $term_taxonomy_id ) ) {
3933 $term_taxonomy = $term_taxonomy_id;
3934 $term_taxonomy_id = intval( $term_taxonomy->term_taxonomy_id );
3937 // If there are no shared term_taxonomy rows, there's nothing to do here.
3938 $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 ) );
3940 if ( ! $shared_tt_count ) {
3945 * Verify that the term_taxonomy_id passed to the function is actually associated with the term_id.
3946 * If there's a mismatch, it may mean that the term is already split. Return the actual term_id from the db.
3948 $check_term_id = $wpdb->get_var( $wpdb->prepare( "SELECT term_id FROM $wpdb->term_taxonomy WHERE term_taxonomy_id = %d", $term_taxonomy_id ) );
3949 if ( $check_term_id != $term_id ) {
3950 return $check_term_id;
3953 // Pull up data about the currently shared slug, which we'll use to populate the new one.
3954 if ( empty( $shared_term ) ) {
3955 $shared_term = $wpdb->get_row( $wpdb->prepare( "SELECT t.* FROM $wpdb->terms t WHERE t.term_id = %d", $term_id ) );
3958 $new_term_data = array(
3959 'name' => $shared_term->name,
3960 'slug' => $shared_term->slug,
3961 'term_group' => $shared_term->term_group,
3964 if ( false === $wpdb->insert( $wpdb->terms, $new_term_data ) ) {
3965 return new WP_Error( 'db_insert_error', __( 'Could not split shared term.' ), $wpdb->last_error );
3968 $new_term_id = (int) $wpdb->insert_id;
3970 // Update the existing term_taxonomy to point to the newly created term.
3971 $wpdb->update( $wpdb->term_taxonomy,
3972 array( 'term_id' => $new_term_id ),
3973 array( 'term_taxonomy_id' => $term_taxonomy_id )
3976 // Reassign child terms to the new parent.
3977 if ( empty( $term_taxonomy ) ) {
3978 $term_taxonomy = $wpdb->get_row( $wpdb->prepare( "SELECT * FROM $wpdb->term_taxonomy WHERE term_taxonomy_id = %d", $term_taxonomy_id ) );
3981 $children_tt_ids = $wpdb->get_col( $wpdb->prepare( "SELECT term_taxonomy_id FROM $wpdb->term_taxonomy WHERE parent = %d AND taxonomy = %s", $term_id, $term_taxonomy->taxonomy ) );
3982 if ( ! empty( $children_tt_ids ) ) {
3983 foreach ( $children_tt_ids as $child_tt_id ) {
3984 $wpdb->update( $wpdb->term_taxonomy,
3985 array( 'parent' => $new_term_id ),
3986 array( 'term_taxonomy_id' => $child_tt_id )
3988 clean_term_cache( $term_id, $term_taxonomy->taxonomy );
3991 // If the term has no children, we must force its taxonomy cache to be rebuilt separately.
3992 clean_term_cache( $new_term_id, $term_taxonomy->taxonomy );
3995 // Clean the cache for term taxonomies formerly shared with the current term.
3996 $shared_term_taxonomies = $wpdb->get_row( $wpdb->prepare( "SELECT taxonomy FROM $wpdb->term_taxonomy WHERE term_id = %d", $term_id ) );
3997 if ( $shared_term_taxonomies ) {
3998 foreach ( $shared_term_taxonomies as $shared_term_taxonomy ) {
3999 clean_term_cache( $term_id, $shared_term_taxonomy );
4003 // Keep a record of term_ids that have been split, keyed by old term_id. See {@see wp_get_split_term()}.
4005 $split_term_data = get_option( '_split_terms', array() );
4006 if ( ! isset( $split_term_data[ $term_id ] ) ) {
4007 $split_term_data[ $term_id ] = array();
4010 $split_term_data[ $term_id ][ $term_taxonomy->taxonomy ] = $new_term_id;
4011 update_option( '_split_terms', $split_term_data );
4014 // If we've just split the final shared term, set the "finished" flag.
4015 $shared_terms_exist = $wpdb->get_results(
4016 "SELECT tt.term_id, t.*, count(*) as term_tt_count FROM {$wpdb->term_taxonomy} tt
4017 LEFT JOIN {$wpdb->terms} t ON t.term_id = tt.term_id
4019 HAVING term_tt_count > 1
4022 if ( ! $shared_terms_exist ) {
4023 update_option( 'finished_splitting_shared_terms', true );
4027 * Fires after a previously shared taxonomy term is split into two separate terms.
4031 * @param int $term_id ID of the formerly shared term.
4032 * @param int $new_term_id ID of the new term created for the $term_taxonomy_id.
4033 * @param int $term_taxonomy_id ID for the term_taxonomy row affected by the split.
4034 * @param string $taxonomy Taxonomy for the split term.
4036 do_action( 'split_shared_term', $term_id, $new_term_id, $term_taxonomy_id, $term_taxonomy->taxonomy );
4038 return $new_term_id;
4042 * Splits a batch of shared taxonomy terms.
4046 * @global wpdb $wpdb WordPress database abstraction object.
4048 function _wp_batch_split_terms() {
4051 $lock_name = 'term_split.lock';
4054 $lock_result = $wpdb->query( $wpdb->prepare( "INSERT IGNORE INTO `$wpdb->options` ( `option_name`, `option_value`, `autoload` ) VALUES (%s, %s, 'no') /* LOCK */", $lock_name, time() ) );
4056 if ( ! $lock_result ) {
4057 $lock_result = get_option( $lock_name );
4059 // Bail if we were unable to create a lock, or if the existing lock is still valid.
4060 if ( ! $lock_result || ( $lock_result > ( time() - HOUR_IN_SECONDS ) ) ) {
4061 wp_schedule_single_event( time() + ( 5 * MINUTE_IN_SECONDS ), 'wp_split_shared_term_batch' );
4066 // Update the lock, as by this point we've definitely got a lock, just need to fire the actions.
4067 update_option( $lock_name, time() );
4069 // Get a list of shared terms (those with more than one associated row in term_taxonomy).
4070 $shared_terms = $wpdb->get_results(
4071 "SELECT tt.term_id, t.*, count(*) as term_tt_count FROM {$wpdb->term_taxonomy} tt
4072 LEFT JOIN {$wpdb->terms} t ON t.term_id = tt.term_id
4074 HAVING term_tt_count > 1
4078 // No more terms, we're done here.
4079 if ( ! $shared_terms ) {
4080 update_option( 'finished_splitting_shared_terms', true );
4081 delete_option( $lock_name );
4085 // Shared terms found? We'll need to run this script again.
4086 wp_schedule_single_event( time() + ( 2 * MINUTE_IN_SECONDS ), 'wp_split_shared_term_batch' );
4088 // Rekey shared term array for faster lookups.
4089 $_shared_terms = array();
4090 foreach ( $shared_terms as $shared_term ) {
4091 $term_id = intval( $shared_term->term_id );
4092 $_shared_terms[ $term_id ] = $shared_term;
4094 $shared_terms = $_shared_terms;
4096 // Get term taxonomy data for all shared terms.
4097 $shared_term_ids = implode( ',', array_keys( $shared_terms ) );
4098 $shared_tts = $wpdb->get_results( "SELECT * FROM {$wpdb->term_taxonomy} WHERE `term_id` IN ({$shared_term_ids})" );
4100 // Split term data recording is slow, so we do it just once, outside the loop.
4101 $split_term_data = get_option( '_split_terms', array() );
4102 $skipped_first_term = $taxonomies = array();
4103 foreach ( $shared_tts as $shared_tt ) {
4104 $term_id = intval( $shared_tt->term_id );
4106 // Don't split the first tt belonging to a given term_id.
4107 if ( ! isset( $skipped_first_term[ $term_id ] ) ) {
4108 $skipped_first_term[ $term_id ] = 1;
4112 if ( ! isset( $split_term_data[ $term_id ] ) ) {
4113 $split_term_data[ $term_id ] = array();
4116 // Keep track of taxonomies whose hierarchies need flushing.
4117 if ( ! isset( $taxonomies[ $shared_tt->taxonomy ] ) ) {
4118 $taxonomies[ $shared_tt->taxonomy ] = 1;
4122 $split_term_data[ $term_id ][ $shared_tt->taxonomy ] = _split_shared_term( $shared_terms[ $term_id ], $shared_tt, false );
4125 // Rebuild the cached hierarchy for each affected taxonomy.
4126 foreach ( array_keys( $taxonomies ) as $tax ) {
4127 delete_option( "{$tax}_children" );
4128 _get_term_hierarchy( $tax );
4131 update_option( '_split_terms', $split_term_data );
4133 delete_option( $lock_name );
4137 * In order to avoid the _wp_batch_split_terms() job being accidentally removed,
4138 * check that it's still scheduled while we haven't finished splitting terms.
4143 function _wp_check_for_scheduled_split_terms() {
4144 if ( ! get_option( 'finished_splitting_shared_terms' ) && ! wp_next_scheduled( 'wp_split_shared_term_batch' ) ) {
4145 wp_schedule_single_event( time() + MINUTE_IN_SECONDS, 'wp_split_shared_term_batch' );
4150 * Check default categories when a term gets split to see if any of them need to be updated.
4155 * @param int $term_id ID of the formerly shared term.
4156 * @param int $new_term_id ID of the new term created for the $term_taxonomy_id.
4157 * @param int $term_taxonomy_id ID for the term_taxonomy row affected by the split.
4158 * @param string $taxonomy Taxonomy for the split term.
4160 function _wp_check_split_default_terms( $term_id, $new_term_id, $term_taxonomy_id, $taxonomy ) {
4161 if ( 'category' != $taxonomy ) {
4165 foreach ( array( 'default_category', 'default_link_category', 'default_email_category' ) as $option ) {
4166 if ( $term_id == get_option( $option, -1 ) ) {
4167 update_option( $option, $new_term_id );
4173 * Check menu items when a term gets split to see if any of them need to be updated.
4178 * @global wpdb $wpdb WordPress database abstraction object.
4180 * @param int $term_id ID of the formerly shared term.
4181 * @param int $new_term_id ID of the new term created for the $term_taxonomy_id.
4182 * @param int $term_taxonomy_id ID for the term_taxonomy row affected by the split.
4183 * @param string $taxonomy Taxonomy for the split term.
4185 function _wp_check_split_terms_in_menus( $term_id, $new_term_id, $term_taxonomy_id, $taxonomy ) {
4187 $post_ids = $wpdb->get_col( $wpdb->prepare(
4189 FROM {$wpdb->postmeta} AS m1
4190 INNER JOIN {$wpdb->postmeta} AS m2 ON ( m2.post_id = m1.post_id )
4191 INNER JOIN {$wpdb->postmeta} AS m3 ON ( m3.post_id = m1.post_id )
4192 WHERE ( m1.meta_key = '_menu_item_type' AND m1.meta_value = 'taxonomy' )
4193 AND ( m2.meta_key = '_menu_item_object' AND m2.meta_value = '%s' )
4194 AND ( m3.meta_key = '_menu_item_object_id' AND m3.meta_value = %d )",
4200 foreach ( $post_ids as $post_id ) {
4201 update_post_meta( $post_id, '_menu_item_object_id', $new_term_id, $term_id );
4207 * If the term being split is a nav_menu, change associations.
4212 * @param int $term_id ID of the formerly shared term.
4213 * @param int $new_term_id ID of the new term created for the $term_taxonomy_id.
4214 * @param int $term_taxonomy_id ID for the term_taxonomy row affected by the split.
4215 * @param string $taxonomy Taxonomy for the split term.
4217 function _wp_check_split_nav_menu_terms( $term_id, $new_term_id, $term_taxonomy_id, $taxonomy ) {
4218 if ( 'nav_menu' !== $taxonomy ) {
4222 // Update menu locations.
4223 $locations = get_nav_menu_locations();
4224 foreach ( $locations as $location => $menu_id ) {
4225 if ( $term_id == $menu_id ) {
4226 $locations[ $location ] = $new_term_id;
4229 set_theme_mod( 'nav_menu_locations', $locations );
4233 * Get data about terms that previously shared a single term_id, but have since been split.
4237 * @param int $old_term_id Term ID. This is the old, pre-split term ID.
4238 * @return array Array of new term IDs, keyed by taxonomy.
4240 function wp_get_split_terms( $old_term_id ) {
4241 $split_terms = get_option( '_split_terms', array() );
4244 if ( isset( $split_terms[ $old_term_id ] ) ) {
4245 $terms = $split_terms[ $old_term_id ];
4252 * Get the new term ID corresponding to a previously split term.
4256 * @param int $old_term_id Term ID. This is the old, pre-split term ID.
4257 * @param string $taxonomy Taxonomy that the term belongs to.
4258 * @return int|false If a previously split term is found corresponding to the old term_id and taxonomy,
4259 * the new term_id will be returned. If no previously split term is found matching
4260 * the parameters, returns false.
4262 function wp_get_split_term( $old_term_id, $taxonomy ) {
4263 $split_terms = wp_get_split_terms( $old_term_id );
4266 if ( isset( $split_terms[ $taxonomy ] ) ) {
4267 $term_id = (int) $split_terms[ $taxonomy ];
4274 * Determine whether a term is shared between multiple taxonomies.
4276 * Shared taxonomy terms began to be split in 4.3, but failed cron tasks or other delays in upgrade routines may cause
4277 * shared terms to remain.
4281 * @param int $term_id
4284 function wp_term_is_shared( $term_id ) {
4287 if ( get_option( 'finished_splitting_shared_terms' ) ) {
4291 $tt_count = $wpdb->get_var( $wpdb->prepare( "SELECT COUNT(*) FROM $wpdb->term_taxonomy WHERE term_id = %d", $term_id ) );
4293 return $tt_count > 1;
4297 * Generate a permalink for a taxonomy term archive.
4301 * @global WP_Rewrite $wp_rewrite
4303 * @param object|int|string $term The term object, ID, or slug whose link will be retrieved.
4304 * @param string $taxonomy Optional. Taxonomy. Default empty.
4305 * @return string|WP_Error HTML link to taxonomy term archive on success, WP_Error if term does not exist.
4307 function get_term_link( $term, $taxonomy = '' ) {
4310 if ( !is_object($term) ) {
4311 if ( is_int( $term ) ) {
4312 $term = get_term( $term, $taxonomy );
4314 $term = get_term_by( 'slug', $term, $taxonomy );
4318 if ( !is_object($term) )
4319 $term = new WP_Error('invalid_term', __('Empty Term'));
4321 if ( is_wp_error( $term ) )
4324 $taxonomy = $term->taxonomy;
4326 $termlink = $wp_rewrite->get_extra_permastruct($taxonomy);
4328 $slug = $term->slug;
4329 $t = get_taxonomy($taxonomy);
4331 if ( empty($termlink) ) {
4332 if ( 'category' == $taxonomy )
4333 $termlink = '?cat=' . $term->term_id;
4334 elseif ( $t->query_var )
4335 $termlink = "?$t->query_var=$slug";
4337 $termlink = "?taxonomy=$taxonomy&term=$slug";
4338 $termlink = home_url($termlink);
4340 if ( $t->rewrite['hierarchical'] ) {
4341 $hierarchical_slugs = array();
4342 $ancestors = get_ancestors( $term->term_id, $taxonomy, 'taxonomy' );
4343 foreach ( (array)$ancestors as $ancestor ) {
4344 $ancestor_term = get_term($ancestor, $taxonomy);
4345 $hierarchical_slugs[] = $ancestor_term->slug;
4347 $hierarchical_slugs = array_reverse($hierarchical_slugs);
4348 $hierarchical_slugs[] = $slug;
4349 $termlink = str_replace("%$taxonomy%", implode('/', $hierarchical_slugs), $termlink);
4351 $termlink = str_replace("%$taxonomy%", $slug, $termlink);
4353 $termlink = home_url( user_trailingslashit($termlink, 'category') );
4355 // Back Compat filters.
4356 if ( 'post_tag' == $taxonomy ) {
4359 * Filter the tag link.
4362 * @deprecated 2.5.0 Use 'term_link' instead.
4364 * @param string $termlink Tag link URL.
4365 * @param int $term_id Term ID.
4367 $termlink = apply_filters( 'tag_link', $termlink, $term->term_id );
4368 } elseif ( 'category' == $taxonomy ) {
4371 * Filter the category link.
4374 * @deprecated 2.5.0 Use 'term_link' instead.
4376 * @param string $termlink Category link URL.
4377 * @param int $term_id Term ID.
4379 $termlink = apply_filters( 'category_link', $termlink, $term->term_id );
4383 * Filter the term link.
4387 * @param string $termlink Term link URL.
4388 * @param object $term Term object.
4389 * @param string $taxonomy Taxonomy slug.
4391 return apply_filters( 'term_link', $termlink, $term, $taxonomy );
4395 * Display the taxonomies of a post with available options.
4397 * This function can be used within the loop to display the taxonomies for a
4398 * post without specifying the Post ID. You can also use it outside the Loop to
4399 * display the taxonomies for a specific post.
4403 * @param array $args {
4404 * Arguments about which post to use and how to format the output. Shares all of the arguments
4405 * supported by get_the_taxonomies(), in addition to the following.
4407 * @type int|WP_Post $post Post ID or object to get taxonomies of. Default current post.
4408 * @type string $before Displays before the taxonomies. Default empty string.
4409 * @type string $sep Separates each taxonomy. Default is a space.
4410 * @type string $after Displays after the taxonomies. Default empty string.
4412 * @param array $args See {@link get_the_taxonomies()} for a description of arguments and their defaults.
4414 function the_taxonomies( $args = array() ) {
4422 $r = wp_parse_args( $args, $defaults );
4424 echo $r['before'] . join( $r['sep'], get_the_taxonomies( $r['post'], $r ) ) . $r['after'];
4428 * Retrieve all taxonomies associated with a post.
4430 * This function can be used within the loop. It will also return an array of
4431 * the taxonomies with links to the taxonomy and name.
4435 * @param int|WP_Post $post Optional. Post ID or WP_Post object. Default is global $post.
4436 * @param array $args {
4437 * Optional. Arguments about how to format the list of taxonomies. Default empty array.
4439 * @type string $template Template for displaying a taxonomy label and list of terms.
4440 * Default is "Label: Terms."
4441 * @type string $term_template Template for displaying a single term in the list. Default is the term name
4442 * linked to its archive.
4444 * @return array List of taxonomies.
4446 function get_the_taxonomies( $post = 0, $args = array() ) {
4447 $post = get_post( $post );
4449 $args = wp_parse_args( $args, array(
4450 /* translators: %s: taxonomy label, %l: list of terms formatted as per $term_template */
4451 'template' => __( '%s: %l.' ),
4452 'term_template' => '<a href="%1$s">%2$s</a>',
4455 $taxonomies = array();
4461 foreach ( get_object_taxonomies( $post ) as $taxonomy ) {
4462 $t = (array) get_taxonomy( $taxonomy );
4463 if ( empty( $t['label'] ) ) {
4464 $t['label'] = $taxonomy;
4466 if ( empty( $t['args'] ) ) {
4467 $t['args'] = array();
4469 if ( empty( $t['template'] ) ) {
4470 $t['template'] = $args['template'];
4472 if ( empty( $t['term_template'] ) ) {
4473 $t['term_template'] = $args['term_template'];
4476 $terms = get_object_term_cache( $post->ID, $taxonomy );
4477 if ( false === $terms ) {
4478 $terms = wp_get_object_terms( $post->ID, $taxonomy, $t['args'] );
4482 foreach ( $terms as $term ) {
4483 $links[] = wp_sprintf( $t['term_template'], esc_attr( get_term_link( $term ) ), $term->name );
4486 $taxonomies[$taxonomy] = wp_sprintf( $t['template'], $t['label'], $links, $terms );
4493 * Retrieve all taxonomies of a post with just the names.
4497 * @param int|WP_Post $post Optional. Post ID or WP_Post object. Default is global $post.
4500 function get_post_taxonomies( $post = 0 ) {
4501 $post = get_post( $post );
4503 return get_object_taxonomies($post);
4507 * Determine if the given object is associated with any of the given terms.
4509 * The given terms are checked against the object's terms' term_ids, names and slugs.
4510 * Terms given as integers will only be checked against the object's terms' term_ids.
4511 * If no terms are given, determines if object is associated with any terms in the given taxonomy.
4515 * @param int $object_id ID of the object (post ID, link ID, ...).
4516 * @param string $taxonomy Single taxonomy name.
4517 * @param int|string|array $terms Optional. Term term_id, name, slug or array of said. Default null.
4518 * @return bool|WP_Error WP_Error on input error.
4520 function is_object_in_term( $object_id, $taxonomy, $terms = null ) {
4521 if ( !$object_id = (int) $object_id )
4522 return new WP_Error( 'invalid_object', __( 'Invalid object ID' ) );
4524 $object_terms = get_object_term_cache( $object_id, $taxonomy );
4525 if ( false === $object_terms ) {
4526 $object_terms = wp_get_object_terms( $object_id, $taxonomy, array( 'update_term_meta_cache' => false ) );
4527 wp_cache_set( $object_id, $object_terms, "{$taxonomy}_relationships" );
4530 if ( is_wp_error( $object_terms ) )
4531 return $object_terms;
4532 if ( empty( $object_terms ) )
4534 if ( empty( $terms ) )
4535 return ( !empty( $object_terms ) );
4537 $terms = (array) $terms;
4539 if ( $ints = array_filter( $terms, 'is_int' ) )
4540 $strs = array_diff( $terms, $ints );
4544 foreach ( $object_terms as $object_term ) {
4545 // If term is an int, check against term_ids only.
4546 if ( $ints && in_array( $object_term->term_id, $ints ) ) {
4551 // Only check numeric strings against term_id, to avoid false matches due to type juggling.
4552 $numeric_strs = array_map( 'intval', array_filter( $strs, 'is_numeric' ) );
4553 if ( in_array( $object_term->term_id, $numeric_strs, true ) ) {
4557 if ( in_array( $object_term->name, $strs ) ) return true;
4558 if ( in_array( $object_term->slug, $strs ) ) return true;
4566 * Determine if the given object type is associated with the given taxonomy.
4570 * @param string $object_type Object type string.
4571 * @param string $taxonomy Single taxonomy name.
4572 * @return bool True if object is associated with the taxonomy, otherwise false.
4574 function is_object_in_taxonomy( $object_type, $taxonomy ) {
4575 $taxonomies = get_object_taxonomies( $object_type );
4576 if ( empty( $taxonomies ) ) {
4579 return in_array( $taxonomy, $taxonomies );
4583 * Get an array of ancestor IDs for a given object.
4586 * @since 4.1.0 Introduced the `$resource_type` argument.
4588 * @param int $object_id Optional. The ID of the object. Default 0.
4589 * @param string $object_type Optional. The type of object for which we'll be retrieving
4590 * ancestors. Accepts a post type or a taxonomy name. Default empty.
4591 * @param string $resource_type Optional. Type of resource $object_type is. Accepts 'post_type'
4592 * or 'taxonomy'. Default empty.
4593 * @return array An array of ancestors from lowest to highest in the hierarchy.
4595 function get_ancestors( $object_id = 0, $object_type = '', $resource_type = '' ) {
4596 $object_id = (int) $object_id;
4598 $ancestors = array();
4600 if ( empty( $object_id ) ) {
4602 /** This filter is documented in wp-includes/taxonomy.php */
4603 return apply_filters( 'get_ancestors', $ancestors, $object_id, $object_type, $resource_type );
4606 if ( ! $resource_type ) {
4607 if ( is_taxonomy_hierarchical( $object_type ) ) {
4608 $resource_type = 'taxonomy';
4609 } elseif ( post_type_exists( $object_type ) ) {
4610 $resource_type = 'post_type';
4614 if ( 'taxonomy' === $resource_type ) {
4615 $term = get_term($object_id, $object_type);
4616 while ( ! is_wp_error($term) && ! empty( $term->parent ) && ! in_array( $term->parent, $ancestors ) ) {
4617 $ancestors[] = (int) $term->parent;
4618 $term = get_term($term->parent, $object_type);
4620 } elseif ( 'post_type' === $resource_type ) {
4621 $ancestors = get_post_ancestors($object_id);
4625 * Filter a given object's ancestors.
4628 * @since 4.1.1 Introduced the `$resource_type` parameter.
4630 * @param array $ancestors An array of object ancestors.
4631 * @param int $object_id Object ID.
4632 * @param string $object_type Type of object.
4633 * @param string $resource_type Type of resource $object_type is.
4635 return apply_filters( 'get_ancestors', $ancestors, $object_id, $object_type, $resource_type );
4639 * Returns the term's parent's term_ID.
4643 * @param int $term_id Term ID.
4644 * @param string $taxonomy Taxonomy name.
4645 * @return int|false False on error.
4647 function wp_get_term_taxonomy_parent_id( $term_id, $taxonomy ) {
4648 $term = get_term( $term_id, $taxonomy );
4649 if ( ! $term || is_wp_error( $term ) ) {
4652 return (int) $term->parent;
4656 * Checks the given subset of the term hierarchy for hierarchy loops.
4657 * Prevents loops from forming and breaks those that it finds.
4659 * Attached to the {@see 'wp_update_term_parent'} filter.
4663 * @param int $parent `term_id` of the parent for the term we're checking.
4664 * @param int $term_id The term we're checking.
4665 * @param string $taxonomy The taxonomy of the term we're checking.
4667 * @return int The new parent for the term.
4669 function wp_check_term_hierarchy_for_loops( $parent, $term_id, $taxonomy ) {
4670 // Nothing fancy here - bail
4674 // Can't be its own parent.
4675 if ( $parent == $term_id )
4678 // Now look for larger loops.
4679 if ( !$loop = wp_find_hierarchy_loop( 'wp_get_term_taxonomy_parent_id', $term_id, $parent, array( $taxonomy ) ) )
4680 return $parent; // No loop
4682 // Setting $parent to the given value causes a loop.
4683 if ( isset( $loop[$term_id] ) )
4686 // There's a loop, but it doesn't contain $term_id. Break the loop.
4687 foreach ( array_keys( $loop ) as $loop_member )
4688 wp_update_term( $loop_member, $taxonomy, array( 'parent' => 0 ) );