wp_insert_term()

wp_insert_term( string $term, string $taxonomy, array|string $args = array() )

向数据库添加新术语。
Add a new term to the database.

目录锚点:#说明#源码#笔记

说明(Description)

不存在的术语按以下顺序插入:将该术语添加到术语表中,然后与分类法相关。如果一切都是正确的,将启动几个操作。计算“term_id_filter”。术语缓存已清除。又有几个动作被启动。返回一个数组,其中包含术语“_id”和“term_taxonomy”标识。如果“slug”参数不为空,则检查该术语是否无效。如果它不是有效的现有术语,则添加该术语并给出术语“_id”。如果分类法是分层的,并且“parent”参数不为空,则插入术语并给出术语_id。错误处理:如果$taxonomy不存在或$term为空,将返回WP_Error对象。如果术语已经存在于同一层次结构中,或者术语slug和name不唯一,则将返回WP_Error对象。


源码(Source)

/**
 * Add a new term to the database.
 *
 * A non-existent term is inserted in the following sequence:
 * 1. The term is added to the term table, then related to the taxonomy.
 * 2. If everything is correct, several actions are fired.
 * 3. The 'term_id_filter' is evaluated.
 * 4. The term cache is cleaned.
 * 5. Several more actions are fired.
 * 6. An array is returned containing the term_id and term_taxonomy_id.
 *
 * If the 'slug' argument is not empty, then it is checked to see if the term
 * is invalid. If it is not a valid, existing term, it is added and the term_id
 * is given.
 *
 * If the taxonomy is hierarchical, and the 'parent' argument is not empty,
 * the term is inserted and the term_id will be given.

 * Error handling:
 * If $taxonomy does not exist or $term is empty,
 * a WP_Error object will be returned.
 *
 * If the term already exists on the same hierarchical level,
 * or the term slug and name are not unique, a WP_Error object will be returned.
 *
 * @global wpdb $wpdb WordPress database abstraction object.

 * @since 2.3.0
 *
 * @param string       $term     The term to add or update.
 * @param string       $taxonomy The taxonomy to which to add the term.
 * @param array|string $args {
 *     Optional. Array or string of arguments for inserting a term.
 *
 *     @type string $alias_of    Slug of the term to make this term an alias of.
 *                               Default empty string. Accepts a term slug.
 *     @type string $description The term description. Default empty string.
 *     @type int    $parent      The id of the parent term. Default 0.
 *     @type string $slug        The term slug to use. Default empty string.
 * }
 * @return array|WP_Error An array containing the `term_id` and `term_taxonomy_id`,
 *                        {@see WP_Error} otherwise.
 */
