10 // Taxonomy Registration
14 * Creates the initial taxonomies.
16 * This function fires twice: in wp-settings.php before plugins are loaded (for
17 * backward 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 * Filters 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,
64 'capabilities' => array(
65 'manage_terms' => 'manage_categories',
66 'edit_terms' => 'edit_categories',
67 'delete_terms' => 'delete_categories',
68 'assign_terms' => 'assign_categories',
70 'show_in_rest' => true,
71 'rest_base' => 'categories',
72 'rest_controller_class' => 'WP_REST_Terms_Controller',
75 register_taxonomy( 'post_tag', 'post', array(
76 'hierarchical' => false,
78 'rewrite' => $rewrite['post_tag'],
81 'show_admin_column' => true,
83 'capabilities' => array(
84 'manage_terms' => 'manage_post_tags',
85 'edit_terms' => 'edit_post_tags',
86 'delete_terms' => 'delete_post_tags',
87 'assign_terms' => 'assign_post_tags',
89 'show_in_rest' => true,
90 'rest_base' => 'tags',
91 'rest_controller_class' => 'WP_REST_Terms_Controller',
94 register_taxonomy( 'nav_menu', 'nav_menu_item', array(
96 'hierarchical' => false,
98 'name' => __( 'Navigation Menus' ),
99 'singular_name' => __( 'Navigation Menu' ),
101 'query_var' => false,
105 'show_in_nav_menus' => false,
108 register_taxonomy( 'link_category', 'link', array(
109 'hierarchical' => false,
111 'name' => __( 'Link Categories' ),
112 'singular_name' => __( 'Link Category' ),
113 'search_items' => __( 'Search Link Categories' ),
114 'popular_items' => null,
115 'all_items' => __( 'All Link Categories' ),
116 'edit_item' => __( 'Edit Link Category' ),
117 'update_item' => __( 'Update Link Category' ),
118 'add_new_item' => __( 'Add New Link Category' ),
119 'new_item_name' => __( 'New Link Category Name' ),
120 'separate_items_with_commas' => null,
121 'add_or_remove_items' => null,
122 'choose_from_most_used' => null,
124 'capabilities' => array(
125 'manage_terms' => 'manage_links',
126 'edit_terms' => 'manage_links',
127 'delete_terms' => 'manage_links',
128 'assign_terms' => 'manage_links',
130 'query_var' => false,
137 register_taxonomy( 'post_format', 'post', array(
139 'hierarchical' => false,
141 'name' => _x( 'Format', 'post format' ),
142 'singular_name' => _x( 'Format', 'post format' ),
145 'rewrite' => $rewrite['post_format'],
148 'show_in_nav_menus' => current_theme_supports( 'post-formats' ),
153 * Retrieves a list of registered taxonomy names or objects.
157 * @global array $wp_taxonomies The registered taxonomies.
159 * @param array $args Optional. An array of `key => value` arguments to match against the taxonomy objects.
160 * Default empty array.
161 * @param string $output Optional. The type of output to return in the array. Accepts either taxonomy 'names'
162 * or 'objects'. Default 'names'.
163 * @param string $operator Optional. The logical operation to perform. Accepts 'and' or 'or'. 'or' means only
164 * one element from the array needs to match; 'and' means all elements must match.
166 * @return array A list of taxonomy names or objects.
168 function get_taxonomies( $args = array(), $output = 'names', $operator = 'and' ) {
169 global $wp_taxonomies;
171 $field = ('names' == $output) ? 'name' : false;
173 return wp_filter_object_list($wp_taxonomies, $args, $operator, $field);
177 * Return the names or objects of the taxonomies which are registered for the requested object or object type, such as
178 * a post object or post type name.
182 * $taxonomies = get_object_taxonomies( 'post' );
186 * Array( 'category', 'post_tag' )
190 * @global array $wp_taxonomies The registered taxonomies.
192 * @param array|string|WP_Post $object Name of the type of taxonomy object, or an object (row from posts)
193 * @param string $output Optional. The type of output to return in the array. Accepts either
194 * taxonomy 'names' or 'objects'. Default 'names'.
195 * @return array The names of all taxonomy of $object_type.
197 function get_object_taxonomies( $object, $output = 'names' ) {
198 global $wp_taxonomies;
200 if ( is_object($object) ) {
201 if ( $object->post_type == 'attachment' )
202 return get_attachment_taxonomies( $object, $output );
203 $object = $object->post_type;
206 $object = (array) $object;
208 $taxonomies = array();
209 foreach ( (array) $wp_taxonomies as $tax_name => $tax_obj ) {
210 if ( array_intersect($object, (array) $tax_obj->object_type) ) {
211 if ( 'names' == $output )
212 $taxonomies[] = $tax_name;
214 $taxonomies[ $tax_name ] = $tax_obj;
222 * Retrieves the taxonomy object of $taxonomy.
224 * The get_taxonomy function will first check that the parameter string given
225 * is a taxonomy object and if it is, it will return it.
229 * @global array $wp_taxonomies The registered taxonomies.
231 * @param string $taxonomy Name of taxonomy object to return.
232 * @return WP_Taxonomy|false The Taxonomy Object or false if $taxonomy doesn't exist.
234 function get_taxonomy( $taxonomy ) {
235 global $wp_taxonomies;
237 if ( ! taxonomy_exists( $taxonomy ) )
240 return $wp_taxonomies[$taxonomy];
244 * Checks that the taxonomy name exists.
246 * Formerly is_taxonomy(), introduced in 2.3.0.
250 * @global array $wp_taxonomies The registered taxonomies.
252 * @param string $taxonomy Name of taxonomy object.
253 * @return bool Whether the taxonomy exists.
255 function taxonomy_exists( $taxonomy ) {
256 global $wp_taxonomies;
258 return isset( $wp_taxonomies[$taxonomy] );
262 * Whether the taxonomy object is hierarchical.
264 * Checks to make sure that the taxonomy is an object first. Then Gets the
265 * object, and finally returns the hierarchical value in the object.
267 * A false return value might also mean that the taxonomy does not exist.
271 * @param string $taxonomy Name of taxonomy object.
272 * @return bool Whether the taxonomy is hierarchical.
274 function is_taxonomy_hierarchical($taxonomy) {
275 if ( ! taxonomy_exists($taxonomy) )
278 $taxonomy = get_taxonomy($taxonomy);
279 return $taxonomy->hierarchical;
283 * Creates or modifies a taxonomy object.
285 * Note: Do not use before the {@see 'init'} hook.
287 * A simple function for creating or modifying a taxonomy object based on the
288 * parameters given. The function will accept an array (third optional
289 * parameter), along with strings for the taxonomy name and another string for
293 * @since 4.2.0 Introduced `show_in_quick_edit` argument.
294 * @since 4.4.0 The `show_ui` argument is now enforced on the term editing screen.
295 * @since 4.4.0 The `public` argument now controls whether the taxonomy can be queried on the front end.
296 * @since 4.5.0 Introduced `publicly_queryable` argument.
297 * @since 4.7.0 Introduced `show_in_rest`, 'rest_base' and 'rest_controller_class'
298 * arguments to register the Taxonomy in REST API.
300 * @global array $wp_taxonomies Registered taxonomies.
302 * @param string $taxonomy Taxonomy key, must not exceed 32 characters.
303 * @param array|string $object_type Object type or array of object types with which the taxonomy should be associated.
304 * @param array|string $args {
305 * Optional. Array or query string of arguments for registering a taxonomy.
307 * @type array $labels An array of labels for this taxonomy. By default, Tag labels are
308 * used for non-hierarchical taxonomies, and Category labels are used
309 * for hierarchical taxonomies. See accepted values in
310 * get_taxonomy_labels(). Default empty array.
311 * @type string $description A short descriptive summary of what the taxonomy is for. Default empty.
312 * @type bool $public Whether a taxonomy is intended for use publicly either via
313 * the admin interface or by front-end users. The default settings
314 * of `$publicly_queryable`, `$show_ui`, and `$show_in_nav_menus`
315 * are inherited from `$public`.
316 * @type bool $publicly_queryable Whether the taxonomy is publicly queryable.
317 * If not set, the default is inherited from `$public`
318 * @type bool $hierarchical Whether the taxonomy is hierarchical. Default false.
319 * @type bool $show_ui Whether to generate and allow a UI for managing terms in this taxonomy in
320 * the admin. If not set, the default is inherited from `$public`
322 * @type bool $show_in_menu Whether to show the taxonomy in the admin menu. If true, the taxonomy is
323 * shown as a submenu of the object type menu. If false, no menu is shown.
324 * `$show_ui` must be true. If not set, default is inherited from `$show_ui`
326 * @type bool $show_in_nav_menus Makes this taxonomy available for selection in navigation menus. If not
327 * set, the default is inherited from `$public` (default true).
328 * @type bool $show_in_rest Whether to include the taxonomy in the REST API.
329 * @type string $rest_base To change the base url of REST API route. Default is $taxonomy.
330 * @type string $rest_controller_class REST API Controller class name. Default is 'WP_REST_Terms_Controller'.
331 * @type bool $show_tagcloud Whether to list the taxonomy in the Tag Cloud Widget controls. If not set,
332 * the default is inherited from `$show_ui` (default true).
333 * @type bool $show_in_quick_edit Whether to show the taxonomy in the quick/bulk edit panel. It not set,
334 * the default is inherited from `$show_ui` (default true).
335 * @type bool $show_admin_column Whether to display a column for the taxonomy on its post type listing
336 * screens. Default false.
337 * @type bool|callable $meta_box_cb Provide a callback function for the meta box display. If not set,
338 * post_categories_meta_box() is used for hierarchical taxonomies, and
339 * post_tags_meta_box() is used for non-hierarchical. If false, no meta
341 * @type array $capabilities {
342 * Array of capabilities for this taxonomy.
344 * @type string $manage_terms Default 'manage_categories'.
345 * @type string $edit_terms Default 'manage_categories'.
346 * @type string $delete_terms Default 'manage_categories'.
347 * @type string $assign_terms Default 'edit_posts'.
349 * @type bool|array $rewrite {
350 * Triggers the handling of rewrites for this taxonomy. Default true, using $taxonomy as slug. To prevent
351 * rewrite, set to false. To specify rewrite rules, an array can be passed with any of these keys:
353 * @type string $slug Customize the permastruct slug. Default `$taxonomy` key.
354 * @type bool $with_front Should the permastruct be prepended with WP_Rewrite::$front. Default true.
355 * @type bool $hierarchical Either hierarchical rewrite tag or not. Default false.
356 * @type int $ep_mask Assign an endpoint mask. Default `EP_NONE`.
358 * @type string $query_var Sets the query var key for this taxonomy. Default `$taxonomy` key. If
359 * false, a taxonomy cannot be loaded at `?{query_var}={term_slug}`. If a
360 * string, the query `?{query_var}={term_slug}` will be valid.
361 * @type callable $update_count_callback Works much like a hook, in that it will be called when the count is
362 * updated. Default _update_post_term_count() for taxonomies attached
363 * to post types, which confirms that the objects are published before
364 * counting them. Default _update_generic_term_count() for taxonomies
365 * attached to other object types, such as users.
366 * @type bool $_builtin This taxonomy is a "built-in" taxonomy. INTERNAL USE ONLY!
369 * @return WP_Error|void WP_Error, if errors.
371 function register_taxonomy( $taxonomy, $object_type, $args = array() ) {
372 global $wp_taxonomies;
374 if ( ! is_array( $wp_taxonomies ) )
375 $wp_taxonomies = array();
377 $args = wp_parse_args( $args );
379 if ( empty( $taxonomy ) || strlen( $taxonomy ) > 32 ) {
380 _doing_it_wrong( __FUNCTION__, __( 'Taxonomy names must be between 1 and 32 characters in length.' ), '4.2.0' );
381 return new WP_Error( 'taxonomy_length_invalid', __( 'Taxonomy names must be between 1 and 32 characters in length.' ) );
384 $taxonomy_object = new WP_Taxonomy( $taxonomy, $object_type, $args );
385 $taxonomy_object->add_rewrite_rules();
387 $wp_taxonomies[ $taxonomy ] = $taxonomy_object;
389 $taxonomy_object->add_hooks();
393 * Fires after a taxonomy is registered.
397 * @param string $taxonomy Taxonomy slug.
398 * @param array|string $object_type Object type or array of object types.
399 * @param array $args Array of taxonomy registration arguments.
401 do_action( 'registered_taxonomy', $taxonomy, $object_type, (array) $taxonomy_object );
405 * Unregisters a taxonomy.
407 * Can not be used to unregister built-in taxonomies.
411 * @global WP $wp Current WordPress environment instance.
412 * @global array $wp_taxonomies List of taxonomies.
414 * @param string $taxonomy Taxonomy name.
415 * @return bool|WP_Error True on success, WP_Error on failure or if the taxonomy doesn't exist.
417 function unregister_taxonomy( $taxonomy ) {
418 if ( ! taxonomy_exists( $taxonomy ) ) {
419 return new WP_Error( 'invalid_taxonomy', __( 'Invalid taxonomy.' ) );
422 $taxonomy_object = get_taxonomy( $taxonomy );
424 // Do not allow unregistering internal taxonomies.
425 if ( $taxonomy_object->_builtin ) {
426 return new WP_Error( 'invalid_taxonomy', __( 'Unregistering a built-in taxonomy is not allowed' ) );
429 global $wp_taxonomies;
431 $taxonomy_object->remove_rewrite_rules();
432 $taxonomy_object->remove_hooks();
434 // Remove the taxonomy.
435 unset( $wp_taxonomies[ $taxonomy ] );
438 * Fires after a taxonomy is unregistered.
442 * @param string $taxonomy Taxonomy name.
444 do_action( 'unregistered_taxonomy', $taxonomy );
450 * Builds an object with all taxonomy labels out of a taxonomy object
452 * Accepted keys of the label array in the taxonomy object:
454 * - name - general name for the taxonomy, usually plural. The same as and overridden by $tax->label. Default is Tags/Categories
455 * - singular_name - name for one object of this taxonomy. Default is Tag/Category
456 * - search_items - Default is Search Tags/Search Categories
457 * - popular_items - This string isn't used on hierarchical taxonomies. Default is Popular Tags
458 * - all_items - Default is All Tags/All Categories
459 * - parent_item - This string isn't used on non-hierarchical taxonomies. In hierarchical ones the default is Parent Category
460 * - parent_item_colon - The same as `parent_item`, but with colon `:` in the end
461 * - edit_item - Default is Edit Tag/Edit Category
462 * - view_item - Default is View Tag/View Category
463 * - update_item - Default is Update Tag/Update Category
464 * - add_new_item - Default is Add New Tag/Add New Category
465 * - new_item_name - Default is New Tag Name/New Category Name
466 * - separate_items_with_commas - This string isn't used on hierarchical taxonomies. Default is "Separate tags with commas", used in the meta box.
467 * - 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.
468 * - 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.
469 * - not_found - Default is "No tags found"/"No categories found", used in the meta box and taxonomy list table.
470 * - no_terms - Default is "No tags"/"No categories", used in the posts and media list tables.
471 * - items_list_navigation - String for the table pagination hidden heading.
472 * - items_list - String for the table hidden heading.
474 * Above, the first default value is for non-hierarchical taxonomies (like tags) and the second one is for hierarchical taxonomies (like categories).
476 * @todo Better documentation for the labels array.
479 * @since 4.3.0 Added the `no_terms` label.
480 * @since 4.4.0 Added the `items_list_navigation` and `items_list` labels.
482 * @param WP_Taxonomy $tax Taxonomy object.
483 * @return object object with all the labels as member variables.
485 function get_taxonomy_labels( $tax ) {
486 $tax->labels = (array) $tax->labels;
488 if ( isset( $tax->helps ) && empty( $tax->labels['separate_items_with_commas'] ) )
489 $tax->labels['separate_items_with_commas'] = $tax->helps;
491 if ( isset( $tax->no_tagcloud ) && empty( $tax->labels['not_found'] ) )
492 $tax->labels['not_found'] = $tax->no_tagcloud;
494 $nohier_vs_hier_defaults = array(
495 'name' => array( _x( 'Tags', 'taxonomy general name' ), _x( 'Categories', 'taxonomy general name' ) ),
496 'singular_name' => array( _x( 'Tag', 'taxonomy singular name' ), _x( 'Category', 'taxonomy singular name' ) ),
497 'search_items' => array( __( 'Search Tags' ), __( 'Search Categories' ) ),
498 'popular_items' => array( __( 'Popular Tags' ), null ),
499 'all_items' => array( __( 'All Tags' ), __( 'All Categories' ) ),
500 'parent_item' => array( null, __( 'Parent Category' ) ),
501 'parent_item_colon' => array( null, __( 'Parent Category:' ) ),
502 'edit_item' => array( __( 'Edit Tag' ), __( 'Edit Category' ) ),
503 'view_item' => array( __( 'View Tag' ), __( 'View Category' ) ),
504 'update_item' => array( __( 'Update Tag' ), __( 'Update Category' ) ),
505 'add_new_item' => array( __( 'Add New Tag' ), __( 'Add New Category' ) ),
506 'new_item_name' => array( __( 'New Tag Name' ), __( 'New Category Name' ) ),
507 'separate_items_with_commas' => array( __( 'Separate tags with commas' ), null ),
508 'add_or_remove_items' => array( __( 'Add or remove tags' ), null ),
509 'choose_from_most_used' => array( __( 'Choose from the most used tags' ), null ),
510 'not_found' => array( __( 'No tags found.' ), __( 'No categories found.' ) ),
511 'no_terms' => array( __( 'No tags' ), __( 'No categories' ) ),
512 'items_list_navigation' => array( __( 'Tags list navigation' ), __( 'Categories list navigation' ) ),
513 'items_list' => array( __( 'Tags list' ), __( 'Categories list' ) ),
515 $nohier_vs_hier_defaults['menu_name'] = $nohier_vs_hier_defaults['name'];
517 $labels = _get_custom_object_labels( $tax, $nohier_vs_hier_defaults );
519 $taxonomy = $tax->name;
521 $default_labels = clone $labels;
524 * Filters the labels of a specific taxonomy.
526 * The dynamic portion of the hook name, `$taxonomy`, refers to the taxonomy slug.
530 * @see get_taxonomy_labels() for the full list of taxonomy labels.
532 * @param object $labels Object with labels for the taxonomy as member variables.
534 $labels = apply_filters( "taxonomy_labels_{$taxonomy}", $labels );
536 // Ensure that the filtered labels contain all required default values.
537 $labels = (object) array_merge( (array) $default_labels, (array) $labels );
543 * Add an already registered taxonomy to an object type.
547 * @global array $wp_taxonomies The registered taxonomies.
549 * @param string $taxonomy Name of taxonomy object.
550 * @param string $object_type Name of the object type.
551 * @return bool True if successful, false if not.
553 function register_taxonomy_for_object_type( $taxonomy, $object_type) {
554 global $wp_taxonomies;
556 if ( !isset($wp_taxonomies[$taxonomy]) )
559 if ( ! get_post_type_object($object_type) )
562 if ( ! in_array( $object_type, $wp_taxonomies[$taxonomy]->object_type ) )
563 $wp_taxonomies[$taxonomy]->object_type[] = $object_type;
565 // Filter out empties.
566 $wp_taxonomies[ $taxonomy ]->object_type = array_filter( $wp_taxonomies[ $taxonomy ]->object_type );
572 * Remove an already registered taxonomy from an object type.
576 * @global array $wp_taxonomies The registered taxonomies.
578 * @param string $taxonomy Name of taxonomy object.
579 * @param string $object_type Name of the object type.
580 * @return bool True if successful, false if not.
582 function unregister_taxonomy_for_object_type( $taxonomy, $object_type ) {
583 global $wp_taxonomies;
585 if ( ! isset( $wp_taxonomies[ $taxonomy ] ) )
588 if ( ! get_post_type_object( $object_type ) )
591 $key = array_search( $object_type, $wp_taxonomies[ $taxonomy ]->object_type, true );
592 if ( false === $key )
595 unset( $wp_taxonomies[ $taxonomy ]->object_type[ $key ] );
604 * Retrieve object_ids of valid taxonomy and term.
606 * The strings of $taxonomies must exist before this function will continue. On
607 * failure of finding a valid taxonomy, it will return an WP_Error class, kind
608 * of like Exceptions in PHP 5, except you can't catch them. Even so, you can
609 * still test for the WP_Error class and get the error message.
611 * The $terms aren't checked the same as $taxonomies, but still need to exist
612 * for $object_ids to be returned.
614 * It is possible to change the order that object_ids is returned by either
615 * using PHP sort family functions or using the database by using $args with
616 * either ASC or DESC array. The value should be in the key named 'order'.
620 * @global wpdb $wpdb WordPress database abstraction object.
622 * @param int|array $term_ids Term id or array of term ids of terms that will be used.
623 * @param string|array $taxonomies String of taxonomy name or Array of string values of taxonomy names.
624 * @param array|string $args Change the order of the object_ids, either ASC or DESC.
625 * @return WP_Error|array If the taxonomy does not exist, then WP_Error will be returned. On success.
626 * the array can be empty meaning that there are no $object_ids found or it will return the $object_ids found.
628 function get_objects_in_term( $term_ids, $taxonomies, $args = array() ) {
631 if ( ! is_array( $term_ids ) ) {
632 $term_ids = array( $term_ids );
634 if ( ! is_array( $taxonomies ) ) {
635 $taxonomies = array( $taxonomies );
637 foreach ( (array) $taxonomies as $taxonomy ) {
638 if ( ! taxonomy_exists( $taxonomy ) ) {
639 return new WP_Error( 'invalid_taxonomy', __( 'Invalid taxonomy.' ) );
643 $defaults = array( 'order' => 'ASC' );
644 $args = wp_parse_args( $args, $defaults );
646 $order = ( 'desc' == strtolower( $args['order'] ) ) ? 'DESC' : 'ASC';
648 $term_ids = array_map('intval', $term_ids );
650 $taxonomies = "'" . implode( "', '", array_map( 'esc_sql', $taxonomies ) ) . "'";
651 $term_ids = "'" . implode( "', '", $term_ids ) . "'";
653 $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");
655 if ( ! $object_ids ){
662 * Given a taxonomy query, generates SQL to be appended to a main query.
668 * @param array $tax_query A compact tax query
669 * @param string $primary_table
670 * @param string $primary_id_column
673 function get_tax_sql( $tax_query, $primary_table, $primary_id_column ) {
674 $tax_query_obj = new WP_Tax_Query( $tax_query );
675 return $tax_query_obj->get_sql( $primary_table, $primary_id_column );
679 * Get all Term data from database by Term ID.
681 * The usage of the get_term function is to apply filters to a term object. It
682 * is possible to get a term object from the database before applying the
685 * $term ID must be part of $taxonomy, to get from the database. Failure, might
686 * be able to be captured by the hooks. Failure would be the same value as $wpdb
687 * returns for the get_row method.
689 * There are two hooks, one is specifically for each term, named 'get_term', and
690 * the second is for the taxonomy name, 'term_$taxonomy'. Both hooks gets the
691 * term object, and the taxonomy name as parameters. Both hooks are expected to
692 * return a Term object.
694 * {@see 'get_term'} hook - Takes two parameters the term Object and the taxonomy name.
695 * Must return term object. Used in get_term() as a catch-all filter for every
698 * {@see 'get_$taxonomy'} hook - Takes two parameters the term Object and the taxonomy
699 * name. Must return term object. $taxonomy will be the taxonomy name, so for
700 * example, if 'category', it would be 'get_category' as the filter name. Useful
701 * for custom taxonomies or plugging into default taxonomies.
703 * @todo Better formatting for DocBlock
706 * @since 4.4.0 Converted to return a WP_Term object if `$output` is `OBJECT`.
707 * The `$taxonomy` parameter was made optional.
709 * @global wpdb $wpdb WordPress database abstraction object.
710 * @see sanitize_term_field() The $context param lists the available values for get_term_by() $filter param.
712 * @param int|WP_Term|object $term If integer, term data will be fetched from the database, or from the cache if
713 * available. If stdClass object (as in the results of a database query), will apply
714 * filters and return a `WP_Term` object corresponding to the `$term` data. If `WP_Term`,
715 * will return `$term`.
716 * @param string $taxonomy Optional. Taxonomy name that $term is part of.
717 * @param string $output Optional. The required return type. One of OBJECT, ARRAY_A, or ARRAY_N, which correspond to
718 * a WP_Term object, an associative array, or a numeric array, respectively. Default OBJECT.
719 * @param string $filter Optional, default is raw or no WordPress defined filter will applied.
720 * @return array|WP_Term|WP_Error|null Object of the type specified by `$output` on success. When `$output` is 'OBJECT',
721 * a WP_Term instance is returned. If taxonomy does not exist, a WP_Error is
722 * returned. Returns null for miscellaneous failure.
724 function get_term( $term, $taxonomy = '', $output = OBJECT, $filter = 'raw' ) {
725 if ( empty( $term ) ) {
726 return new WP_Error( 'invalid_term', __( 'Empty Term' ) );
729 if ( $taxonomy && ! taxonomy_exists( $taxonomy ) ) {
730 return new WP_Error( 'invalid_taxonomy', __( 'Invalid taxonomy.' ) );
733 if ( $term instanceof WP_Term ) {
735 } elseif ( is_object( $term ) ) {
736 if ( empty( $term->filter ) || 'raw' === $term->filter ) {
737 $_term = sanitize_term( $term, $taxonomy, 'raw' );
738 $_term = new WP_Term( $_term );
740 $_term = WP_Term::get_instance( $term->term_id );
743 $_term = WP_Term::get_instance( $term, $taxonomy );
746 if ( is_wp_error( $_term ) ) {
748 } elseif ( ! $_term ) {
756 * @since 4.4.0 `$_term` can now also be a WP_Term object.
758 * @param int|WP_Term $_term Term object or ID.
759 * @param string $taxonomy The taxonomy slug.
761 $_term = apply_filters( 'get_term', $_term, $taxonomy );
764 * Filters a taxonomy.
766 * The dynamic portion of the filter name, `$taxonomy`, refers
767 * to the taxonomy slug.
770 * @since 4.4.0 `$_term` can now also be a WP_Term object.
772 * @param int|WP_Term $_term Term object or ID.
773 * @param string $taxonomy The taxonomy slug.
775 $_term = apply_filters( "get_{$taxonomy}", $_term, $taxonomy );
777 // Bail if a filter callback has changed the type of the `$_term` object.
778 if ( ! ( $_term instanceof WP_Term ) ) {
782 // Sanitize term, according to the specified filter.
783 $_term->filter( $filter );
785 if ( $output == ARRAY_A ) {
786 return $_term->to_array();
787 } elseif ( $output == ARRAY_N ) {
788 return array_values( $_term->to_array() );
795 * Get all Term data from database by Term field and data.
797 * Warning: $value is not escaped for 'name' $field. You must do it yourself, if
800 * The default $field is 'id', therefore it is possible to also use null for
801 * field, but not recommended that you do so.
803 * If $value does not exist, the return value will be false. If $taxonomy exists
804 * and $field and $value combinations exist, the Term will be returned.
806 * This function will always return the first term that matches the `$field`-
807 * `$value`-`$taxonomy` combination specified in the parameters. If your query
808 * is likely to match more than one term (as is likely to be the case when
809 * `$field` is 'name', for example), consider using get_terms() instead; that
810 * way, you will get all matching terms, and can provide your own logic for
811 * deciding which one was intended.
813 * @todo Better formatting for DocBlock.
816 * @since 4.4.0 `$taxonomy` is optional if `$field` is 'term_taxonomy_id'. Converted to return
817 * a WP_Term object if `$output` is `OBJECT`.
819 * @global wpdb $wpdb WordPress database abstraction object.
820 * @see sanitize_term_field() The $context param lists the available values for get_term_by() $filter param.
822 * @param string $field Either 'slug', 'name', 'id' (term_id), or 'term_taxonomy_id'
823 * @param string|int $value Search for this term value
824 * @param string $taxonomy Taxonomy name. Optional, if `$field` is 'term_taxonomy_id'.
825 * @param string $output Optional. The required return type. One of OBJECT, ARRAY_A, or ARRAY_N, which correspond to
826 * a WP_Term object, an associative array, or a numeric array, respectively. Default OBJECT.
827 * @param string $filter Optional, default is raw or no WordPress defined filter will applied.
828 * @return WP_Term|array|false WP_Term instance (or array) on success. Will return false if `$taxonomy` does not exist
829 * or `$term` was not found.
831 function get_term_by( $field, $value, $taxonomy = '', $output = OBJECT, $filter = 'raw' ) {
834 // 'term_taxonomy_id' lookups don't require taxonomy checks.
835 if ( 'term_taxonomy_id' !== $field && ! taxonomy_exists( $taxonomy ) ) {
839 $tax_clause = $wpdb->prepare( "AND tt.taxonomy = %s", $taxonomy );
841 if ( 'slug' == $field ) {
843 $value = sanitize_title($value);
846 } elseif ( 'name' == $field ) {
847 // Assume already escaped
848 $value = wp_unslash($value);
850 } elseif ( 'term_taxonomy_id' == $field ) {
851 $value = (int) $value;
852 $_field = 'tt.term_taxonomy_id';
854 // No `taxonomy` clause when searching by 'term_taxonomy_id'.
857 $term = get_term( (int) $value, $taxonomy, $output, $filter );
858 if ( is_wp_error( $term ) || is_null( $term ) ) {
864 $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", $value ) . " $tax_clause LIMIT 1" );
868 // In the case of 'term_taxonomy_id', override the provided `$taxonomy` with whatever we find in the db.
869 if ( 'term_taxonomy_id' === $field ) {
870 $taxonomy = $term->taxonomy;
873 wp_cache_add( $term->term_id, $term, 'terms' );
875 return get_term( $term, $taxonomy, $output, $filter );
879 * Merge all term children into a single array of their IDs.
881 * This recursive function will merge all of the children of $term into the same
882 * array of term IDs. Only useful for taxonomies which are hierarchical.
884 * Will return an empty array if $term does not exist in $taxonomy.
888 * @param string $term_id ID of Term to get children.
889 * @param string $taxonomy Taxonomy Name.
890 * @return array|WP_Error List of Term IDs. WP_Error returned if `$taxonomy` does not exist.
892 function get_term_children( $term_id, $taxonomy ) {
893 if ( ! taxonomy_exists( $taxonomy ) ) {
894 return new WP_Error( 'invalid_taxonomy', __( 'Invalid taxonomy.' ) );
897 $term_id = intval( $term_id );
899 $terms = _get_term_hierarchy($taxonomy);
901 if ( ! isset($terms[$term_id]) )
904 $children = $terms[$term_id];
906 foreach ( (array) $terms[$term_id] as $child ) {
907 if ( $term_id == $child ) {
911 if ( isset($terms[$child]) )
912 $children = array_merge($children, get_term_children($child, $taxonomy));
919 * Get sanitized Term field.
921 * The function is for contextual reasons and for simplicity of usage.
924 * @since 4.4.0 The `$taxonomy` parameter was made optional. `$term` can also now accept a WP_Term object.
926 * @see sanitize_term_field()
928 * @param string $field Term field to fetch.
929 * @param int|WP_Term $term Term ID or object.
930 * @param string $taxonomy Optional. Taxonomy Name. Default empty.
931 * @param string $context Optional, default is display. Look at sanitize_term_field() for available options.
932 * @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.
934 function get_term_field( $field, $term, $taxonomy = '', $context = 'display' ) {
935 $term = get_term( $term, $taxonomy );
936 if ( is_wp_error($term) )
939 if ( !is_object($term) )
942 if ( !isset($term->$field) )
945 return sanitize_term_field( $field, $term->$field, $term->term_id, $term->taxonomy, $context );
949 * Sanitizes Term for editing.
951 * Return value is sanitize_term() and usage is for sanitizing the term for
952 * editing. Function is for contextual and simplicity.
956 * @param int|object $id Term ID or object.
957 * @param string $taxonomy Taxonomy name.
958 * @return string|int|null|WP_Error Will return empty string if $term is not an object.
960 function get_term_to_edit( $id, $taxonomy ) {
961 $term = get_term( $id, $taxonomy );
963 if ( is_wp_error($term) )
966 if ( !is_object($term) )
969 return sanitize_term($term, $taxonomy, 'edit');
973 * Retrieve the terms in a given taxonomy or list of taxonomies.
975 * You can fully inject any customizations to the query before it is sent, as
976 * well as control the output with a filter.
978 * The {@see 'get_terms'} filter will be called when the cache has the term and will
979 * pass the found term along with the array of $taxonomies and array of $args.
980 * This filter is also called before the array of terms is passed and will pass
981 * the array of terms, along with the $taxonomies and $args.
983 * The {@see 'list_terms_exclusions'} filter passes the compiled exclusions along with
986 * The {@see 'get_terms_orderby'} filter passes the `ORDER BY` clause for the query
987 * along with the $args array.
989 * Prior to 4.5.0, the first parameter of `get_terms()` was a taxonomy or list of taxonomies:
991 * $terms = get_terms( 'post_tag', array(
992 * 'hide_empty' => false,
995 * Since 4.5.0, taxonomies should be passed via the 'taxonomy' argument in the `$args` array:
997 * $terms = get_terms( array(
998 * 'taxonomy' => 'post_tag',
999 * 'hide_empty' => false,
1003 * @since 4.2.0 Introduced 'name' and 'childless' parameters.
1004 * @since 4.4.0 Introduced the ability to pass 'term_id' as an alias of 'id' for the `orderby` parameter.
1005 * Introduced the 'meta_query' and 'update_term_meta_cache' parameters. Converted to return
1006 * a list of WP_Term objects.
1007 * @since 4.5.0 Changed the function signature so that the `$args` array can be provided as the first parameter.
1008 * Introduced 'meta_key' and 'meta_value' parameters. Introduced the ability to order results by metadata.
1010 * @internal The `$deprecated` parameter is parsed for backward compatibility only.
1012 * @global wpdb $wpdb WordPress database abstraction object.
1013 * @global array $wp_filter
1015 * @param array|string $args {
1016 * Optional. Array or string of arguments to get terms.
1018 * @type string|array $taxonomy Taxonomy name, or array of taxonomies, to which results should
1020 * @type string $orderby Field(s) to order terms by. Accepts term fields ('name', 'slug',
1021 * 'term_group', 'term_id', 'id', 'description'), 'count' for term
1022 * taxonomy count, 'include' to match the 'order' of the $include param,
1023 * 'meta_value', 'meta_value_num', the value of `$meta_key`, the array
1024 * keys of `$meta_query`, or 'none' to omit the ORDER BY clause.
1025 * Defaults to 'name'.
1026 * @type string $order Whether to order terms in ascending or descending order.
1027 * Accepts 'ASC' (ascending) or 'DESC' (descending).
1029 * @type bool|int $hide_empty Whether to hide terms not assigned to any posts. Accepts
1030 * 1|true or 0|false. Default 1|true.
1031 * @type array|string $include Array or comma/space-separated string of term ids to include.
1032 * Default empty array.
1033 * @type array|string $exclude Array or comma/space-separated string of term ids to exclude.
1034 * If $include is non-empty, $exclude is ignored.
1035 * Default empty array.
1036 * @type array|string $exclude_tree Array or comma/space-separated string of term ids to exclude
1037 * along with all of their descendant terms. If $include is
1038 * non-empty, $exclude_tree is ignored. Default empty array.
1039 * @type int|string $number Maximum number of terms to return. Accepts ''|0 (all) or any
1040 * positive number. Default ''|0 (all).
1041 * @type int $offset The number by which to offset the terms query. Default empty.
1042 * @type string $fields Term fields to query for. Accepts 'all' (returns an array of complete
1043 * term objects), 'ids' (returns an array of ids), 'id=>parent' (returns
1044 * an associative array with ids as keys, parent term IDs as values),
1045 * 'names' (returns an array of term names), 'count' (returns the number
1046 * of matching terms), 'id=>name' (returns an associative array with ids
1047 * as keys, term names as values), or 'id=>slug' (returns an associative
1048 * array with ids as keys, term slugs as values). Default 'all'.
1049 * @type string|array $name Optional. Name or array of names to return term(s) for. Default empty.
1050 * @type string|array $slug Optional. Slug or array of slugs to return term(s) for. Default empty.
1051 * @type bool $hierarchical Whether to include terms that have non-empty descendants (even
1052 * if $hide_empty is set to true). Default true.
1053 * @type string $search Search criteria to match terms. Will be SQL-formatted with
1054 * wildcards before and after. Default empty.
1055 * @type string $name__like Retrieve terms with criteria by which a term is LIKE $name__like.
1057 * @type string $description__like Retrieve terms where the description is LIKE $description__like.
1059 * @type bool $pad_counts Whether to pad the quantity of a term's children in the quantity
1060 * of each term's "count" object variable. Default false.
1061 * @type string $get Whether to return terms regardless of ancestry or whether the terms
1062 * are empty. Accepts 'all' or empty (disabled). Default empty.
1063 * @type int $child_of Term ID to retrieve child terms of. If multiple taxonomies
1064 * are passed, $child_of is ignored. Default 0.
1065 * @type int|string $parent Parent term ID to retrieve direct-child terms of. Default empty.
1066 * @type bool $childless True to limit results to terms that have no children. This parameter
1067 * has no effect on non-hierarchical taxonomies. Default false.
1068 * @type string $cache_domain Unique cache key to be produced when this query is stored in an
1069 * object cache. Default is 'core'.
1070 * @type bool $update_term_meta_cache Whether to prime meta caches for matched terms. Default true.
1071 * @type array $meta_query Meta query clauses to limit retrieved terms by.
1072 * See `WP_Meta_Query`. Default empty.
1073 * @type string $meta_key Limit terms to those matching a specific metadata key. Can be used in
1074 * conjunction with `$meta_value`.
1075 * @type string $meta_value Limit terms to those matching a specific metadata value. Usually used
1076 * in conjunction with `$meta_key`.
1078 * @param array $deprecated Argument array, when using the legacy function parameter format. If present, this
1079 * parameter will be interpreted as `$args`, and the first function parameter will
1080 * be parsed as a taxonomy or array of taxonomies.
1081 * @return array|int|WP_Error List of WP_Term instances and their children. Will return WP_Error, if any of $taxonomies
1084 function get_terms( $args = array(), $deprecated = '' ) {
1087 $term_query = new WP_Term_Query();
1090 * Legacy argument format ($taxonomy, $args) takes precedence.
1092 * We detect legacy argument format by checking if
1093 * (a) a second non-empty parameter is passed, or
1094 * (b) the first parameter shares no keys with the default array (ie, it's a list of taxonomies)
1096 $_args = wp_parse_args( $args );
1097 $key_intersect = array_intersect_key( $term_query->query_var_defaults, (array) $_args );
1098 $do_legacy_args = $deprecated || empty( $key_intersect );
1100 if ( $do_legacy_args ) {
1101 $taxonomies = (array) $args;
1102 $args = wp_parse_args( $deprecated );
1103 $args['taxonomy'] = $taxonomies;
1105 $args = wp_parse_args( $args );
1106 if ( isset( $args['taxonomy'] ) && null !== $args['taxonomy'] ) {
1107 $args['taxonomy'] = (array) $args['taxonomy'];
1111 if ( ! empty( $args['taxonomy'] ) ) {
1112 foreach ( $args['taxonomy'] as $taxonomy ) {
1113 if ( ! taxonomy_exists( $taxonomy ) ) {
1114 return new WP_Error( 'invalid_taxonomy', __( 'Invalid taxonomy.' ) );
1119 $terms = $term_query->query( $args );
1121 // Count queries are not filtered, for legacy reasons.
1122 if ( ! is_array( $terms ) ) {
1127 * Filters the found terms.
1130 * @since 4.6.0 Added the `$term_query` parameter.
1132 * @param array $terms Array of found terms.
1133 * @param array $taxonomies An array of taxonomies.
1134 * @param array $args An array of get_terms() arguments.
1135 * @param WP_Term_Query $term_query The WP_Term_Query object.
1137 return apply_filters( 'get_terms', $terms, $term_query->query_vars['taxonomy'], $term_query->query_vars, $term_query );
1141 * Adds metadata to a term.
1145 * @param int $term_id Term ID.
1146 * @param string $meta_key Metadata name.
1147 * @param mixed $meta_value Metadata value.
1148 * @param bool $unique Optional. Whether to bail if an entry with the same key is found for the term.
1150 * @return int|WP_Error|bool Meta ID on success. WP_Error when term_id is ambiguous between taxonomies.
1153 function add_term_meta( $term_id, $meta_key, $meta_value, $unique = false ) {
1154 // Bail if term meta table is not installed.
1155 if ( get_option( 'db_version' ) < 34370 ) {
1159 if ( wp_term_is_shared( $term_id ) ) {
1160 return new WP_Error( 'ambiguous_term_id', __( 'Term meta cannot be added to terms that are shared between taxonomies.'), $term_id );
1163 $added = add_metadata( 'term', $term_id, $meta_key, $meta_value, $unique );
1165 // Bust term query cache.
1167 wp_cache_set( 'last_changed', microtime(), 'terms' );
1174 * Removes metadata matching criteria from a term.
1178 * @param int $term_id Term ID.
1179 * @param string $meta_key Metadata name.
1180 * @param mixed $meta_value Optional. Metadata value. If provided, rows will only be removed that match the value.
1181 * @return bool True on success, false on failure.
1183 function delete_term_meta( $term_id, $meta_key, $meta_value = '' ) {
1184 // Bail if term meta table is not installed.
1185 if ( get_option( 'db_version' ) < 34370 ) {
1189 $deleted = delete_metadata( 'term', $term_id, $meta_key, $meta_value );
1191 // Bust term query cache.
1193 wp_cache_set( 'last_changed', microtime(), 'terms' );
1200 * Retrieves metadata for a term.
1204 * @param int $term_id Term ID.
1205 * @param string $key Optional. The meta key to retrieve. If no key is provided, fetches all metadata for the term.
1206 * @param bool $single Whether to return a single value. If false, an array of all values matching the
1207 * `$term_id`/`$key` pair will be returned. Default: false.
1208 * @return mixed If `$single` is false, an array of metadata values. If `$single` is true, a single metadata value.
1210 function get_term_meta( $term_id, $key = '', $single = false ) {
1211 // Bail if term meta table is not installed.
1212 if ( get_option( 'db_version' ) < 34370 ) {
1216 return get_metadata( 'term', $term_id, $key, $single );
1220 * Updates term metadata.
1222 * Use the `$prev_value` parameter to differentiate between meta fields with the same key and term ID.
1224 * If the meta field for the term does not exist, it will be added.
1228 * @param int $term_id Term ID.
1229 * @param string $meta_key Metadata key.
1230 * @param mixed $meta_value Metadata value.
1231 * @param mixed $prev_value Optional. Previous value to check before removing.
1232 * @return int|WP_Error|bool Meta ID if the key didn't previously exist. True on successful update.
1233 * WP_Error when term_id is ambiguous between taxonomies. False on failure.
1235 function update_term_meta( $term_id, $meta_key, $meta_value, $prev_value = '' ) {
1236 // Bail if term meta table is not installed.
1237 if ( get_option( 'db_version' ) < 34370 ) {
1241 if ( wp_term_is_shared( $term_id ) ) {
1242 return new WP_Error( 'ambiguous_term_id', __( 'Term meta cannot be added to terms that are shared between taxonomies.'), $term_id );
1245 $updated = update_metadata( 'term', $term_id, $meta_key, $meta_value, $prev_value );
1247 // Bust term query cache.
1249 wp_cache_set( 'last_changed', microtime(), 'terms' );
1256 * Updates metadata cache for list of term IDs.
1258 * Performs SQL query to retrieve all metadata for the terms matching `$term_ids` and stores them in the cache.
1259 * Subsequent calls to `get_term_meta()` will not need to query the database.
1263 * @param array $term_ids List of term IDs.
1264 * @return array|false Returns false if there is nothing to update. Returns an array of metadata on success.
1266 function update_termmeta_cache( $term_ids ) {
1267 // Bail if term meta table is not installed.
1268 if ( get_option( 'db_version' ) < 34370 ) {
1272 return update_meta_cache( 'term', $term_ids );
1276 * Check if Term exists.
1278 * Formerly is_term(), introduced in 2.3.0.
1282 * @global wpdb $wpdb WordPress database abstraction object.
1284 * @param int|string $term The term to check. Accepts term ID, slug, or name.
1285 * @param string $taxonomy The taxonomy name to use
1286 * @param int $parent Optional. ID of parent term under which to confine the exists search.
1287 * @return mixed Returns null if the term does not exist. Returns the term ID
1288 * if no taxonomy is specified and the term ID exists. Returns
1289 * an array of the term ID and the term taxonomy ID the taxonomy
1290 * is specified and the pairing exists.
1292 function term_exists( $term, $taxonomy = '', $parent = null ) {
1295 $select = "SELECT term_id FROM $wpdb->terms as t WHERE ";
1296 $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 ";
1298 if ( is_int($term) ) {
1301 $where = 't.term_id = %d';
1302 if ( !empty($taxonomy) )
1303 return $wpdb->get_row( $wpdb->prepare( $tax_select . $where . " AND tt.taxonomy = %s", $term, $taxonomy ), ARRAY_A );
1305 return $wpdb->get_var( $wpdb->prepare( $select . $where, $term ) );
1308 $term = trim( wp_unslash( $term ) );
1309 $slug = sanitize_title( $term );
1311 $where = 't.slug = %s';
1312 $else_where = 't.name = %s';
1313 $where_fields = array($slug);
1314 $else_where_fields = array($term);
1315 $orderby = 'ORDER BY t.term_id ASC';
1317 if ( !empty($taxonomy) ) {
1318 if ( is_numeric( $parent ) ) {
1319 $parent = (int) $parent;
1320 $where_fields[] = $parent;
1321 $else_where_fields[] = $parent;
1322 $where .= ' AND tt.parent = %d';
1323 $else_where .= ' AND tt.parent = %d';
1326 $where_fields[] = $taxonomy;
1327 $else_where_fields[] = $taxonomy;
1329 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) )
1332 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);
1335 if ( $result = $wpdb->get_var( $wpdb->prepare("SELECT term_id FROM $wpdb->terms as t WHERE $where $orderby $limit", $where_fields) ) )
1338 return $wpdb->get_var( $wpdb->prepare("SELECT term_id FROM $wpdb->terms as t WHERE $else_where $orderby $limit", $else_where_fields) );
1342 * Check if a term is an ancestor of another term.
1344 * You can use either an id or the term object for both parameters.
1348 * @param int|object $term1 ID or object to check if this is the parent term.
1349 * @param int|object $term2 The child term.
1350 * @param string $taxonomy Taxonomy name that $term1 and `$term2` belong to.
1351 * @return bool Whether `$term2` is a child of `$term1`.
1353 function term_is_ancestor_of( $term1, $term2, $taxonomy ) {
1354 if ( ! isset( $term1->term_id ) )
1355 $term1 = get_term( $term1, $taxonomy );
1356 if ( ! isset( $term2->parent ) )
1357 $term2 = get_term( $term2, $taxonomy );
1359 if ( empty( $term1->term_id ) || empty( $term2->parent ) )
1361 if ( $term2->parent == $term1->term_id )
1364 return term_is_ancestor_of( $term1, get_term( $term2->parent, $taxonomy ), $taxonomy );
1368 * Sanitize Term all fields.
1370 * Relies on sanitize_term_field() to sanitize the term. The difference is that
1371 * this function will sanitize <strong>all</strong> fields. The context is based
1372 * on sanitize_term_field().
1374 * The $term is expected to be either an array or an object.
1378 * @param array|object $term The term to check.
1379 * @param string $taxonomy The taxonomy name to use.
1380 * @param string $context Optional. Context in which to sanitize the term. Accepts 'edit', 'db',
1381 * 'display', 'attribute', or 'js'. Default 'display'.
1382 * @return array|object Term with all fields sanitized.
1384 function sanitize_term($term, $taxonomy, $context = 'display') {
1385 $fields = array( 'term_id', 'name', 'description', 'slug', 'count', 'parent', 'term_group', 'term_taxonomy_id', 'object_id' );
1387 $do_object = is_object( $term );
1389 $term_id = $do_object ? $term->term_id : (isset($term['term_id']) ? $term['term_id'] : 0);
1391 foreach ( (array) $fields as $field ) {
1393 if ( isset($term->$field) )
1394 $term->$field = sanitize_term_field($field, $term->$field, $term_id, $taxonomy, $context);
1396 if ( isset($term[$field]) )
1397 $term[$field] = sanitize_term_field($field, $term[$field], $term_id, $taxonomy, $context);
1402 $term->filter = $context;
1404 $term['filter'] = $context;
1410 * Cleanse the field value in the term based on the context.
1412 * Passing a term field value through the function should be assumed to have
1413 * cleansed the value for whatever context the term field is going to be used.
1415 * If no context or an unsupported context is given, then default filters will
1418 * There are enough filters for each context to support a custom filtering
1419 * without creating your own filter function. Simply create a function that
1420 * hooks into the filter you need.
1424 * @param string $field Term field to sanitize.
1425 * @param string $value Search for this term value.
1426 * @param int $term_id Term ID.
1427 * @param string $taxonomy Taxonomy Name.
1428 * @param string $context Context in which to sanitize the term field. Accepts 'edit', 'db', 'display',
1429 * 'attribute', or 'js'.
1430 * @return mixed Sanitized field.
1432 function sanitize_term_field($field, $value, $term_id, $taxonomy, $context) {
1433 $int_fields = array( 'parent', 'term_id', 'count', 'term_group', 'term_taxonomy_id', 'object_id' );
1434 if ( in_array( $field, $int_fields ) ) {
1435 $value = (int) $value;
1440 if ( 'raw' == $context )
1443 if ( 'edit' == $context ) {
1446 * Filters a term field to edit before it is sanitized.
1448 * The dynamic portion of the filter name, `$field`, refers to the term field.
1452 * @param mixed $value Value of the term field.
1453 * @param int $term_id Term ID.
1454 * @param string $taxonomy Taxonomy slug.
1456 $value = apply_filters( "edit_term_{$field}", $value, $term_id, $taxonomy );
1459 * Filters the taxonomy field to edit before it is sanitized.
1461 * The dynamic portions of the filter name, `$taxonomy` and `$field`, refer
1462 * to the taxonomy slug and taxonomy field, respectively.
1466 * @param mixed $value Value of the taxonomy field to edit.
1467 * @param int $term_id Term ID.
1469 $value = apply_filters( "edit_{$taxonomy}_{$field}", $value, $term_id );
1471 if ( 'description' == $field )
1472 $value = esc_html($value); // textarea_escaped
1474 $value = esc_attr($value);
1475 } elseif ( 'db' == $context ) {
1478 * Filters a term field value before it is sanitized.
1480 * The dynamic portion of the filter name, `$field`, refers to the term field.
1484 * @param mixed $value Value of the term field.
1485 * @param string $taxonomy Taxonomy slug.
1487 $value = apply_filters( "pre_term_{$field}", $value, $taxonomy );
1490 * Filters a taxonomy field before it is sanitized.
1492 * The dynamic portions of the filter name, `$taxonomy` and `$field`, refer
1493 * to the taxonomy slug and field name, respectively.
1497 * @param mixed $value Value of the taxonomy field.
1499 $value = apply_filters( "pre_{$taxonomy}_{$field}", $value );
1501 // Back compat filters
1502 if ( 'slug' == $field ) {
1504 * Filters the category nicename before it is sanitized.
1506 * Use the {@see 'pre_$taxonomy_$field'} hook instead.
1510 * @param string $value The category nicename.
1512 $value = apply_filters( 'pre_category_nicename', $value );
1515 } elseif ( 'rss' == $context ) {
1518 * Filters the term field for use in RSS.
1520 * The dynamic portion of the filter name, `$field`, refers to the term field.
1524 * @param mixed $value Value of the term field.
1525 * @param string $taxonomy Taxonomy slug.
1527 $value = apply_filters( "term_{$field}_rss", $value, $taxonomy );
1530 * Filters the taxonomy field for use in RSS.
1532 * The dynamic portions of the hook name, `$taxonomy`, and `$field`, refer
1533 * to the taxonomy slug and field name, respectively.
1537 * @param mixed $value Value of the taxonomy field.
1539 $value = apply_filters( "{$taxonomy}_{$field}_rss", $value );
1541 // Use display filters by default.
1544 * Filters the term field sanitized for display.
1546 * The dynamic portion of the filter name, `$field`, refers to the term field name.
1550 * @param mixed $value Value of the term field.
1551 * @param int $term_id Term ID.
1552 * @param string $taxonomy Taxonomy slug.
1553 * @param string $context Context to retrieve the term field value.
1555 $value = apply_filters( "term_{$field}", $value, $term_id, $taxonomy, $context );
1558 * Filters the taxonomy field sanitized for display.
1560 * The dynamic portions of the filter name, `$taxonomy`, and `$field`, refer
1561 * to the taxonomy slug and taxonomy field, respectively.
1565 * @param mixed $value Value of the taxonomy field.
1566 * @param int $term_id Term ID.
1567 * @param string $context Context to retrieve the taxonomy field value.
1569 $value = apply_filters( "{$taxonomy}_{$field}", $value, $term_id, $context );
1572 if ( 'attribute' == $context ) {
1573 $value = esc_attr($value);
1574 } elseif ( 'js' == $context ) {
1575 $value = esc_js($value);
1581 * Count how many terms are in Taxonomy.
1583 * Default $args is 'hide_empty' which can be 'hide_empty=true' or array('hide_empty' => true).
1587 * @param string $taxonomy Taxonomy name.
1588 * @param array|string $args Optional. Array of arguments that get passed to get_terms().
1589 * Default empty array.
1590 * @return array|int|WP_Error Number of terms in that taxonomy or WP_Error if the taxonomy does not exist.
1592 function wp_count_terms( $taxonomy, $args = array() ) {
1593 $defaults = array('hide_empty' => false);
1594 $args = wp_parse_args($args, $defaults);
1596 // backward compatibility
1597 if ( isset($args['ignore_empty']) ) {
1598 $args['hide_empty'] = $args['ignore_empty'];
1599 unset($args['ignore_empty']);
1602 $args['fields'] = 'count';
1604 return get_terms($taxonomy, $args);
1608 * Will unlink the object from the taxonomy or taxonomies.
1610 * Will remove all relationships between the object and any terms in
1611 * a particular taxonomy or taxonomies. Does not remove the term or
1616 * @param int $object_id The term Object Id that refers to the term.
1617 * @param string|array $taxonomies List of Taxonomy Names or single Taxonomy name.
1619 function wp_delete_object_term_relationships( $object_id, $taxonomies ) {
1620 $object_id = (int) $object_id;
1622 if ( !is_array($taxonomies) )
1623 $taxonomies = array($taxonomies);
1625 foreach ( (array) $taxonomies as $taxonomy ) {
1626 $term_ids = wp_get_object_terms( $object_id, $taxonomy, array( 'fields' => 'ids' ) );
1627 $term_ids = array_map( 'intval', $term_ids );
1628 wp_remove_object_terms( $object_id, $term_ids, $taxonomy );
1633 * Removes a term from the database.
1635 * If the term is a parent of other terms, then the children will be updated to
1636 * that term's parent.
1638 * Metadata associated with the term will be deleted.
1642 * @global wpdb $wpdb WordPress database abstraction object.
1644 * @param int $term Term ID.
1645 * @param string $taxonomy Taxonomy Name.
1646 * @param array|string $args {
1647 * Optional. Array of arguments to override the default term ID. Default empty array.
1649 * @type int $default The term ID to make the default term. This will only override
1650 * the terms found if there is only one term found. Any other and
1651 * the found terms are used.
1652 * @type bool $force_default Optional. Whether to force the supplied term as default to be
1653 * assigned even if the object was not going to be term-less.
1656 * @return bool|int|WP_Error True on success, false if term does not exist. Zero on attempted
1657 * deletion of default Category. WP_Error if the taxonomy does not exist.
1659 function wp_delete_term( $term, $taxonomy, $args = array() ) {
1662 $term = (int) $term;
1664 if ( ! $ids = term_exists($term, $taxonomy) )
1666 if ( is_wp_error( $ids ) )
1669 $tt_id = $ids['term_taxonomy_id'];
1671 $defaults = array();
1673 if ( 'category' == $taxonomy ) {
1674 $defaults['default'] = get_option( 'default_category' );
1675 if ( $defaults['default'] == $term )
1676 return 0; // Don't delete the default category
1679 $args = wp_parse_args($args, $defaults);
1681 if ( isset( $args['default'] ) ) {
1682 $default = (int) $args['default'];
1683 if ( ! term_exists( $default, $taxonomy ) ) {
1688 if ( isset( $args['force_default'] ) ) {
1689 $force_default = $args['force_default'];
1693 * Fires when deleting a term, before any modifications are made to posts or terms.
1697 * @param int $term Term ID.
1698 * @param string $taxonomy Taxonomy Name.
1700 do_action( 'pre_delete_term', $term, $taxonomy );
1702 // Update children to point to new parent
1703 if ( is_taxonomy_hierarchical($taxonomy) ) {
1704 $term_obj = get_term($term, $taxonomy);
1705 if ( is_wp_error( $term_obj ) )
1707 $parent = $term_obj->parent;
1709 $edit_ids = $wpdb->get_results( "SELECT term_id, term_taxonomy_id FROM $wpdb->term_taxonomy WHERE `parent` = " . (int)$term_obj->term_id );
1710 $edit_tt_ids = wp_list_pluck( $edit_ids, 'term_taxonomy_id' );
1713 * Fires immediately before a term to delete's children are reassigned a parent.
1717 * @param array $edit_tt_ids An array of term taxonomy IDs for the given term.
1719 do_action( 'edit_term_taxonomies', $edit_tt_ids );
1721 $wpdb->update( $wpdb->term_taxonomy, compact( 'parent' ), array( 'parent' => $term_obj->term_id) + compact( 'taxonomy' ) );
1723 // Clean the cache for all child terms.
1724 $edit_term_ids = wp_list_pluck( $edit_ids, 'term_id' );
1725 clean_term_cache( $edit_term_ids, $taxonomy );
1728 * Fires immediately after a term to delete's children are reassigned a parent.
1732 * @param array $edit_tt_ids An array of term taxonomy IDs for the given term.
1734 do_action( 'edited_term_taxonomies', $edit_tt_ids );
1737 // Get the term before deleting it or its term relationships so we can pass to actions below.
1738 $deleted_term = get_term( $term, $taxonomy );
1740 $object_ids = (array) $wpdb->get_col( $wpdb->prepare( "SELECT object_id FROM $wpdb->term_relationships WHERE term_taxonomy_id = %d", $tt_id ) );
1742 foreach ( $object_ids as $object_id ) {
1743 $terms = wp_get_object_terms( $object_id, $taxonomy, array( 'fields' => 'ids', 'orderby' => 'none' ) );
1744 if ( 1 == count($terms) && isset($default) ) {
1745 $terms = array($default);
1747 $terms = array_diff($terms, array($term));
1748 if (isset($default) && isset($force_default) && $force_default)
1749 $terms = array_merge($terms, array($default));
1751 $terms = array_map('intval', $terms);
1752 wp_set_object_terms( $object_id, $terms, $taxonomy );
1755 // Clean the relationship caches for all object types using this term.
1756 $tax_object = get_taxonomy( $taxonomy );
1757 foreach ( $tax_object->object_type as $object_type )
1758 clean_object_term_cache( $object_ids, $object_type );
1760 $term_meta_ids = $wpdb->get_col( $wpdb->prepare( "SELECT meta_id FROM $wpdb->termmeta WHERE term_id = %d ", $term ) );
1761 foreach ( $term_meta_ids as $mid ) {
1762 delete_metadata_by_mid( 'term', $mid );
1766 * Fires immediately before a term taxonomy ID is deleted.
1770 * @param int $tt_id Term taxonomy ID.
1772 do_action( 'delete_term_taxonomy', $tt_id );
1773 $wpdb->delete( $wpdb->term_taxonomy, array( 'term_taxonomy_id' => $tt_id ) );
1776 * Fires immediately after a term taxonomy ID is deleted.
1780 * @param int $tt_id Term taxonomy ID.
1782 do_action( 'deleted_term_taxonomy', $tt_id );
1784 // Delete the term if no taxonomies use it.
1785 if ( !$wpdb->get_var( $wpdb->prepare( "SELECT COUNT(*) FROM $wpdb->term_taxonomy WHERE term_id = %d", $term) ) )
1786 $wpdb->delete( $wpdb->terms, array( 'term_id' => $term ) );
1788 clean_term_cache($term, $taxonomy);
1791 * Fires after a term is deleted from the database and the cache is cleaned.
1794 * @since 4.5.0 Introduced the `$object_ids` argument.
1796 * @param int $term Term ID.
1797 * @param int $tt_id Term taxonomy ID.
1798 * @param string $taxonomy Taxonomy slug.
1799 * @param mixed $deleted_term Copy of the already-deleted term, in the form specified
1800 * by the parent function. WP_Error otherwise.
1801 * @param array $object_ids List of term object IDs.
1803 do_action( 'delete_term', $term, $tt_id, $taxonomy, $deleted_term, $object_ids );
1806 * Fires after a term in a specific taxonomy is deleted.
1808 * The dynamic portion of the hook name, `$taxonomy`, refers to the specific
1809 * taxonomy the term belonged to.
1812 * @since 4.5.0 Introduced the `$object_ids` argument.
1814 * @param int $term Term ID.
1815 * @param int $tt_id Term taxonomy ID.
1816 * @param mixed $deleted_term Copy of the already-deleted term, in the form specified
1817 * by the parent function. WP_Error otherwise.
1818 * @param array $object_ids List of term object IDs.
1820 do_action( "delete_{$taxonomy}", $term, $tt_id, $deleted_term, $object_ids );
1826 * Deletes one existing category.
1830 * @param int $cat_ID
1831 * @return bool|int|WP_Error Returns true if completes delete action; false if term doesn't exist;
1832 * Zero on attempted deletion of default Category; WP_Error object is also a possibility.
1834 function wp_delete_category( $cat_ID ) {
1835 return wp_delete_term( $cat_ID, 'category' );
1839 * Retrieves the terms associated with the given object(s), in the supplied taxonomies.
1842 * @since 4.2.0 Added support for 'taxonomy', 'parent', and 'term_taxonomy_id' values of `$orderby`.
1843 * Introduced `$parent` argument.
1844 * @since 4.4.0 Introduced `$meta_query` and `$update_term_meta_cache` arguments. When `$fields` is 'all' or
1845 * 'all_with_object_id', an array of `WP_Term` objects will be returned.
1846 * @since 4.7.0 Refactored to use WP_Term_Query, and to support any WP_Term_Query arguments.
1848 * @global wpdb $wpdb WordPress database abstraction object.
1850 * @param int|array $object_ids The ID(s) of the object(s) to retrieve.
1851 * @param string|array $taxonomies The taxonomies to retrieve terms from.
1852 * @param array|string $args See WP_Term_Query::__construct() for supported arguments.
1853 * @return array|WP_Error The requested term data or empty array if no terms found.
1854 * WP_Error if any of the $taxonomies don't exist.
1856 function wp_get_object_terms($object_ids, $taxonomies, $args = array()) {
1859 if ( empty( $object_ids ) || empty( $taxonomies ) )
1862 if ( !is_array($taxonomies) )
1863 $taxonomies = array($taxonomies);
1865 foreach ( $taxonomies as $taxonomy ) {
1866 if ( ! taxonomy_exists($taxonomy) )
1867 return new WP_Error( 'invalid_taxonomy', __( 'Invalid taxonomy.' ) );
1870 if ( !is_array($object_ids) )
1871 $object_ids = array($object_ids);
1872 $object_ids = array_map('intval', $object_ids);
1874 $args = wp_parse_args( $args );
1876 $args['taxonomy'] = $taxonomies;
1877 $args['object_ids'] = $object_ids;
1879 $terms = get_terms( $args );
1882 * Filters the terms for a given object or objects.
1886 * @param array $terms An array of terms for the given object or objects.
1887 * @param array $object_ids Array of object IDs for which `$terms` were retrieved.
1888 * @param array $taxonomies Array of taxonomies from which `$terms` were retrieved.
1889 * @param array $args An array of arguments for retrieving terms for the given
1890 * object(s). See wp_get_object_terms() for details.
1892 $terms = apply_filters( 'get_object_terms', $terms, $object_ids, $taxonomies, $args );
1894 $object_ids = implode( ',', $object_ids );
1895 $taxonomies = implode( ',', $taxonomies );
1898 * Filters the terms for a given object or objects.
1900 * The `$taxonomies` parameter passed to this filter is formatted as a SQL fragment. The
1901 * {@see 'get_object_terms'} filter is recommended as an alternative.
1905 * @param array $terms An array of terms for the given object or objects.
1906 * @param int|array $object_ids Object ID or array of IDs.
1907 * @param string $taxonomies SQL-formatted (comma-separated and quoted) list of taxonomy names.
1908 * @param array $args An array of arguments for retrieving terms for the given object(s).
1909 * See wp_get_object_terms() for details.
1911 return apply_filters( 'wp_get_object_terms', $terms, $object_ids, $taxonomies, $args );
1915 * Add a new term to the database.
1917 * A non-existent term is inserted in the following sequence:
1918 * 1. The term is added to the term table, then related to the taxonomy.
1919 * 2. If everything is correct, several actions are fired.
1920 * 3. The 'term_id_filter' is evaluated.
1921 * 4. The term cache is cleaned.
1922 * 5. Several more actions are fired.
1923 * 6. An array is returned containing the term_id and term_taxonomy_id.
1925 * If the 'slug' argument is not empty, then it is checked to see if the term
1926 * is invalid. If it is not a valid, existing term, it is added and the term_id
1929 * If the taxonomy is hierarchical, and the 'parent' argument is not empty,
1930 * the term is inserted and the term_id will be given.
1933 * If $taxonomy does not exist or $term is empty,
1934 * a WP_Error object will be returned.
1936 * If the term already exists on the same hierarchical level,
1937 * or the term slug and name are not unique, a WP_Error object will be returned.
1939 * @global wpdb $wpdb WordPress database abstraction object.
1943 * @param string $term The term to add or update.
1944 * @param string $taxonomy The taxonomy to which to add the term.
1945 * @param array|string $args {
1946 * Optional. Array or string of arguments for inserting a term.
1948 * @type string $alias_of Slug of the term to make this term an alias of.
1949 * Default empty string. Accepts a term slug.
1950 * @type string $description The term description. Default empty string.
1951 * @type int $parent The id of the parent term. Default 0.
1952 * @type string $slug The term slug to use. Default empty string.
1954 * @return array|WP_Error An array containing the `term_id` and `term_taxonomy_id`,
1955 * WP_Error otherwise.
1957 function wp_insert_term( $term, $taxonomy, $args = array() ) {
1960 if ( ! taxonomy_exists($taxonomy) ) {
1961 return new WP_Error( 'invalid_taxonomy', __( 'Invalid taxonomy.' ) );
1964 * Filters a term before it is sanitized and inserted into the database.
1968 * @param string $term The term to add or update.
1969 * @param string $taxonomy Taxonomy slug.
1971 $term = apply_filters( 'pre_insert_term', $term, $taxonomy );
1972 if ( is_wp_error( $term ) ) {
1975 if ( is_int( $term ) && 0 == $term ) {
1976 return new WP_Error( 'invalid_term_id', __( 'Invalid term ID.' ) );
1978 if ( '' == trim( $term ) ) {
1979 return new WP_Error( 'empty_term_name', __( 'A name is required for this term.' ) );
1981 $defaults = array( 'alias_of' => '', 'description' => '', 'parent' => 0, 'slug' => '');
1982 $args = wp_parse_args( $args, $defaults );
1984 if ( $args['parent'] > 0 && ! term_exists( (int) $args['parent'] ) ) {
1985 return new WP_Error( 'missing_parent', __( 'Parent term does not exist.' ) );
1988 $args['name'] = $term;
1989 $args['taxonomy'] = $taxonomy;
1991 // Coerce null description to strings, to avoid database errors.
1992 $args['description'] = (string) $args['description'];
1994 $args = sanitize_term($args, $taxonomy, 'db');
1996 // expected_slashed ($name)
1997 $name = wp_unslash( $args['name'] );
1998 $description = wp_unslash( $args['description'] );
1999 $parent = (int) $args['parent'];
2001 $slug_provided = ! empty( $args['slug'] );
2002 if ( ! $slug_provided ) {
2003 $slug = sanitize_title( $name );
2005 $slug = $args['slug'];
2009 if ( $args['alias_of'] ) {
2010 $alias = get_term_by( 'slug', $args['alias_of'], $taxonomy );
2011 if ( ! empty( $alias->term_group ) ) {
2012 // The alias we want is already in a group, so let's use that one.
2013 $term_group = $alias->term_group;
2014 } elseif ( ! empty( $alias->term_id ) ) {
2016 * The alias is not in a group, so we create a new one
2017 * and add the alias to it.
2019 $term_group = $wpdb->get_var("SELECT MAX(term_group) FROM $wpdb->terms") + 1;
2021 wp_update_term( $alias->term_id, $taxonomy, array(
2022 'term_group' => $term_group,
2028 * Prevent the creation of terms with duplicate names at the same level of a taxonomy hierarchy,
2029 * unless a unique slug has been explicitly provided.
2031 $name_matches = get_terms( $taxonomy, array(
2033 'hide_empty' => false,
2037 * The `name` match in `get_terms()` doesn't differentiate accented characters,
2038 * so we do a stricter comparison here.
2041 if ( $name_matches ) {
2042 foreach ( $name_matches as $_match ) {
2043 if ( strtolower( $name ) === strtolower( $_match->name ) ) {
2044 $name_match = $_match;
2050 if ( $name_match ) {
2051 $slug_match = get_term_by( 'slug', $slug, $taxonomy );
2052 if ( ! $slug_provided || $name_match->slug === $slug || $slug_match ) {
2053 if ( is_taxonomy_hierarchical( $taxonomy ) ) {
2054 $siblings = get_terms( $taxonomy, array( 'get' => 'all', 'parent' => $parent ) );
2056 $existing_term = null;
2057 if ( $name_match->slug === $slug && in_array( $name, wp_list_pluck( $siblings, 'name' ) ) ) {
2058 $existing_term = $name_match;
2059 } elseif ( $slug_match && in_array( $slug, wp_list_pluck( $siblings, 'slug' ) ) ) {
2060 $existing_term = $slug_match;
2063 if ( $existing_term ) {
2064 return new WP_Error( 'term_exists', __( 'A term with the name provided already exists with this parent.' ), $existing_term->term_id );
2067 return new WP_Error( 'term_exists', __( 'A term with the name provided already exists in this taxonomy.' ), $name_match->term_id );
2072 $slug = wp_unique_term_slug( $slug, (object) $args );
2074 $data = compact( 'name', 'slug', 'term_group' );
2077 * Filters term data before it is inserted into the database.
2081 * @param array $data Term data to be inserted.
2082 * @param string $taxonomy Taxonomy slug.
2083 * @param array $args Arguments passed to wp_insert_term().
2085 $data = apply_filters( 'wp_insert_term_data', $data, $taxonomy, $args );
2087 if ( false === $wpdb->insert( $wpdb->terms, $data ) ) {
2088 return new WP_Error( 'db_insert_error', __( 'Could not insert term into the database' ), $wpdb->last_error );
2091 $term_id = (int) $wpdb->insert_id;
2093 // Seems unreachable, However, Is used in the case that a term name is provided, which sanitizes to an empty string.
2094 if ( empty($slug) ) {
2095 $slug = sanitize_title($slug, $term_id);
2097 /** This action is documented in wp-includes/taxonomy.php */
2098 do_action( 'edit_terms', $term_id, $taxonomy );
2099 $wpdb->update( $wpdb->terms, compact( 'slug' ), compact( 'term_id' ) );
2101 /** This action is documented in wp-includes/taxonomy.php */
2102 do_action( 'edited_terms', $term_id, $taxonomy );
2105 $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 ) );
2107 if ( !empty($tt_id) ) {
2108 return array('term_id' => $term_id, 'term_taxonomy_id' => $tt_id);
2110 $wpdb->insert( $wpdb->term_taxonomy, compact( 'term_id', 'taxonomy', 'description', 'parent') + array( 'count' => 0 ) );
2111 $tt_id = (int) $wpdb->insert_id;
2114 * Sanity check: if we just created a term with the same parent + taxonomy + slug but a higher term_id than
2115 * an existing term, then we have unwittingly created a duplicate term. Delete the dupe, and use the term_id
2116 * and term_taxonomy_id of the older term instead. Then return out of the function so that the "create" hooks
2119 $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 ) );
2120 if ( $duplicate_term ) {
2121 $wpdb->delete( $wpdb->terms, array( 'term_id' => $term_id ) );
2122 $wpdb->delete( $wpdb->term_taxonomy, array( 'term_taxonomy_id' => $tt_id ) );
2124 $term_id = (int) $duplicate_term->term_id;
2125 $tt_id = (int) $duplicate_term->term_taxonomy_id;
2127 clean_term_cache( $term_id, $taxonomy );
2128 return array( 'term_id' => $term_id, 'term_taxonomy_id' => $tt_id );
2132 * Fires immediately after a new term is created, before the term cache is cleaned.
2136 * @param int $term_id Term ID.
2137 * @param int $tt_id Term taxonomy ID.
2138 * @param string $taxonomy Taxonomy slug.
2140 do_action( "create_term", $term_id, $tt_id, $taxonomy );
2143 * Fires after a new term is created for a specific taxonomy.
2145 * The dynamic portion of the hook name, `$taxonomy`, refers
2146 * to the slug of the taxonomy the term was created for.
2150 * @param int $term_id Term ID.
2151 * @param int $tt_id Term taxonomy ID.
2153 do_action( "create_{$taxonomy}", $term_id, $tt_id );
2156 * Filters the term ID after a new term is created.
2160 * @param int $term_id Term ID.
2161 * @param int $tt_id Taxonomy term ID.
2163 $term_id = apply_filters( 'term_id_filter', $term_id, $tt_id );
2165 clean_term_cache($term_id, $taxonomy);
2168 * Fires after a new term is created, and after the term cache has been cleaned.
2172 * @param int $term_id Term ID.
2173 * @param int $tt_id Term taxonomy ID.
2174 * @param string $taxonomy Taxonomy slug.
2176 do_action( 'created_term', $term_id, $tt_id, $taxonomy );
2179 * Fires after a new term in a specific taxonomy is created, and after the term
2180 * cache has been cleaned.
2182 * The dynamic portion of the hook name, `$taxonomy`, refers to the taxonomy slug.
2186 * @param int $term_id Term ID.
2187 * @param int $tt_id Term taxonomy ID.
2189 do_action( "created_{$taxonomy}", $term_id, $tt_id );
2191 return array('term_id' => $term_id, 'term_taxonomy_id' => $tt_id);
2195 * Create Term and Taxonomy Relationships.
2197 * Relates an object (post, link etc) to a term and taxonomy type. Creates the
2198 * term and taxonomy relationship if it doesn't already exist. Creates a term if
2199 * it doesn't exist (using the slug).
2201 * A relationship means that the term is grouped in or belongs to the taxonomy.
2202 * A term has no meaning until it is given context by defining which taxonomy it
2207 * @global wpdb $wpdb The WordPress database abstraction object.
2209 * @param int $object_id The object to relate to.
2210 * @param array|int|string $terms A single term slug, single term id, or array of either term slugs or ids.
2211 * Will replace all existing related terms in this taxonomy.
2212 * @param string $taxonomy The context in which to relate the term to the object.
2213 * @param bool $append Optional. If false will delete difference of terms. Default false.
2214 * @return array|WP_Error Term taxonomy IDs of the affected terms.
2216 function wp_set_object_terms( $object_id, $terms, $taxonomy, $append = false ) {
2219 $object_id = (int) $object_id;
2221 if ( ! taxonomy_exists( $taxonomy ) ) {
2222 return new WP_Error( 'invalid_taxonomy', __( 'Invalid taxonomy.' ) );
2225 if ( !is_array($terms) )
2226 $terms = array($terms);
2229 $old_tt_ids = wp_get_object_terms($object_id, $taxonomy, array('fields' => 'tt_ids', 'orderby' => 'none'));
2231 $old_tt_ids = array();
2234 $term_ids = array();
2235 $new_tt_ids = array();
2237 foreach ( (array) $terms as $term) {
2238 if ( !strlen(trim($term)) )
2241 if ( !$term_info = term_exists($term, $taxonomy) ) {
2242 // Skip if a non-existent term ID is passed.
2243 if ( is_int($term) )
2245 $term_info = wp_insert_term($term, $taxonomy);
2247 if ( is_wp_error($term_info) )
2249 $term_ids[] = $term_info['term_id'];
2250 $tt_id = $term_info['term_taxonomy_id'];
2253 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 ) ) )
2257 * Fires immediately before an object-term relationship is added.
2260 * @since 4.7.0 Added the `$taxonomy` parameter.
2262 * @param int $object_id Object ID.
2263 * @param int $tt_id Term taxonomy ID.
2264 * @param string $taxonomy Taxonomy slug.
2266 do_action( 'add_term_relationship', $object_id, $tt_id, $taxonomy );
2267 $wpdb->insert( $wpdb->term_relationships, array( 'object_id' => $object_id, 'term_taxonomy_id' => $tt_id ) );
2270 * Fires immediately after an object-term relationship is added.
2273 * @since 4.7.0 Added the `$taxonomy` parameter.
2275 * @param int $object_id Object ID.
2276 * @param int $tt_id Term taxonomy ID.
2277 * @param string $taxonomy Taxonomy slug.
2279 do_action( 'added_term_relationship', $object_id, $tt_id, $taxonomy );
2280 $new_tt_ids[] = $tt_id;
2284 wp_update_term_count( $new_tt_ids, $taxonomy );
2287 $delete_tt_ids = array_diff( $old_tt_ids, $tt_ids );
2289 if ( $delete_tt_ids ) {
2290 $in_delete_tt_ids = "'" . implode( "', '", $delete_tt_ids ) . "'";
2291 $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 ) );
2292 $delete_term_ids = array_map( 'intval', $delete_term_ids );
2294 $remove = wp_remove_object_terms( $object_id, $delete_term_ids, $taxonomy );
2295 if ( is_wp_error( $remove ) ) {
2301 $t = get_taxonomy($taxonomy);
2302 if ( ! $append && isset($t->sort) && $t->sort ) {
2305 $final_tt_ids = wp_get_object_terms($object_id, $taxonomy, array('fields' => 'tt_ids'));
2306 foreach ( $tt_ids as $tt_id )
2307 if ( in_array($tt_id, $final_tt_ids) )
2308 $values[] = $wpdb->prepare( "(%d, %d, %d)", $object_id, $tt_id, ++$term_order);
2310 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)" ) )
2311 return new WP_Error( 'db_insert_error', __( 'Could not insert term relationship into the database' ), $wpdb->last_error );
2314 wp_cache_delete( $object_id, $taxonomy . '_relationships' );
2317 * Fires after an object's terms have been set.
2321 * @param int $object_id Object ID.
2322 * @param array $terms An array of object terms.
2323 * @param array $tt_ids An array of term taxonomy IDs.
2324 * @param string $taxonomy Taxonomy slug.
2325 * @param bool $append Whether to append new terms to the old terms.
2326 * @param array $old_tt_ids Old array of term taxonomy IDs.
2328 do_action( 'set_object_terms', $object_id, $terms, $tt_ids, $taxonomy, $append, $old_tt_ids );
2333 * Add term(s) associated with a given object.
2337 * @param int $object_id The ID of the object to which the terms will be added.
2338 * @param array|int|string $terms The slug(s) or ID(s) of the term(s) to add.
2339 * @param array|string $taxonomy Taxonomy name.
2340 * @return array|WP_Error Term taxonomy IDs of the affected terms.
2342 function wp_add_object_terms( $object_id, $terms, $taxonomy ) {
2343 return wp_set_object_terms( $object_id, $terms, $taxonomy, true );
2347 * Remove term(s) associated with a given object.
2351 * @global wpdb $wpdb WordPress database abstraction object.
2353 * @param int $object_id The ID of the object from which the terms will be removed.
2354 * @param array|int|string $terms The slug(s) or ID(s) of the term(s) to remove.
2355 * @param array|string $taxonomy Taxonomy name.
2356 * @return bool|WP_Error True on success, false or WP_Error on failure.
2358 function wp_remove_object_terms( $object_id, $terms, $taxonomy ) {
2361 $object_id = (int) $object_id;
2363 if ( ! taxonomy_exists( $taxonomy ) ) {
2364 return new WP_Error( 'invalid_taxonomy', __( 'Invalid taxonomy.' ) );
2367 if ( ! is_array( $terms ) ) {
2368 $terms = array( $terms );
2373 foreach ( (array) $terms as $term ) {
2374 if ( ! strlen( trim( $term ) ) ) {
2378 if ( ! $term_info = term_exists( $term, $taxonomy ) ) {
2379 // Skip if a non-existent term ID is passed.
2380 if ( is_int( $term ) ) {
2385 if ( is_wp_error( $term_info ) ) {
2389 $tt_ids[] = $term_info['term_taxonomy_id'];
2393 $in_tt_ids = "'" . implode( "', '", $tt_ids ) . "'";
2396 * Fires immediately before an object-term relationship is deleted.
2399 * @since 4.7.0 Added the `$taxonomy` parameter.
2401 * @param int $object_id Object ID.
2402 * @param array $tt_ids An array of term taxonomy IDs.
2403 * @param string $taxonomy Taxonomy slug.
2405 do_action( 'delete_term_relationships', $object_id, $tt_ids, $taxonomy );
2406 $deleted = $wpdb->query( $wpdb->prepare( "DELETE FROM $wpdb->term_relationships WHERE object_id = %d AND term_taxonomy_id IN ($in_tt_ids)", $object_id ) );
2408 wp_cache_delete( $object_id, $taxonomy . '_relationships' );
2411 * Fires immediately after an object-term relationship is deleted.
2414 * @since 4.7.0 Added the `$taxonomy` parameter.
2416 * @param int $object_id Object ID.
2417 * @param array $tt_ids An array of term taxonomy IDs.
2418 * @param string $taxonomy Taxonomy slug.
2420 do_action( 'deleted_term_relationships', $object_id, $tt_ids, $taxonomy );
2422 wp_update_term_count( $tt_ids, $taxonomy );
2424 return (bool) $deleted;
2431 * Will make slug unique, if it isn't already.
2433 * The `$slug` has to be unique global to every taxonomy, meaning that one
2434 * taxonomy term can't have a matching slug with another taxonomy term. Each
2435 * slug has to be globally unique for every taxonomy.
2437 * The way this works is that if the taxonomy that the term belongs to is
2438 * hierarchical and has a parent, it will append that parent to the $slug.
2440 * If that still doesn't return an unique slug, then it try to append a number
2441 * until it finds a number that is truly unique.
2443 * The only purpose for `$term` is for appending a parent, if one exists.
2447 * @global wpdb $wpdb WordPress database abstraction object.
2449 * @param string $slug The string that will be tried for a unique slug.
2450 * @param object $term The term object that the `$slug` will belong to.
2451 * @return string Will return a true unique slug.
2453 function wp_unique_term_slug( $slug, $term ) {
2456 $needs_suffix = true;
2457 $original_slug = $slug;
2459 // As of 4.1, duplicate slugs are allowed as long as they're in different taxonomies.
2460 if ( ! term_exists( $slug ) || get_option( 'db_version' ) >= 30133 && ! get_term_by( 'slug', $slug, $term->taxonomy ) ) {
2461 $needs_suffix = false;
2465 * If the taxonomy supports hierarchy and the term has a parent, make the slug unique
2466 * by incorporating parent slugs.
2468 $parent_suffix = '';
2469 if ( $needs_suffix && is_taxonomy_hierarchical( $term->taxonomy ) && ! empty( $term->parent ) ) {
2470 $the_parent = $term->parent;
2471 while ( ! empty($the_parent) ) {
2472 $parent_term = get_term($the_parent, $term->taxonomy);
2473 if ( is_wp_error($parent_term) || empty($parent_term) )
2475 $parent_suffix .= '-' . $parent_term->slug;
2476 if ( ! term_exists( $slug . $parent_suffix ) ) {
2480 if ( empty($parent_term->parent) )
2482 $the_parent = $parent_term->parent;
2486 // If we didn't get a unique slug, try appending a number to make it unique.
2489 * Filters whether the proposed unique term slug is bad.
2493 * @param bool $needs_suffix Whether the slug needs to be made unique with a suffix.
2494 * @param string $slug The slug.
2495 * @param object $term Term object.
2497 if ( apply_filters( 'wp_unique_term_slug_is_bad_slug', $needs_suffix, $slug, $term ) ) {
2498 if ( $parent_suffix ) {
2499 $slug .= $parent_suffix;
2501 if ( ! empty( $term->term_id ) )
2502 $query = $wpdb->prepare( "SELECT slug FROM $wpdb->terms WHERE slug = %s AND term_id != %d", $slug, $term->term_id );
2504 $query = $wpdb->prepare( "SELECT slug FROM $wpdb->terms WHERE slug = %s", $slug );
2506 if ( $wpdb->get_var( $query ) ) {
2509 $alt_slug = $slug . "-$num";
2511 $slug_check = $wpdb->get_var( $wpdb->prepare( "SELECT slug FROM $wpdb->terms WHERE slug = %s", $alt_slug ) );
2512 } while ( $slug_check );
2519 * Filters the unique term slug.
2523 * @param string $slug Unique term slug.
2524 * @param object $term Term object.
2525 * @param string $original_slug Slug originally passed to the function for testing.
2527 return apply_filters( 'wp_unique_term_slug', $slug, $term, $original_slug );
2531 * Update term based on arguments provided.
2533 * The $args will indiscriminately override all values with the same field name.
2534 * Care must be taken to not override important information need to update or
2535 * update will fail (or perhaps create a new term, neither would be acceptable).
2537 * Defaults will set 'alias_of', 'description', 'parent', and 'slug' if not
2538 * defined in $args already.
2540 * 'alias_of' will create a term group, if it doesn't already exist, and update
2543 * If the 'slug' argument in $args is missing, then the 'name' in $args will be
2544 * used. It should also be noted that if you set 'slug' and it isn't unique then
2545 * a WP_Error will be passed back. If you don't pass any slug, then a unique one
2546 * will be created for you.
2548 * For what can be overrode in `$args`, check the term scheme can contain and stay
2549 * away from the term keys.
2553 * @global wpdb $wpdb WordPress database abstraction object.
2555 * @param int $term_id The ID of the term
2556 * @param string $taxonomy The context in which to relate the term to the object.
2557 * @param array|string $args Optional. Array of get_terms() arguments. Default empty array.
2558 * @return array|WP_Error Returns Term ID and Taxonomy Term ID
2560 function wp_update_term( $term_id, $taxonomy, $args = array() ) {
2563 if ( ! taxonomy_exists( $taxonomy ) ) {
2564 return new WP_Error( 'invalid_taxonomy', __( 'Invalid taxonomy.' ) );
2567 $term_id = (int) $term_id;
2569 // First, get all of the original args
2570 $term = get_term( $term_id, $taxonomy );
2572 if ( is_wp_error( $term ) ) {
2577 return new WP_Error( 'invalid_term', __( 'Empty Term' ) );
2580 $term = (array) $term->data;
2582 // Escape data pulled from DB.
2583 $term = wp_slash( $term );
2585 // Merge old and new args with new args overwriting old ones.
2586 $args = array_merge($term, $args);
2588 $defaults = array( 'alias_of' => '', 'description' => '', 'parent' => 0, 'slug' => '');
2589 $args = wp_parse_args($args, $defaults);
2590 $args = sanitize_term($args, $taxonomy, 'db');
2591 $parsed_args = $args;
2593 // expected_slashed ($name)
2594 $name = wp_unslash( $args['name'] );
2595 $description = wp_unslash( $args['description'] );
2597 $parsed_args['name'] = $name;
2598 $parsed_args['description'] = $description;
2600 if ( '' == trim( $name ) ) {
2601 return new WP_Error( 'empty_term_name', __( 'A name is required for this term.' ) );
2604 if ( $parsed_args['parent'] > 0 && ! term_exists( (int) $parsed_args['parent'] ) ) {
2605 return new WP_Error( 'missing_parent', __( 'Parent term does not exist.' ) );
2608 $empty_slug = false;
2609 if ( empty( $args['slug'] ) ) {
2611 $slug = sanitize_title($name);
2613 $slug = $args['slug'];
2616 $parsed_args['slug'] = $slug;
2618 $term_group = isset( $parsed_args['term_group'] ) ? $parsed_args['term_group'] : 0;
2619 if ( $args['alias_of'] ) {
2620 $alias = get_term_by( 'slug', $args['alias_of'], $taxonomy );
2621 if ( ! empty( $alias->term_group ) ) {
2622 // The alias we want is already in a group, so let's use that one.
2623 $term_group = $alias->term_group;
2624 } elseif ( ! empty( $alias->term_id ) ) {
2626 * The alias is not in a group, so we create a new one
2627 * and add the alias to it.
2629 $term_group = $wpdb->get_var("SELECT MAX(term_group) FROM $wpdb->terms") + 1;
2631 wp_update_term( $alias->term_id, $taxonomy, array(
2632 'term_group' => $term_group,
2636 $parsed_args['term_group'] = $term_group;
2640 * Filters the term parent.
2642 * Hook to this filter to see if it will cause a hierarchy loop.
2646 * @param int $parent ID of the parent term.
2647 * @param int $term_id Term ID.
2648 * @param string $taxonomy Taxonomy slug.
2649 * @param array $parsed_args An array of potentially altered update arguments for the given term.
2650 * @param array $args An array of update arguments for the given term.
2652 $parent = apply_filters( 'wp_update_term_parent', $args['parent'], $term_id, $taxonomy, $parsed_args, $args );
2654 // Check for duplicate slug
2655 $duplicate = get_term_by( 'slug', $slug, $taxonomy );
2656 if ( $duplicate && $duplicate->term_id != $term_id ) {
2657 // If an empty slug was passed or the parent changed, reset the slug to something unique.
2659 if ( $empty_slug || ( $parent != $term['parent']) ) {
2660 $slug = wp_unique_term_slug($slug, (object) $args);
2662 /* translators: 1: Taxonomy term slug */
2663 return new WP_Error('duplicate_term_slug', sprintf(__('The slug “%s” is already in use by another term'), $slug));
2667 $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) );
2669 // Check whether this is a shared term that needs splitting.
2670 $_term_id = _split_shared_term( $term_id, $tt_id );
2671 if ( ! is_wp_error( $_term_id ) ) {
2672 $term_id = $_term_id;
2676 * Fires immediately before the given terms are edited.
2680 * @param int $term_id Term ID.
2681 * @param string $taxonomy Taxonomy slug.
2683 do_action( 'edit_terms', $term_id, $taxonomy );
2685 $data = compact( 'name', 'slug', 'term_group' );
2688 * Filters term data before it is updated in the database.
2692 * @param array $data Term data to be updated.
2693 * @param int $term_id Term ID.
2694 * @param string $taxonomy Taxonomy slug.
2695 * @param array $args Arguments passed to wp_update_term().
2697 $data = apply_filters( 'wp_update_term_data', $data, $term_id, $taxonomy, $args );
2699 $wpdb->update( $wpdb->terms, $data, compact( 'term_id' ) );
2700 if ( empty($slug) ) {
2701 $slug = sanitize_title($name, $term_id);
2702 $wpdb->update( $wpdb->terms, compact( 'slug' ), compact( 'term_id' ) );
2706 * Fires immediately after the given terms are edited.
2710 * @param int $term_id Term ID
2711 * @param string $taxonomy Taxonomy slug.
2713 do_action( 'edited_terms', $term_id, $taxonomy );
2716 * Fires immediate before a term-taxonomy relationship is updated.
2720 * @param int $tt_id Term taxonomy ID.
2721 * @param string $taxonomy Taxonomy slug.
2723 do_action( 'edit_term_taxonomy', $tt_id, $taxonomy );
2725 $wpdb->update( $wpdb->term_taxonomy, compact( 'term_id', 'taxonomy', 'description', 'parent' ), array( 'term_taxonomy_id' => $tt_id ) );
2728 * Fires immediately after a term-taxonomy relationship is updated.
2732 * @param int $tt_id Term taxonomy ID.
2733 * @param string $taxonomy Taxonomy slug.
2735 do_action( 'edited_term_taxonomy', $tt_id, $taxonomy );
2738 * Fires after a term has been updated, but before the term cache has been cleaned.
2742 * @param int $term_id Term ID.
2743 * @param int $tt_id Term taxonomy ID.
2744 * @param string $taxonomy Taxonomy slug.
2746 do_action( "edit_term", $term_id, $tt_id, $taxonomy );
2749 * Fires after a term in a specific taxonomy has been updated, but before the term
2750 * cache has been cleaned.
2752 * The dynamic portion of the hook name, `$taxonomy`, refers to the taxonomy slug.
2756 * @param int $term_id Term ID.
2757 * @param int $tt_id Term taxonomy ID.
2759 do_action( "edit_{$taxonomy}", $term_id, $tt_id );
2761 /** This filter is documented in wp-includes/taxonomy.php */
2762 $term_id = apply_filters( 'term_id_filter', $term_id, $tt_id );
2764 clean_term_cache($term_id, $taxonomy);
2767 * Fires after a term has been updated, and the term cache has been cleaned.
2771 * @param int $term_id Term ID.
2772 * @param int $tt_id Term taxonomy ID.
2773 * @param string $taxonomy Taxonomy slug.
2775 do_action( "edited_term", $term_id, $tt_id, $taxonomy );
2778 * Fires after a term for a specific taxonomy has been updated, and the term
2779 * cache has been cleaned.
2781 * The dynamic portion of the hook name, `$taxonomy`, refers to the taxonomy slug.
2785 * @param int $term_id Term ID.
2786 * @param int $tt_id Term taxonomy ID.
2788 do_action( "edited_{$taxonomy}", $term_id, $tt_id );
2790 return array('term_id' => $term_id, 'term_taxonomy_id' => $tt_id);
2794 * Enable or disable term counting.
2798 * @staticvar bool $_defer
2800 * @param bool $defer Optional. Enable if true, disable if false.
2801 * @return bool Whether term counting is enabled or disabled.
2803 function wp_defer_term_counting($defer=null) {
2804 static $_defer = false;
2806 if ( is_bool($defer) ) {
2808 // flush any deferred counts
2810 wp_update_term_count( null, null, true );
2817 * Updates the amount of terms in taxonomy.
2819 * If there is a taxonomy callback applied, then it will be called for updating
2822 * The default action is to count what the amount of terms have the relationship
2823 * of term ID. Once that is done, then update the database.
2827 * @staticvar array $_deferred
2829 * @param int|array $terms The term_taxonomy_id of the terms.
2830 * @param string $taxonomy The context of the term.
2831 * @param bool $do_deferred Whether to flush the deferred term counts too. Default false.
2832 * @return bool If no terms will return false, and if successful will return true.
2834 function wp_update_term_count( $terms, $taxonomy, $do_deferred = false ) {
2835 static $_deferred = array();
2837 if ( $do_deferred ) {
2838 foreach ( (array) array_keys($_deferred) as $tax ) {
2839 wp_update_term_count_now( $_deferred[$tax], $tax );
2840 unset( $_deferred[$tax] );
2844 if ( empty($terms) )
2847 if ( !is_array($terms) )
2848 $terms = array($terms);
2850 if ( wp_defer_term_counting() ) {
2851 if ( !isset($_deferred[$taxonomy]) )
2852 $_deferred[$taxonomy] = array();
2853 $_deferred[$taxonomy] = array_unique( array_merge($_deferred[$taxonomy], $terms) );
2857 return wp_update_term_count_now( $terms, $taxonomy );
2861 * Perform term count update immediately.
2865 * @param array $terms The term_taxonomy_id of terms to update.
2866 * @param string $taxonomy The context of the term.
2867 * @return true Always true when complete.
2869 function wp_update_term_count_now( $terms, $taxonomy ) {
2870 $terms = array_map('intval', $terms);
2872 $taxonomy = get_taxonomy($taxonomy);
2873 if ( !empty($taxonomy->update_count_callback) ) {
2874 call_user_func($taxonomy->update_count_callback, $terms, $taxonomy);
2876 $object_types = (array) $taxonomy->object_type;
2877 foreach ( $object_types as &$object_type ) {
2878 if ( 0 === strpos( $object_type, 'attachment:' ) )
2879 list( $object_type ) = explode( ':', $object_type );
2882 if ( $object_types == array_filter( $object_types, 'post_type_exists' ) ) {
2883 // Only post types are attached to this taxonomy
2884 _update_post_term_count( $terms, $taxonomy );
2886 // Default count updater
2887 _update_generic_term_count( $terms, $taxonomy );
2891 clean_term_cache($terms, '', false);
2901 * Removes the taxonomy relationship to terms from the cache.
2903 * Will remove the entire taxonomy relationship containing term `$object_id`. The
2904 * term IDs have to exist within the taxonomy `$object_type` for the deletion to
2909 * @global bool $_wp_suspend_cache_invalidation
2911 * @see get_object_taxonomies() for more on $object_type.
2913 * @param int|array $object_ids Single or list of term object ID(s).
2914 * @param array|string $object_type The taxonomy object type.
2916 function clean_object_term_cache($object_ids, $object_type) {
2917 global $_wp_suspend_cache_invalidation;
2919 if ( ! empty( $_wp_suspend_cache_invalidation ) ) {
2923 if ( !is_array($object_ids) )
2924 $object_ids = array($object_ids);
2926 $taxonomies = get_object_taxonomies( $object_type );
2928 foreach ( $object_ids as $id ) {
2929 foreach ( $taxonomies as $taxonomy ) {
2930 wp_cache_delete($id, "{$taxonomy}_relationships");
2935 * Fires after the object term cache has been cleaned.
2939 * @param array $object_ids An array of object IDs.
2940 * @param string $objet_type Object type.
2942 do_action( 'clean_object_term_cache', $object_ids, $object_type );
2946 * Will remove all of the term ids from the cache.
2950 * @global wpdb $wpdb WordPress database abstraction object.
2951 * @global bool $_wp_suspend_cache_invalidation
2953 * @param int|array $ids Single or list of Term IDs.
2954 * @param string $taxonomy Optional. Can be empty and will assume `tt_ids`, else will use for context.
2956 * @param bool $clean_taxonomy Optional. Whether to clean taxonomy wide caches (true), or just individual
2957 * term object caches (false). Default true.
2959 function clean_term_cache($ids, $taxonomy = '', $clean_taxonomy = true) {
2960 global $wpdb, $_wp_suspend_cache_invalidation;
2962 if ( ! empty( $_wp_suspend_cache_invalidation ) ) {
2966 if ( !is_array($ids) )
2969 $taxonomies = array();
2970 // If no taxonomy, assume tt_ids.
2971 if ( empty($taxonomy) ) {
2972 $tt_ids = array_map('intval', $ids);
2973 $tt_ids = implode(', ', $tt_ids);
2974 $terms = $wpdb->get_results("SELECT term_id, taxonomy FROM $wpdb->term_taxonomy WHERE term_taxonomy_id IN ($tt_ids)");
2976 foreach ( (array) $terms as $term ) {
2977 $taxonomies[] = $term->taxonomy;
2978 $ids[] = $term->term_id;
2979 wp_cache_delete( $term->term_id, 'terms' );
2981 $taxonomies = array_unique($taxonomies);
2983 $taxonomies = array($taxonomy);
2984 foreach ( $taxonomies as $taxonomy ) {
2985 foreach ( $ids as $id ) {
2986 wp_cache_delete( $id, 'terms' );
2991 foreach ( $taxonomies as $taxonomy ) {
2992 if ( $clean_taxonomy ) {
2993 wp_cache_delete('all_ids', $taxonomy);
2994 wp_cache_delete('get', $taxonomy);
2995 delete_option("{$taxonomy}_children");
2996 // Regenerate {$taxonomy}_children
2997 _get_term_hierarchy($taxonomy);
3001 * Fires once after each taxonomy's term cache has been cleaned.
3004 * @since 4.5.0 Added the `$clean_taxonomy` parameter.
3006 * @param array $ids An array of term IDs.
3007 * @param string $taxonomy Taxonomy slug.
3008 * @param bool $clean_taxonomy Whether or not to clean taxonomy-wide caches
3010 do_action( 'clean_term_cache', $ids, $taxonomy, $clean_taxonomy );
3013 wp_cache_set( 'last_changed', microtime(), 'terms' );
3017 * Retrieves the taxonomy relationship to the term object id.
3019 * Upstream functions (like get_the_terms() and is_object_in_term()) are
3020 * responsible for populating the object-term relationship cache. The current
3021 * function only fetches relationship data that is already in the cache.
3024 * @since 4.7.0 Returns a WP_Error object if get_term() returns an error for
3025 * any of the matched terms.
3027 * @param int $id Term object ID.
3028 * @param string $taxonomy Taxonomy name.
3029 * @return bool|array|WP_Error Array of `WP_Term` objects, if cached.
3030 * False if cache is empty for `$taxonomy` and `$id`.
3031 * WP_Error if get_term() returns an error object for any term.
3033 function get_object_term_cache( $id, $taxonomy ) {
3034 $_term_ids = wp_cache_get( $id, "{$taxonomy}_relationships" );
3036 // We leave the priming of relationship caches to upstream functions.
3037 if ( false === $_term_ids ) {
3041 // Backward compatibility for if a plugin is putting objects into the cache, rather than IDs.
3042 $term_ids = array();
3043 foreach ( $_term_ids as $term_id ) {
3044 if ( is_numeric( $term_id ) ) {
3045 $term_ids[] = intval( $term_id );
3046 } elseif ( isset( $term_id->term_id ) ) {
3047 $term_ids[] = intval( $term_id->term_id );
3051 // Fill the term objects.
3052 _prime_term_caches( $term_ids );
3055 foreach ( $term_ids as $term_id ) {
3056 $term = get_term( $term_id, $taxonomy );
3057 if ( is_wp_error( $term ) ) {
3068 * Updates the cache for the given term object ID(s).
3070 * Note: Due to performance concerns, great care should be taken to only update
3071 * term caches when necessary. Processing time can increase exponentially depending
3072 * on both the number of passed term IDs and the number of taxonomies those terms
3075 * Caches will only be updated for terms not already cached.
3079 * @param string|array $object_ids Comma-separated list or array of term object IDs.
3080 * @param array|string $object_type The taxonomy object type.
3081 * @return void|false False if all of the terms in `$object_ids` are already cached.
3083 function update_object_term_cache($object_ids, $object_type) {
3084 if ( empty($object_ids) )
3087 if ( !is_array($object_ids) )
3088 $object_ids = explode(',', $object_ids);
3090 $object_ids = array_map('intval', $object_ids);
3092 $taxonomies = get_object_taxonomies($object_type);
3095 foreach ( (array) $object_ids as $id ) {
3096 foreach ( $taxonomies as $taxonomy ) {
3097 if ( false === wp_cache_get($id, "{$taxonomy}_relationships") ) {
3104 if ( empty( $ids ) )
3107 $terms = wp_get_object_terms( $ids, $taxonomies, array(
3108 'fields' => 'all_with_object_id',
3109 'orderby' => 'name',
3110 'update_term_meta_cache' => false,
3113 $object_terms = array();
3114 foreach ( (array) $terms as $term ) {
3115 $object_terms[ $term->object_id ][ $term->taxonomy ][] = $term->term_id;
3118 foreach ( $ids as $id ) {
3119 foreach ( $taxonomies as $taxonomy ) {
3120 if ( ! isset($object_terms[$id][$taxonomy]) ) {
3121 if ( !isset($object_terms[$id]) )
3122 $object_terms[$id] = array();
3123 $object_terms[$id][$taxonomy] = array();
3128 foreach ( $object_terms as $id => $value ) {
3129 foreach ( $value as $taxonomy => $terms ) {
3130 wp_cache_add( $id, $terms, "{$taxonomy}_relationships" );
3136 * Updates Terms to Taxonomy in cache.
3140 * @param array $terms List of term objects to change.
3141 * @param string $taxonomy Optional. Update Term to this taxonomy in cache. Default empty.
3143 function update_term_cache( $terms, $taxonomy = '' ) {
3144 foreach ( (array) $terms as $term ) {
3145 // Create a copy in case the array was passed by reference.
3146 $_term = clone $term;
3148 // Object ID should not be cached.
3149 unset( $_term->object_id );
3151 wp_cache_add( $term->term_id, $_term, 'terms' );
3160 * Retrieves children of taxonomy as Term IDs.
3165 * @param string $taxonomy Taxonomy name.
3166 * @return array Empty if $taxonomy isn't hierarchical or returns children as Term IDs.
3168 function _get_term_hierarchy( $taxonomy ) {
3169 if ( !is_taxonomy_hierarchical($taxonomy) )
3171 $children = get_option("{$taxonomy}_children");
3173 if ( is_array($children) )
3175 $children = array();
3176 $terms = get_terms($taxonomy, array('get' => 'all', 'orderby' => 'id', 'fields' => 'id=>parent'));
3177 foreach ( $terms as $term_id => $parent ) {
3179 $children[$parent][] = $term_id;
3181 update_option("{$taxonomy}_children", $children);
3187 * Get the subset of $terms that are descendants of $term_id.
3189 * If `$terms` is an array of objects, then _get_term_children() returns an array of objects.
3190 * If `$terms` is an array of IDs, then _get_term_children() returns an array of IDs.
3195 * @param int $term_id The ancestor term: all returned terms should be descendants of `$term_id`.
3196 * @param array $terms The set of terms - either an array of term objects or term IDs - from which those that
3197 * are descendants of $term_id will be chosen.
3198 * @param string $taxonomy The taxonomy which determines the hierarchy of the terms.
3199 * @param array $ancestors Optional. Term ancestors that have already been identified. Passed by reference, to keep
3200 * track of found terms when recursing the hierarchy. The array of located ancestors is used
3201 * to prevent infinite recursion loops. For performance, `term_ids` are used as array keys,
3202 * with 1 as value. Default empty array.
3203 * @return array|WP_Error The subset of $terms that are descendants of $term_id.
3205 function _get_term_children( $term_id, $terms, $taxonomy, &$ancestors = array() ) {
3206 $empty_array = array();
3207 if ( empty($terms) )
3208 return $empty_array;
3210 $term_list = array();
3211 $has_children = _get_term_hierarchy($taxonomy);
3213 if ( ( 0 != $term_id ) && ! isset($has_children[$term_id]) )
3214 return $empty_array;
3216 // Include the term itself in the ancestors array, so we can properly detect when a loop has occurred.
3217 if ( empty( $ancestors ) ) {
3218 $ancestors[ $term_id ] = 1;
3221 foreach ( (array) $terms as $term ) {
3223 if ( !is_object($term) ) {
3224 $term = get_term($term, $taxonomy);
3225 if ( is_wp_error( $term ) )
3230 // Don't recurse if we've already identified the term as a child - this indicates a loop.
3231 if ( isset( $ancestors[ $term->term_id ] ) ) {
3235 if ( $term->parent == $term_id ) {
3237 $term_list[] = $term->term_id;
3239 $term_list[] = $term;
3241 if ( !isset($has_children[$term->term_id]) )
3244 $ancestors[ $term->term_id ] = 1;
3246 if ( $children = _get_term_children( $term->term_id, $terms, $taxonomy, $ancestors) )
3247 $term_list = array_merge($term_list, $children);
3255 * Add count of children to parent count.
3257 * Recalculates term counts by including items from child terms. Assumes all
3258 * relevant children are already in the $terms argument.
3263 * @global wpdb $wpdb WordPress database abstraction object.
3265 * @param array $terms List of term objects, passed by reference.
3266 * @param string $taxonomy Term context.
3268 function _pad_term_counts( &$terms, $taxonomy ) {
3271 // This function only works for hierarchical taxonomies like post categories.
3272 if ( !is_taxonomy_hierarchical( $taxonomy ) )
3275 $term_hier = _get_term_hierarchy($taxonomy);
3277 if ( empty($term_hier) )
3280 $term_items = array();
3281 $terms_by_id = array();
3282 $term_ids = array();
3284 foreach ( (array) $terms as $key => $term ) {
3285 $terms_by_id[$term->term_id] = & $terms[$key];
3286 $term_ids[$term->term_taxonomy_id] = $term->term_id;
3289 // Get the object and term ids and stick them in a lookup table.
3290 $tax_obj = get_taxonomy($taxonomy);
3291 $object_types = esc_sql($tax_obj->object_type);
3292 $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'");
3293 foreach ( $results as $row ) {
3294 $id = $term_ids[$row->term_taxonomy_id];
3295 $term_items[$id][$row->object_id] = isset($term_items[$id][$row->object_id]) ? ++$term_items[$id][$row->object_id] : 1;
3298 // Touch every ancestor's lookup row for each post in each term.
3299 foreach ( $term_ids as $term_id ) {
3301 $ancestors = array();
3302 while ( !empty( $terms_by_id[$child] ) && $parent = $terms_by_id[$child]->parent ) {
3303 $ancestors[] = $child;
3304 if ( !empty( $term_items[$term_id] ) )
3305 foreach ( $term_items[$term_id] as $item_id => $touches ) {
3306 $term_items[$parent][$item_id] = isset($term_items[$parent][$item_id]) ? ++$term_items[$parent][$item_id]: 1;
3310 if ( in_array( $parent, $ancestors ) ) {
3316 // Transfer the touched cells.
3317 foreach ( (array) $term_items as $id => $items )
3318 if ( isset($terms_by_id[$id]) )
3319 $terms_by_id[$id]->count = count($items);
3323 * Adds any terms from the given IDs to the cache that do not already exist in cache.
3328 * @global wpdb $wpdb WordPress database abstraction object.
3330 * @param array $term_ids Array of term IDs.
3331 * @param bool $update_meta_cache Optional. Whether to update the meta cache. Default true.
3333 function _prime_term_caches( $term_ids, $update_meta_cache = true ) {
3336 $non_cached_ids = _get_non_cached_ids( $term_ids, 'terms' );
3337 if ( ! empty( $non_cached_ids ) ) {
3338 $fresh_terms = $wpdb->get_results( sprintf( "SELECT t.*, tt.* FROM $wpdb->terms AS t INNER JOIN $wpdb->term_taxonomy AS tt ON t.term_id = tt.term_id WHERE t.term_id IN (%s)", join( ",", array_map( 'intval', $non_cached_ids ) ) ) );
3340 update_term_cache( $fresh_terms, $update_meta_cache );
3342 if ( $update_meta_cache ) {
3343 update_termmeta_cache( $non_cached_ids );
3349 // Default callbacks
3353 * Will update term count based on object types of the current taxonomy.
3355 * Private function for the default callback for post_tag and category
3361 * @global wpdb $wpdb WordPress database abstraction object.
3363 * @param array $terms List of Term taxonomy IDs.
3364 * @param object $taxonomy Current taxonomy object of terms.
3366 function _update_post_term_count( $terms, $taxonomy ) {
3369 $object_types = (array) $taxonomy->object_type;
3371 foreach ( $object_types as &$object_type )
3372 list( $object_type ) = explode( ':', $object_type );
3374 $object_types = array_unique( $object_types );
3376 if ( false !== ( $check_attachments = array_search( 'attachment', $object_types ) ) ) {
3377 unset( $object_types[ $check_attachments ] );
3378 $check_attachments = true;
3381 if ( $object_types )
3382 $object_types = esc_sql( array_filter( $object_types, 'post_type_exists' ) );
3384 foreach ( (array) $terms as $term ) {
3387 // Attachments can be 'inherit' status, we need to base count off the parent's status if so.
3388 if ( $check_attachments )
3389 $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 ) );
3391 if ( $object_types )
3392 $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 ) );
3394 /** This action is documented in wp-includes/taxonomy.php */
3395 do_action( 'edit_term_taxonomy', $term, $taxonomy->name );
3396 $wpdb->update( $wpdb->term_taxonomy, compact( 'count' ), array( 'term_taxonomy_id' => $term ) );
3398 /** This action is documented in wp-includes/taxonomy.php */
3399 do_action( 'edited_term_taxonomy', $term, $taxonomy->name );
3404 * Will update term count based on number of objects.
3406 * Default callback for the 'link_category' taxonomy.
3410 * @global wpdb $wpdb WordPress database abstraction object.
3412 * @param array $terms List of term taxonomy IDs.
3413 * @param object $taxonomy Current taxonomy object of terms.
3415 function _update_generic_term_count( $terms, $taxonomy ) {
3418 foreach ( (array) $terms as $term ) {
3419 $count = $wpdb->get_var( $wpdb->prepare( "SELECT COUNT(*) FROM $wpdb->term_relationships WHERE term_taxonomy_id = %d", $term ) );
3421 /** This action is documented in wp-includes/taxonomy.php */
3422 do_action( 'edit_term_taxonomy', $term, $taxonomy->name );
3423 $wpdb->update( $wpdb->term_taxonomy, compact( 'count' ), array( 'term_taxonomy_id' => $term ) );
3425 /** This action is documented in wp-includes/taxonomy.php */
3426 do_action( 'edited_term_taxonomy', $term, $taxonomy->name );
3431 * Create a new term for a term_taxonomy item that currently shares its term
3432 * with another term_taxonomy.
3436 * @since 4.3.0 Introduced `$record` parameter. Also, `$term_id` and
3437 * `$term_taxonomy_id` can now accept objects.
3439 * @global wpdb $wpdb WordPress database abstraction object.
3441 * @param int|object $term_id ID of the shared term, or the shared term object.
3442 * @param int|object $term_taxonomy_id ID of the term_taxonomy item to receive a new term, or the term_taxonomy object
3443 * (corresponding to a row from the term_taxonomy table).
3444 * @param bool $record Whether to record data about the split term in the options table. The recording
3445 * process has the potential to be resource-intensive, so during batch operations
3446 * it can be beneficial to skip inline recording and do it just once, after the
3447 * batch is processed. Only set this to `false` if you know what you are doing.
3449 * @return int|WP_Error When the current term does not need to be split (or cannot be split on the current
3450 * database schema), `$term_id` is returned. When the term is successfully split, the
3451 * new term_id is returned. A WP_Error is returned for miscellaneous errors.
3453 function _split_shared_term( $term_id, $term_taxonomy_id, $record = true ) {
3456 if ( is_object( $term_id ) ) {
3457 $shared_term = $term_id;
3458 $term_id = intval( $shared_term->term_id );
3461 if ( is_object( $term_taxonomy_id ) ) {
3462 $term_taxonomy = $term_taxonomy_id;
3463 $term_taxonomy_id = intval( $term_taxonomy->term_taxonomy_id );
3466 // If there are no shared term_taxonomy rows, there's nothing to do here.
3467 $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 ) );
3469 if ( ! $shared_tt_count ) {
3474 * Verify that the term_taxonomy_id passed to the function is actually associated with the term_id.
3475 * If there's a mismatch, it may mean that the term is already split. Return the actual term_id from the db.
3477 $check_term_id = $wpdb->get_var( $wpdb->prepare( "SELECT term_id FROM $wpdb->term_taxonomy WHERE term_taxonomy_id = %d", $term_taxonomy_id ) );
3478 if ( $check_term_id != $term_id ) {
3479 return $check_term_id;
3482 // Pull up data about the currently shared slug, which we'll use to populate the new one.
3483 if ( empty( $shared_term ) ) {
3484 $shared_term = $wpdb->get_row( $wpdb->prepare( "SELECT t.* FROM $wpdb->terms t WHERE t.term_id = %d", $term_id ) );
3487 $new_term_data = array(
3488 'name' => $shared_term->name,
3489 'slug' => $shared_term->slug,
3490 'term_group' => $shared_term->term_group,
3493 if ( false === $wpdb->insert( $wpdb->terms, $new_term_data ) ) {
3494 return new WP_Error( 'db_insert_error', __( 'Could not split shared term.' ), $wpdb->last_error );
3497 $new_term_id = (int) $wpdb->insert_id;
3499 // Update the existing term_taxonomy to point to the newly created term.
3500 $wpdb->update( $wpdb->term_taxonomy,
3501 array( 'term_id' => $new_term_id ),
3502 array( 'term_taxonomy_id' => $term_taxonomy_id )
3505 // Reassign child terms to the new parent.
3506 if ( empty( $term_taxonomy ) ) {
3507 $term_taxonomy = $wpdb->get_row( $wpdb->prepare( "SELECT * FROM $wpdb->term_taxonomy WHERE term_taxonomy_id = %d", $term_taxonomy_id ) );
3510 $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 ) );
3511 if ( ! empty( $children_tt_ids ) ) {
3512 foreach ( $children_tt_ids as $child_tt_id ) {
3513 $wpdb->update( $wpdb->term_taxonomy,
3514 array( 'parent' => $new_term_id ),
3515 array( 'term_taxonomy_id' => $child_tt_id )
3517 clean_term_cache( $term_id, $term_taxonomy->taxonomy );
3520 // If the term has no children, we must force its taxonomy cache to be rebuilt separately.
3521 clean_term_cache( $new_term_id, $term_taxonomy->taxonomy );
3524 // Clean the cache for term taxonomies formerly shared with the current term.
3525 $shared_term_taxonomies = $wpdb->get_row( $wpdb->prepare( "SELECT taxonomy FROM $wpdb->term_taxonomy WHERE term_id = %d", $term_id ) );
3526 if ( $shared_term_taxonomies ) {
3527 foreach ( $shared_term_taxonomies as $shared_term_taxonomy ) {
3528 clean_term_cache( $term_id, $shared_term_taxonomy );
3532 // Keep a record of term_ids that have been split, keyed by old term_id. See wp_get_split_term().
3534 $split_term_data = get_option( '_split_terms', array() );
3535 if ( ! isset( $split_term_data[ $term_id ] ) ) {
3536 $split_term_data[ $term_id ] = array();
3539 $split_term_data[ $term_id ][ $term_taxonomy->taxonomy ] = $new_term_id;
3540 update_option( '_split_terms', $split_term_data );
3543 // If we've just split the final shared term, set the "finished" flag.
3544 $shared_terms_exist = $wpdb->get_results(
3545 "SELECT tt.term_id, t.*, count(*) as term_tt_count FROM {$wpdb->term_taxonomy} tt
3546 LEFT JOIN {$wpdb->terms} t ON t.term_id = tt.term_id
3548 HAVING term_tt_count > 1
3551 if ( ! $shared_terms_exist ) {
3552 update_option( 'finished_splitting_shared_terms', true );
3556 * Fires after a previously shared taxonomy term is split into two separate terms.
3560 * @param int $term_id ID of the formerly shared term.
3561 * @param int $new_term_id ID of the new term created for the $term_taxonomy_id.
3562 * @param int $term_taxonomy_id ID for the term_taxonomy row affected by the split.
3563 * @param string $taxonomy Taxonomy for the split term.
3565 do_action( 'split_shared_term', $term_id, $new_term_id, $term_taxonomy_id, $term_taxonomy->taxonomy );
3567 return $new_term_id;
3571 * Splits a batch of shared taxonomy terms.
3575 * @global wpdb $wpdb WordPress database abstraction object.
3577 function _wp_batch_split_terms() {
3580 $lock_name = 'term_split.lock';
3583 $lock_result = $wpdb->query( $wpdb->prepare( "INSERT IGNORE INTO `$wpdb->options` ( `option_name`, `option_value`, `autoload` ) VALUES (%s, %s, 'no') /* LOCK */", $lock_name, time() ) );
3585 if ( ! $lock_result ) {
3586 $lock_result = get_option( $lock_name );
3588 // Bail if we were unable to create a lock, or if the existing lock is still valid.
3589 if ( ! $lock_result || ( $lock_result > ( time() - HOUR_IN_SECONDS ) ) ) {
3590 wp_schedule_single_event( time() + ( 5 * MINUTE_IN_SECONDS ), 'wp_split_shared_term_batch' );
3595 // Update the lock, as by this point we've definitely got a lock, just need to fire the actions.
3596 update_option( $lock_name, time() );
3598 // Get a list of shared terms (those with more than one associated row in term_taxonomy).
3599 $shared_terms = $wpdb->get_results(
3600 "SELECT tt.term_id, t.*, count(*) as term_tt_count FROM {$wpdb->term_taxonomy} tt
3601 LEFT JOIN {$wpdb->terms} t ON t.term_id = tt.term_id
3603 HAVING term_tt_count > 1
3607 // No more terms, we're done here.
3608 if ( ! $shared_terms ) {
3609 update_option( 'finished_splitting_shared_terms', true );
3610 delete_option( $lock_name );
3614 // Shared terms found? We'll need to run this script again.
3615 wp_schedule_single_event( time() + ( 2 * MINUTE_IN_SECONDS ), 'wp_split_shared_term_batch' );
3617 // Rekey shared term array for faster lookups.
3618 $_shared_terms = array();
3619 foreach ( $shared_terms as $shared_term ) {
3620 $term_id = intval( $shared_term->term_id );
3621 $_shared_terms[ $term_id ] = $shared_term;
3623 $shared_terms = $_shared_terms;
3625 // Get term taxonomy data for all shared terms.
3626 $shared_term_ids = implode( ',', array_keys( $shared_terms ) );
3627 $shared_tts = $wpdb->get_results( "SELECT * FROM {$wpdb->term_taxonomy} WHERE `term_id` IN ({$shared_term_ids})" );
3629 // Split term data recording is slow, so we do it just once, outside the loop.
3630 $split_term_data = get_option( '_split_terms', array() );
3631 $skipped_first_term = $taxonomies = array();
3632 foreach ( $shared_tts as $shared_tt ) {
3633 $term_id = intval( $shared_tt->term_id );
3635 // Don't split the first tt belonging to a given term_id.
3636 if ( ! isset( $skipped_first_term[ $term_id ] ) ) {
3637 $skipped_first_term[ $term_id ] = 1;
3641 if ( ! isset( $split_term_data[ $term_id ] ) ) {
3642 $split_term_data[ $term_id ] = array();
3645 // Keep track of taxonomies whose hierarchies need flushing.
3646 if ( ! isset( $taxonomies[ $shared_tt->taxonomy ] ) ) {
3647 $taxonomies[ $shared_tt->taxonomy ] = 1;
3651 $split_term_data[ $term_id ][ $shared_tt->taxonomy ] = _split_shared_term( $shared_terms[ $term_id ], $shared_tt, false );
3654 // Rebuild the cached hierarchy for each affected taxonomy.
3655 foreach ( array_keys( $taxonomies ) as $tax ) {
3656 delete_option( "{$tax}_children" );
3657 _get_term_hierarchy( $tax );
3660 update_option( '_split_terms', $split_term_data );
3662 delete_option( $lock_name );
3666 * In order to avoid the _wp_batch_split_terms() job being accidentally removed,
3667 * check that it's still scheduled while we haven't finished splitting terms.
3672 function _wp_check_for_scheduled_split_terms() {
3673 if ( ! get_option( 'finished_splitting_shared_terms' ) && ! wp_next_scheduled( 'wp_split_shared_term_batch' ) ) {
3674 wp_schedule_single_event( time() + MINUTE_IN_SECONDS, 'wp_split_shared_term_batch' );
3679 * Check default categories when a term gets split to see if any of them need to be updated.
3684 * @param int $term_id ID of the formerly shared term.
3685 * @param int $new_term_id ID of the new term created for the $term_taxonomy_id.
3686 * @param int $term_taxonomy_id ID for the term_taxonomy row affected by the split.
3687 * @param string $taxonomy Taxonomy for the split term.
3689 function _wp_check_split_default_terms( $term_id, $new_term_id, $term_taxonomy_id, $taxonomy ) {
3690 if ( 'category' != $taxonomy ) {
3694 foreach ( array( 'default_category', 'default_link_category', 'default_email_category' ) as $option ) {
3695 if ( $term_id == get_option( $option, -1 ) ) {
3696 update_option( $option, $new_term_id );
3702 * Check menu items when a term gets split to see if any of them need to be updated.
3707 * @global wpdb $wpdb WordPress database abstraction object.
3709 * @param int $term_id ID of the formerly shared term.
3710 * @param int $new_term_id ID of the new term created for the $term_taxonomy_id.
3711 * @param int $term_taxonomy_id ID for the term_taxonomy row affected by the split.
3712 * @param string $taxonomy Taxonomy for the split term.
3714 function _wp_check_split_terms_in_menus( $term_id, $new_term_id, $term_taxonomy_id, $taxonomy ) {
3716 $post_ids = $wpdb->get_col( $wpdb->prepare(
3718 FROM {$wpdb->postmeta} AS m1
3719 INNER JOIN {$wpdb->postmeta} AS m2 ON ( m2.post_id = m1.post_id )
3720 INNER JOIN {$wpdb->postmeta} AS m3 ON ( m3.post_id = m1.post_id )
3721 WHERE ( m1.meta_key = '_menu_item_type' AND m1.meta_value = 'taxonomy' )
3722 AND ( m2.meta_key = '_menu_item_object' AND m2.meta_value = '%s' )
3723 AND ( m3.meta_key = '_menu_item_object_id' AND m3.meta_value = %d )",
3729 foreach ( $post_ids as $post_id ) {
3730 update_post_meta( $post_id, '_menu_item_object_id', $new_term_id, $term_id );
3736 * If the term being split is a nav_menu, change associations.
3741 * @param int $term_id ID of the formerly shared term.
3742 * @param int $new_term_id ID of the new term created for the $term_taxonomy_id.
3743 * @param int $term_taxonomy_id ID for the term_taxonomy row affected by the split.
3744 * @param string $taxonomy Taxonomy for the split term.
3746 function _wp_check_split_nav_menu_terms( $term_id, $new_term_id, $term_taxonomy_id, $taxonomy ) {
3747 if ( 'nav_menu' !== $taxonomy ) {
3751 // Update menu locations.
3752 $locations = get_nav_menu_locations();
3753 foreach ( $locations as $location => $menu_id ) {
3754 if ( $term_id == $menu_id ) {
3755 $locations[ $location ] = $new_term_id;
3758 set_theme_mod( 'nav_menu_locations', $locations );
3762 * Get data about terms that previously shared a single term_id, but have since been split.
3766 * @param int $old_term_id Term ID. This is the old, pre-split term ID.
3767 * @return array Array of new term IDs, keyed by taxonomy.
3769 function wp_get_split_terms( $old_term_id ) {
3770 $split_terms = get_option( '_split_terms', array() );
3773 if ( isset( $split_terms[ $old_term_id ] ) ) {
3774 $terms = $split_terms[ $old_term_id ];
3781 * Get the new term ID corresponding to a previously split term.
3785 * @param int $old_term_id Term ID. This is the old, pre-split term ID.
3786 * @param string $taxonomy Taxonomy that the term belongs to.
3787 * @return int|false If a previously split term is found corresponding to the old term_id and taxonomy,
3788 * the new term_id will be returned. If no previously split term is found matching
3789 * the parameters, returns false.
3791 function wp_get_split_term( $old_term_id, $taxonomy ) {
3792 $split_terms = wp_get_split_terms( $old_term_id );
3795 if ( isset( $split_terms[ $taxonomy ] ) ) {
3796 $term_id = (int) $split_terms[ $taxonomy ];
3803 * Determine whether a term is shared between multiple taxonomies.
3805 * Shared taxonomy terms began to be split in 4.3, but failed cron tasks or other delays in upgrade routines may cause
3806 * shared terms to remain.
3810 * @param int $term_id
3813 function wp_term_is_shared( $term_id ) {
3816 if ( get_option( 'finished_splitting_shared_terms' ) ) {
3820 $tt_count = $wpdb->get_var( $wpdb->prepare( "SELECT COUNT(*) FROM $wpdb->term_taxonomy WHERE term_id = %d", $term_id ) );
3822 return $tt_count > 1;
3826 * Generate a permalink for a taxonomy term archive.
3830 * @global WP_Rewrite $wp_rewrite
3832 * @param object|int|string $term The term object, ID, or slug whose link will be retrieved.
3833 * @param string $taxonomy Optional. Taxonomy. Default empty.
3834 * @return string|WP_Error HTML link to taxonomy term archive on success, WP_Error if term does not exist.
3836 function get_term_link( $term, $taxonomy = '' ) {
3839 if ( !is_object($term) ) {
3840 if ( is_int( $term ) ) {
3841 $term = get_term( $term, $taxonomy );
3843 $term = get_term_by( 'slug', $term, $taxonomy );
3847 if ( !is_object($term) )
3848 $term = new WP_Error('invalid_term', __('Empty Term'));
3850 if ( is_wp_error( $term ) )
3853 $taxonomy = $term->taxonomy;
3855 $termlink = $wp_rewrite->get_extra_permastruct($taxonomy);
3857 $slug = $term->slug;
3858 $t = get_taxonomy($taxonomy);
3860 if ( empty($termlink) ) {
3861 if ( 'category' == $taxonomy )
3862 $termlink = '?cat=' . $term->term_id;
3863 elseif ( $t->query_var )
3864 $termlink = "?$t->query_var=$slug";
3866 $termlink = "?taxonomy=$taxonomy&term=$slug";
3867 $termlink = home_url($termlink);
3869 if ( $t->rewrite['hierarchical'] ) {
3870 $hierarchical_slugs = array();
3871 $ancestors = get_ancestors( $term->term_id, $taxonomy, 'taxonomy' );
3872 foreach ( (array)$ancestors as $ancestor ) {
3873 $ancestor_term = get_term($ancestor, $taxonomy);
3874 $hierarchical_slugs[] = $ancestor_term->slug;
3876 $hierarchical_slugs = array_reverse($hierarchical_slugs);
3877 $hierarchical_slugs[] = $slug;
3878 $termlink = str_replace("%$taxonomy%", implode('/', $hierarchical_slugs), $termlink);
3880 $termlink = str_replace("%$taxonomy%", $slug, $termlink);
3882 $termlink = home_url( user_trailingslashit($termlink, 'category') );
3884 // Back Compat filters.
3885 if ( 'post_tag' == $taxonomy ) {
3888 * Filters the tag link.
3891 * @deprecated 2.5.0 Use 'term_link' instead.
3893 * @param string $termlink Tag link URL.
3894 * @param int $term_id Term ID.
3896 $termlink = apply_filters( 'tag_link', $termlink, $term->term_id );
3897 } elseif ( 'category' == $taxonomy ) {
3900 * Filters the category link.
3903 * @deprecated 2.5.0 Use 'term_link' instead.
3905 * @param string $termlink Category link URL.
3906 * @param int $term_id Term ID.
3908 $termlink = apply_filters( 'category_link', $termlink, $term->term_id );
3912 * Filters the term link.
3916 * @param string $termlink Term link URL.
3917 * @param object $term Term object.
3918 * @param string $taxonomy Taxonomy slug.
3920 return apply_filters( 'term_link', $termlink, $term, $taxonomy );
3924 * Display the taxonomies of a post with available options.
3926 * This function can be used within the loop to display the taxonomies for a
3927 * post without specifying the Post ID. You can also use it outside the Loop to
3928 * display the taxonomies for a specific post.
3932 * @param array $args {
3933 * Arguments about which post to use and how to format the output. Shares all of the arguments
3934 * supported by get_the_taxonomies(), in addition to the following.
3936 * @type int|WP_Post $post Post ID or object to get taxonomies of. Default current post.
3937 * @type string $before Displays before the taxonomies. Default empty string.
3938 * @type string $sep Separates each taxonomy. Default is a space.
3939 * @type string $after Displays after the taxonomies. Default empty string.
3942 function the_taxonomies( $args = array() ) {
3950 $r = wp_parse_args( $args, $defaults );
3952 echo $r['before'] . join( $r['sep'], get_the_taxonomies( $r['post'], $r ) ) . $r['after'];
3956 * Retrieve all taxonomies associated with a post.
3958 * This function can be used within the loop. It will also return an array of
3959 * the taxonomies with links to the taxonomy and name.
3963 * @param int|WP_Post $post Optional. Post ID or WP_Post object. Default is global $post.
3964 * @param array $args {
3965 * Optional. Arguments about how to format the list of taxonomies. Default empty array.
3967 * @type string $template Template for displaying a taxonomy label and list of terms.
3968 * Default is "Label: Terms."
3969 * @type string $term_template Template for displaying a single term in the list. Default is the term name
3970 * linked to its archive.
3972 * @return array List of taxonomies.
3974 function get_the_taxonomies( $post = 0, $args = array() ) {
3975 $post = get_post( $post );
3977 $args = wp_parse_args( $args, array(
3978 /* translators: %s: taxonomy label, %l: list of terms formatted as per $term_template */
3979 'template' => __( '%s: %l.' ),
3980 'term_template' => '<a href="%1$s">%2$s</a>',
3983 $taxonomies = array();
3989 foreach ( get_object_taxonomies( $post ) as $taxonomy ) {
3990 $t = (array) get_taxonomy( $taxonomy );
3991 if ( empty( $t['label'] ) ) {
3992 $t['label'] = $taxonomy;
3994 if ( empty( $t['args'] ) ) {
3995 $t['args'] = array();
3997 if ( empty( $t['template'] ) ) {
3998 $t['template'] = $args['template'];
4000 if ( empty( $t['term_template'] ) ) {
4001 $t['term_template'] = $args['term_template'];
4004 $terms = get_object_term_cache( $post->ID, $taxonomy );
4005 if ( false === $terms ) {
4006 $terms = wp_get_object_terms( $post->ID, $taxonomy, $t['args'] );
4010 foreach ( $terms as $term ) {
4011 $links[] = wp_sprintf( $t['term_template'], esc_attr( get_term_link( $term ) ), $term->name );
4014 $taxonomies[$taxonomy] = wp_sprintf( $t['template'], $t['label'], $links, $terms );
4021 * Retrieve all taxonomies of a post with just the names.
4025 * @param int|WP_Post $post Optional. Post ID or WP_Post object. Default is global $post.
4028 function get_post_taxonomies( $post = 0 ) {
4029 $post = get_post( $post );
4031 return get_object_taxonomies($post);
4035 * Determine if the given object is associated with any of the given terms.
4037 * The given terms are checked against the object's terms' term_ids, names and slugs.
4038 * Terms given as integers will only be checked against the object's terms' term_ids.
4039 * If no terms are given, determines if object is associated with any terms in the given taxonomy.
4043 * @param int $object_id ID of the object (post ID, link ID, ...).
4044 * @param string $taxonomy Single taxonomy name.
4045 * @param int|string|array $terms Optional. Term term_id, name, slug or array of said. Default null.
4046 * @return bool|WP_Error WP_Error on input error.
4048 function is_object_in_term( $object_id, $taxonomy, $terms = null ) {
4049 if ( !$object_id = (int) $object_id )
4050 return new WP_Error( 'invalid_object', __( 'Invalid object ID' ) );
4052 $object_terms = get_object_term_cache( $object_id, $taxonomy );
4053 if ( false === $object_terms ) {
4054 $object_terms = wp_get_object_terms( $object_id, $taxonomy, array( 'update_term_meta_cache' => false ) );
4055 if ( is_wp_error( $object_terms ) ) {
4056 return $object_terms;
4059 wp_cache_set( $object_id, wp_list_pluck( $object_terms, 'term_id' ), "{$taxonomy}_relationships" );
4062 if ( is_wp_error( $object_terms ) )
4063 return $object_terms;
4064 if ( empty( $object_terms ) )
4066 if ( empty( $terms ) )
4067 return ( !empty( $object_terms ) );
4069 $terms = (array) $terms;
4071 if ( $ints = array_filter( $terms, 'is_int' ) )
4072 $strs = array_diff( $terms, $ints );
4076 foreach ( $object_terms as $object_term ) {
4077 // If term is an int, check against term_ids only.
4078 if ( $ints && in_array( $object_term->term_id, $ints ) ) {
4083 // Only check numeric strings against term_id, to avoid false matches due to type juggling.
4084 $numeric_strs = array_map( 'intval', array_filter( $strs, 'is_numeric' ) );
4085 if ( in_array( $object_term->term_id, $numeric_strs, true ) ) {
4089 if ( in_array( $object_term->name, $strs ) ) return true;
4090 if ( in_array( $object_term->slug, $strs ) ) return true;
4098 * Determine if the given object type is associated with the given taxonomy.
4102 * @param string $object_type Object type string.
4103 * @param string $taxonomy Single taxonomy name.
4104 * @return bool True if object is associated with the taxonomy, otherwise false.
4106 function is_object_in_taxonomy( $object_type, $taxonomy ) {
4107 $taxonomies = get_object_taxonomies( $object_type );
4108 if ( empty( $taxonomies ) ) {
4111 return in_array( $taxonomy, $taxonomies );
4115 * Get an array of ancestor IDs for a given object.
4118 * @since 4.1.0 Introduced the `$resource_type` argument.
4120 * @param int $object_id Optional. The ID of the object. Default 0.
4121 * @param string $object_type Optional. The type of object for which we'll be retrieving
4122 * ancestors. Accepts a post type or a taxonomy name. Default empty.
4123 * @param string $resource_type Optional. Type of resource $object_type is. Accepts 'post_type'
4124 * or 'taxonomy'. Default empty.
4125 * @return array An array of ancestors from lowest to highest in the hierarchy.
4127 function get_ancestors( $object_id = 0, $object_type = '', $resource_type = '' ) {
4128 $object_id = (int) $object_id;
4130 $ancestors = array();
4132 if ( empty( $object_id ) ) {
4134 /** This filter is documented in wp-includes/taxonomy.php */
4135 return apply_filters( 'get_ancestors', $ancestors, $object_id, $object_type, $resource_type );
4138 if ( ! $resource_type ) {
4139 if ( is_taxonomy_hierarchical( $object_type ) ) {
4140 $resource_type = 'taxonomy';
4141 } elseif ( post_type_exists( $object_type ) ) {
4142 $resource_type = 'post_type';
4146 if ( 'taxonomy' === $resource_type ) {
4147 $term = get_term($object_id, $object_type);
4148 while ( ! is_wp_error($term) && ! empty( $term->parent ) && ! in_array( $term->parent, $ancestors ) ) {
4149 $ancestors[] = (int) $term->parent;
4150 $term = get_term($term->parent, $object_type);
4152 } elseif ( 'post_type' === $resource_type ) {
4153 $ancestors = get_post_ancestors($object_id);
4157 * Filters a given object's ancestors.
4160 * @since 4.1.1 Introduced the `$resource_type` parameter.
4162 * @param array $ancestors An array of object ancestors.
4163 * @param int $object_id Object ID.
4164 * @param string $object_type Type of object.
4165 * @param string $resource_type Type of resource $object_type is.
4167 return apply_filters( 'get_ancestors', $ancestors, $object_id, $object_type, $resource_type );
4171 * Returns the term's parent's term_ID.
4175 * @param int $term_id Term ID.
4176 * @param string $taxonomy Taxonomy name.
4177 * @return int|false False on error.
4179 function wp_get_term_taxonomy_parent_id( $term_id, $taxonomy ) {
4180 $term = get_term( $term_id, $taxonomy );
4181 if ( ! $term || is_wp_error( $term ) ) {
4184 return (int) $term->parent;
4188 * Checks the given subset of the term hierarchy for hierarchy loops.
4189 * Prevents loops from forming and breaks those that it finds.
4191 * Attached to the {@see 'wp_update_term_parent'} filter.
4195 * @param int $parent `term_id` of the parent for the term we're checking.
4196 * @param int $term_id The term we're checking.
4197 * @param string $taxonomy The taxonomy of the term we're checking.
4199 * @return int The new parent for the term.
4201 function wp_check_term_hierarchy_for_loops( $parent, $term_id, $taxonomy ) {
4202 // Nothing fancy here - bail
4206 // Can't be its own parent.
4207 if ( $parent == $term_id )
4210 // Now look for larger loops.
4211 if ( !$loop = wp_find_hierarchy_loop( 'wp_get_term_taxonomy_parent_id', $term_id, $parent, array( $taxonomy ) ) )
4212 return $parent; // No loop
4214 // Setting $parent to the given value causes a loop.
4215 if ( isset( $loop[$term_id] ) )
4218 // There's a loop, but it doesn't contain $term_id. Break the loop.
4219 foreach ( array_keys( $loop ) as $loop_member )
4220 wp_update_term( $loop_member, $taxonomy, array( 'parent' => 0 ) );