Масив параметрів для терміну, що додається. Може приймати такі параметри:
description (рядок) Опис терміну (рубрики). За замовчуванням: ”
parent (число) Батьківський термін для знову вставляється. За замовчуванням: 0
Якщо вказано аргумент parent , термін буде додано тільки якщо таксономія деревоподібна і вказаний у parent термін існує.
slug (рядок) Ярлик нового терміну (назва URL). Типово: sanitize_title( $term )
Якщо вказано аргумент ‘slug’ , він буде перевірений на доступність (чи не існує терміна з такою ж слагом). Якщо такого терміну ще немає, термін буде додано.
alias_of (рядок) Ярлик (склад) терміну, щоб зробити цей термін аліасом.
Тут вказується ярлик терміна, у якого потрібно взяти групу – поле term_group і використовувати це число для поточного терміну, що додається. Якщо у вказаного в alias_of терміна немає групи, вона буде створена (буде створено число). Насправді term_group ніде немає. За допомогою нього передбачалося об’єднувати терміни, щоб показувати записи із групи… За замовчуванням: ”
Приклади
0
#1 Приклад вставки нового терміна “Яблуко” у таксономію “product”.
Перед вставкою автоматично перевіряємо та отримуємо ID батьківського терміну “fruits”:
function wp_insert_term( $term, $taxonomy, $args = array() ) {
Global $wpdb;
if ( ! taxonomy_exists( $taxonomy ) ) {
return new WP_Error( 'invalid_taxonomy', __( 'Invalid taxonomy.' ) );
}
/**
* Filters a term before it is sanitized and inserted in the database.
*
* @ Since 3.0.0
*
* @param string|WP_Error $term Термін name до адреси, або WP_Error об'єкт, якщо він не вдається.
* @param string $taxonomy Taxonomy slug.
*/
$term = apply_filters( 'pre_insert_term', $term, $taxonomy);
if ( is_wp_error( $term ) ) {
return $term;
}
if ( is_int( $term ) && 0 === $term ) {
return new WP_Error( 'invalid_term_id', __( 'Invalid term ID.' ) );
}
if ( '' === trim( $term ) ) {
return new WP_Error( 'empty_term_name', __( 'A name is required for this term.' ) );
}
$defaults = array(
'alias_of' => '',
'description' => '',
'parent' => 0,
'slug' => '',
);
$ args = wp_parse_args ($ args, $ defaults);
if ( (int) $args['parent'] > 0 && ! term_exists( (int) $args['parent'] ) ) {
return new WP_Error( 'missing_parent', __( 'Parent term does not exist.' ) );
}
$args['name'] = $term;
$args['taxonomy'] = $taxonomy;
// Coerce null description до strings, до avoid database errors.
$args['description'] = (string) $args['description'];
$args = sanitize_term( $args, $taxonomy, 'db');
// expected_slashed ($name)
$name = wp_unslash( $args['name'] );
$description = wp_unslash( $args['description'] );
$parent = (int) $args['parent'];
$ slug_provided = ! empty($args['slug']);
if ( ! $slug_provided ) {
$ slug = sanitize_title ( $ name );
} else {
$slug = $args['slug'];
}
$ term_group = 0;
if ( $args['alias_of'] ) {
$alias = get_term_by( 'slug', $args['alias_of'], $taxonomy );
if ( ! empty( $alias->term_group ) ) {
// The alias we want is already in a group, so let's use that one.
$term_group = $alias->term_group;
} elseif ( ! empty( $alias->term_id ) ) {
/*
* The alias is not in a group, so we create a new one
* and add the alias to it.
*/
$term_group = $wpdb->get_var( "SELECT MAX(term_group) FROM $wpdb->terms" ) + 1;
wp_update_term(
$alias->term_id,
$taxonomy,
array(
'term_group' => $term_group,
)
);
}
}
/*
* Prevent the creation of terms with duplicate names at the same level of a taxonomy hierarchy,
* unless a unique slug має бути explicitly provided.
*/
$name_matches = get_terms(
array(
'taxonomy' => $taxonomy,
'name' => $name,
'hide_empty' => false,
'parent' => $args['parent'],
'update_term_meta_cache' => false,
)
);
/*
* The `name` match in `get_terms()` doesn't differentiate accented characters,
* So we do a stricter comparison here.
*/
$name_match = null;
if ( $name_matches ) {
foreach ( $name_matches as $_match ) {
if ( strtolower( $name ) === strtolower( $_match->name ) ) {
$name_match = $_match;
break;
}
}
}
if ($name_match) {
$slug_match = get_term_by( 'slug', $slug, $taxonomy);
if ( ! $slug_provided || $name_match->slug === $slug || $slug_match ) {
if ( is_taxonomy_hierarchical( $taxonomy ) ) {
$ siblings = get_terms (
array(
'taxonomy' => $taxonomy,
'get' => 'all',
'parent' => $parent,
'update_term_meta_cache' => false,
)
);
$existing_term = null;
$sibling_names = wp_list_pluck( $siblings, 'name');
$sibling_slugs = wp_list_pluck( $siblings, 'slug');
if ( ( ! $slug_provided || $name_match->slug === $slug ) && in_array( $name, $sibling_names, true ) ) {
$existing_term = $name_match;
} elseif ( $slug_match && in_array( $slug, $sibling_slugs, true ) ) {
$existing_term = $slug_match;
}
if ($existing_term) {
return new WP_Error( 'term_exists', __( 'A term with the name provided already exists with this parent.' ), $existing_term->term_id );
}
} else {
return new WP_Error( 'term_exists', __( 'A term with name provided already exists in this taxonomy.' ), $name_match->term_id );
}
}
}
$slug = wp_unique_term_slug( $slug, (object) $args );
$data = compact( 'name', 'slug', 'term_group' );
/**
* Filters term data before it is inserted into database.
*
* @ Since 4.7.0
*
* @param array $data Term data to be inserted.
* @param string $taxonomy Taxonomy slug.
* @param array $args Arguments passed to wp_insert_term().
*/
$data = apply_filters( 'wp_insert_term_data', $data, $taxonomy, $args);
if ( false === $wpdb->insert( $wpdb->terms, $data ) ) {
return new WP_Error( 'db_insert_error', __( 'Could not insert term into database.' ), $wpdb->last_error );
}
$term_id = (int) $wpdb->insert_id;
// Seems unreachable. However, is used in the case that a term name is provided, which sanitizes to empty string.
if ( empty( $slug ) ) {
$ slug = sanitize_title ( $ slug, $ term_id );
/** Ця дія міститься в wp-includes/taxonomy.php */
do_action( 'edit_terms', $term_id, $taxonomy);
$wpdb->update( $wpdb->terms, compact( 'slug' ), compact( 'term_id' ) );
/** Ця дія міститься в wp-includes/taxonomy.php */
do_action( 'edited_terms', $term_id, $taxonomy);
}
$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 WHE %s AND t.term_id = %d", $taxonomy, $term_id)));
if ( ! empty( $tt_id ) ) {
return array(
'term_id' => $term_id,
'term_taxonomy_id' => $tt_id,
);
}
if ( false === $wpdb->insert( $wpdb->term_taxonomy, compact( 'term_id', 'taxonomy', 'description', 'parent' ) + array( 'count' => 0 ) ) ) {
return new WP_Error( 'db_insert_error', __( 'Could not insert term taxonomy in the database.' ), $wpdb->last_error );
}
$tt_id = (int) $wpdb->insert_id;
/*
* Sanity check: if we just created a term with the same parent + taxonomy + slug but a higher term_id than
* an existing term, then we have unwittingly created a duplicate term. Delete the dupe, and use the term_id
* and term_taxonomy_id of older term instead. The return out of the function so that the "create" hooks
* are not fired.
*/
$duplicate_term = $wpdb->get_row( $wpdb->prepare( "SELECT t.term_id, t.slug, tt.term_taxonomy_id, tt.taxonomy FROM $wpdb->terms AS t INNER JOIN $wpdb->term_tax ( 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));
/**
* Filters duplicate term check that takes place during term creation.
*
* Терм parent + taxonomy + slug combinations є meant to be unique, and wp_insert_term()
* Performs a last-minute confirmation of this uniqueness before allowing a new term
* to be created. Plugins with different uniqueness requirements use this filter
* Використовуйте pass або modify duplicate-term check.
*
* @ Since 5.1.0
*
* @param object $duplicate_term Duplicate term row from terms table, if found.
* @param string $term Term being inserted.
* @param string $taxonomy Taxonomy name.
* @param array $args Term arguments passed to the function.
* @param int $tt_id term_taxonomy_id для нового створеного терміну.
*/
$duplicate_term = apply_filters( 'wp_insert_term_duplicate_term_check', $duplicate_term, $term, $taxonomy, $args, $tt_id);
if ( $duplicate_term ) {
$wpdb->delete( $wpdb->terms, array( 'term_id' => $term_id ) );
$wpdb->delete( $wpdb->term_taxonomy, array( 'term_taxonomy_id' => $tt_id ) );
$term_id = (int) $duplicate_term->term_id;
$tt_id = (int) $duplicate_term->term_taxonomy_id;
clean_term_cache($term_id, $taxonomy);
return array(
'term_id' => $term_id,
'term_taxonomy_id' => $tt_id,
);
}
/**
* Fires immediately after a new term is created, before the term cache is cleaned.
*
* The {@see 'create_$taxonomy'} hook is also available for targeting a specific
* taxonomy.
*
* @ Since 2.3.0
*
* @param int $term_id Term ID.
* @param int $tt_id Term taxonomy ID.
* @param string $taxonomy Taxonomy slug.
*/
do_action( 'create_term', $term_id, $tt_id, $taxonomy);
/**
* Fires after a new term is created for a specific taxonomy.
*
* The dynamic portion of hook name, `$taxonomy`, refers
* to slug of the taxonomy the term був створений для.
*
* Possible hook names include:
*
* - `create_category`
* - `create_post_tag`
*
* @ Since 2.3.0
*
* @param int $term_id Term ID.
* @param int $tt_id Term taxonomy ID.
*/
do_action( "create_{$taxonomy}", $term_id, $tt_id);
/**
* Filters the term ID after a new term is created.
*
* @ Since 2.3.0
*
* @param int $term_id Term ID.
* @param int $tt_id Term taxonomy ID.
*/
$term_id = apply_filters( 'term_id_filter', $term_id, $tt_id);
clean_term_cache($term_id, $taxonomy);
/**
* Fires after a new term is created, and after the term cache has been cleaned.
*
* The {@see 'created_$taxonomy'} hook is also available for targeting a specific
* taxonomy.
*
* @ Since 2.3.0
*
* @param int $term_id Term ID.
* @param int $tt_id Term taxonomy ID.
* @param string $taxonomy Taxonomy slug.
*/
do_action( 'created_term', $term_id, $tt_id, $taxonomy);
/**
* Fires after a new term in a specific taxonomy is created, and after the term
* cache has been cleaned.
*
* The dynamickа порція 'hook name', `$taxonomy`, refers to the taxonomy slug.
*
* Possible hook names include:
*
* - `created_category`
* - `created_post_tag`
*
* @ Since 2.3.0
*
* @param int $term_id Term ID.
* @param int $tt_id Term taxonomy ID.
*/
do_action( "created_{$taxonomy}", $term_id, $tt_id);
/**
* Fires after a term has been saved, and the term cache has been cleared.
*
* The {@see 'saved_$taxonomy'} hook is also available for targeting a specific
* taxonomy.
*
* @ Since 5.5.0
*
* @param int $term_id Term ID.
* @param int $tt_id Term taxonomy ID.
* @param string $taxonomy Taxonomy slug.
* @param bool $update Whether this is an existing term being updated.
*/
do_action( 'saved_term', $term_id, $tt_id, $taxonomy, false);
/**
* Fires after a term in a specific taxonomy has been saved, and the term
* cache has been cleared.
*
* The dynamickа порція 'hook name', `$taxonomy`, refers to the taxonomy slug.
*
* Possible hook names include:
*
* - `saved_category`
* - `saved_post_tag`
*
* @ Since 5.5.0
*
* @param int $term_id Term ID.
* @param int $tt_id Term taxonomy ID.
* @param bool $update Whether this is an existing term being updated.
*/
do_action( "saved_{$taxonomy}", $term_id, $tt_id, false);
return array(
'term_id' => $term_id,
'term_taxonomy_id' => $tt_id,
);
}