function wp_insert_term( $term, $taxonomy, $args = array() ) {
	global $wpdb;

	if ( ! taxonomy_exists($taxonomy) ) {
		return new WP_Error('invalid_taxonomy', __('Invalid taxonomy'));
	}
	/**
	 * Filter a term before it is sanitized and inserted into the database.
	 *
	 * @since 3.0.0
	 *
	 * @param string $term     The term to add or update.
	 * @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 ( $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;
	$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 has been explicitly provided.
	 */
	if ( $name_match = get_term_by( 'name', $name, $taxonomy ) ) {
		$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( $taxonomy, array( 'get' => 'all', 'parent' => $parent ) );

				$existing_term = null;
				if ( $name_match->slug === $slug && in_array( $name, wp_list_pluck( $siblings, 'name' ) ) ) {
					$existing_term = $name_match;
				} elseif ( $slug_match && in_array( $slug, wp_list_pluck( $siblings, 'slug' ) ) ) {
					$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 the name provided already exists in this taxonomy.' ), $name_match->term_id );
			}
		}
	}

	$slug = wp_unique_term_slug( $slug, (object) $args );

	if ( false === $wpdb->insert( $wpdb->terms, compact( 'name', 'slug', 'term_group' ) ) ) {
		return new WP_Error( 'db_insert_error', __( 'Could not insert term into the 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 an empty string.
	if ( empty($slug) ) {
		$slug = sanitize_title($slug, $term_id);

		/** This action is documented in wp-includes/taxonomy.php */
		do_action( 'edit_terms', $term_id, $taxonomy );
		$wpdb->update( $wpdb->terms, compact( 'slug' ), compact( 'term_id' ) );

		/** This action is documented in 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 WHERE tt.taxonomy = %s AND t.term_id = %d", $taxonomy, $term_id ) );

	if ( !empty($tt_id) ) {
		return array('term_id' => $term_id, 'term_taxonomy_id' => $tt_id);
	}
	$wpdb->insert( $wpdb->term_taxonomy, compact( 'term_id', 'taxonomy', 'description', 'parent') + array( 'count' => 0 ) );
	$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 the older term instead. Then return out of the function so that the "create" hooks
	 * are not fired.
	 */
	$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="" )="" );="" 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.
	 *
	 * @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 the hook name, `$taxonomy`, refers
	 * to the slug of the taxonomy the term was created for.
	 *
	 * @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 );

	/**
	 * Filter the term ID after a new term is created.
	 *
	 * @since 2.3.0
	 *
	 * @param int $term_id Term ID.
	 * @param int $tt_id   Taxonomy term 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.
	 *
	 * @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 dynamic portion of the hook name, `$taxonomy`, refers to the taxonomy slug.
	 *
	 * @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 );

	return array('term_id' => $term_id, 'term_taxonomy_id' => $tt_id);
}
更新版本 源码位置 使用 被使用
2.3.0 wp-includes/taxonomy.php 4 14

笔记(Notes)

注意自定义分类的无效分类错误。此错误意味着您在register_taxonomy之前调用wp_insert_term。仔细检查你的动作钩。

absint()

absint( mixed $maybeint )将值转换为非负整数,也就是取绝对值。Convert a value to non-negative integer.目录锚点:#参数#返回#源码#笔记参数(Parameters)参数类型必填说明$maybeint(mixed)必需要转换为非负整数的数据。返回(Return)(int)非负整数。源码(Source)function absint( $maybeint ) { return abs( intval( $maybeint ) );}/** *...

日期:2020-06-23 10:35:32 浏览:1232

activate_plugin()

activate_plugin( string $plugin, string $redirect = '', bool $network_wide = false, bool $silent = false )尝试激活插件,并在成功时重定向。Attempts activation of plugin in a “sandbox” and redirects on success.目录锚点:#说明#参数#返回#源码#笔记说明(Description)已激活的插件将不会再次尝试激活。其工作方式是在尝试包含插件...

日期:2020-06-23 10:39:26 浏览:981

activate_plugins()

activate_plugins( string|string[]&nbsp;$plugins, string&nbsp;$redirect&nbsp;=&nbsp;'', bool&nbsp;$network_wide&nbsp;=&nbsp;false, bool&nbsp;$silent&nbsp;=&nbsp;false&nbsp;)激活多个插件。Activate multiple plugins.目录锚点:#说明#参数#返回#源码说明(Description)当WP_Error返回时,并不意...

日期:2020-09-08 17:28:27 浏览:1038

activate_sitewide_plugin()

activate_sitewide_plugin()不推荐用于激活仅网络插件的功能。Deprecated functionality for activating a network-only plugin.目录锚点:#说明#返回#源码说明(Description)另见激活插件()返回(Return)无返回值源码(Source)更新版本源码位置使用被使用3.0.0 wp-admin/includes/ms-deprecated.php:5701 function...

日期:2020-09-08 17:28:28 浏览:1736

addslashes_gpc()

addslashes_gpc( string&nbsp;$gpc&nbsp;)添加斜线以转义字符串。Adds slashes to escape strings.目录锚点:#说明#参数#返回#源码说明(Description)如果设置了magic_quotes_gpc,将首先删除斜线,请参见https://www.php.net/magic_quotes更多细节。参数(Parameters)参数类型必填说明 $gpc (string) ...

日期:2020-09-21 12:46:52 浏览:889

addslashes_strings_only()

addslashes_strings_only( mixed&nbsp;$value&nbsp;)仅当提供的值是字符串时才添加斜杠。Adds slashes only if the provided value is a string.目录锚点:#参数#返回#源码参数(Parameters)参数类型必填说明 $value (mixed) 必需 返回(Return)(mixe...

日期:2020-09-24 15:58:41 浏览:1269

add_action()

add_action( string&nbsp;$tag, callable&nbsp;$function_to_add, int&nbsp;$priority&nbsp;=&nbsp;10, int&nbsp;$accepted_args&nbsp;=&nbsp;1&nbsp;)将函数挂接到特定操作上。Hooks a function on to a specific action.目录锚点:#说明#参数#返回#源码#笔记说明(Description)Actions是WordPress核心在执行期间...

日期:2020-09-08 17:28:28 浏览:1128

add_blog_option()

add_blog_option( int&nbsp;$id, string&nbsp;$option, mixed&nbsp;$value&nbsp;)为给定的博客id添加新选项。Add a new option for a given blog id.目录锚点:#说明#参数#返回#源码#笔记说明(Description)不需要序列化值。如果需要序列化该值,则在将其插入数据库之前将对其进行序列化。请记住,资源不能序列化或作为选项添加。可以创建不带值的选项,然后稍后更新这些值。现有选项将不会更新,并执行检...

日期:2020-08-26 10:53:23 浏览:944

add_clean_index()

add_clean_index( string&nbsp;$table, string&nbsp;$index&nbsp;)向指定表添加索引。Adds an index to a specified table.目录锚点:#参数#返回#源码#笔记参数(Parameters)参数类型必填说明 $table (string) 必需 数据库表名。 ...

日期:2020-09-08 17:28:29 浏览:945

add_comments_page()

add_comments_page( string&nbsp;$page_title, string&nbsp;$menu_title, string&nbsp;$capability, string&nbsp;$menu_slug, callable&nbsp;$function&nbsp;=&nbsp;'', int&nbsp;$position&nbsp;=&nbsp;null&nbsp;)将子菜单页添加到“注释”主菜单。Add submenu page to the Comments ma...

日期:2020-08-24 11:14:39 浏览:992