wp_insert_user()

wp_insert_user( array|object|WP_User $userdata )

将用户插入数据库。
Insert a user into the database.
目录锚点:#说明#源码#笔记

说明(Description)

大多数$userdata数组字段都有与值关联的筛选器。例外情况包括'ID'、'rich'editing'、'syntax'highlighting'、'comment'u shortcuts'、'admin'u color'、'use'u ssl'、'user'u activation_key'、'spam'和'role'。过滤器的前缀为“pre_user”,后跟字段名。一个使用“description”的示例将有一个名为“pre_user_description”的过滤器,可以将其挂接到该过滤器中。


源码(Source)

/**
 * Insert a user into the database.
 *
 * Most of the `$userdata` array fields have filters associated with the values. Exceptions are
 * 'ID', 'rich_editing', 'comment_shortcuts', 'admin_color', 'use_ssl',
 * 'user_registered', and 'role'. The filters have the prefix 'pre_user_' followed by the field
 * name. An example using 'description' would have the filter called, 'pre_user_description' that
 * can be hooked into.
 *
 * @since 2.0.0
 * @since 3.6.0 The `aim`, `jabber`, and `yim` fields were removed as default user contact
 *              methods for new installs. See wp_get_user_contact_methods().
 *
 * @global wpdb $wpdb WordPress database object for queries.
 *
 * @param array|object|WP_User $userdata {
 *     An array, object, or WP_User object of user data arguments.
 *
 *     @type int         $ID                   User ID. If supplied, the user will be updated.
 *     @type string      $user_pass            The plain-text user password.
 *     @type string      $user_login           The user's login username.
 *     @type string      $user_nicename        The URL-friendly user name.
 *     @type string      $user_url             The user URL.
 *     @type string      $user_email           The user email address.
 *     @type string      $display_name         The user's display name.
 *                                             Default is the the user's username.
 *     @type string      $nickname             The user's nickname.
 *                                             Default is the the user's username.
 *     @type string      $first_name           The user's first name. For new users, will be used
 *                                             to build the first part of the user's display name
 *                                             if `$display_name` is not specified.
 *     @type string      $last_name            The user's last name. For new users, will be used
 *                                             to build the second part of the user's display name
 *                                             if `$display_name` is not specified.
 *     @type string      $description          The user's biographical description.
 *     @type string|bool $rich_editing         Whether to enable the rich-editor for the user.
 *                                             False if not empty.
 *     @type string|bool $comment_shortcuts    Whether to enable comment moderation keyboard
 *                                             shortcuts for the user. Default false.
 *     @type string      $admin_color          Admin color scheme for the user. Default 'fresh'.
 *     @type bool        $use_ssl              Whether the user should always access the admin over
 *                                             https. Default false.
 *     @type string      $user_registered      Date the user registered. Format is 'Y-m-d H:i:s'.
 *     @type string|bool $show_admin_bar_front Whether to display the Admin Bar for the user on the
 *                                             site's frontend. Default true.
 *     @type string      $role                 User's role.
 * }
 * @return int|WP_Error The newly created user's ID or a WP_Error object if the user could not
 *                      be created.
 */
function wp_insert_user( $userdata ) {
	global $wpdb;

	if ( $userdata instanceof stdClass ) {
		$userdata = get_object_vars( $userdata );
	} elseif ( $userdata instanceof WP_User ) {
		$userdata = $userdata->to_array();
	}
	// Are we updating or creating?
	if ( ! empty( $userdata['ID'] ) ) {
		$ID = (int) $userdata['ID'];
		$update = true;
		$old_user_data = WP_User::get_data_by( 'id', $ID );
		// hashed in wp_update_user(), plaintext if called directly
		$user_pass = $userdata['user_pass'];
	} else {
		$update = false;
		// Hash the password
		$user_pass = wp_hash_password( $userdata['user_pass'] );
	}

	$sanitized_user_login = sanitize_user( $userdata['user_login'], true );

	/**
	 * Filter a username after it has been sanitized.
	 *
	 * This filter is called before the user is created or updated.
	 *
	 * @since 2.0.3
	 *
	 * @param string $sanitized_user_login Username after it has been sanitized.
	 */
	$pre_user_login = apply_filters( 'pre_user_login', $sanitized_user_login );

	//Remove any non-printable chars from the login string to see if we have ended up with an empty username
	$user_login = trim( $pre_user_login );

	if ( empty( $user_login ) ) {
		return new WP_Error('empty_user_login', __('Cannot create a user with an empty login name.') );
	}
	if ( ! $update && username_exists( $user_login ) ) {
		return new WP_Error( 'existing_user_login', __( 'Sorry, that username already exists!' ) );
	}

	// If a nicename is provided, remove unsafe user characters before
	// using it. Otherwise build a nicename from the user_login.
	if ( ! empty( $userdata['user_nicename'] ) ) {
		$user_nicename = sanitize_user( $userdata['user_nicename'], true );
	} else {
		$user_nicename = $user_login;
	}

	$user_nicename = sanitize_title( $user_nicename );

	// Store values to save in user meta.
	$meta = array();

	/**
	 * Filter a user's nicename before the user is created or updated.
	 *
	 * @since 2.0.3
	 *
	 * @param string $user_nicename The user's nicename.
	 */
	$user_nicename = apply_filters( 'pre_user_nicename', $user_nicename );

	$raw_user_url = empty( $userdata['user_url'] ) ? '' : $userdata['user_url'];

	/**
	 * Filter a user's URL before the user is created or updated.
	 *
	 * @since 2.0.3
	 *
	 * @param string $raw_user_url The user's URL.
	 */
	$user_url = apply_filters( 'pre_user_url', $raw_user_url );

	$raw_user_email = empty( $userdata['user_email'] ) ? '' : $userdata['user_email'];

	/**
	 * Filter a user's email before the user is created or updated.
	 *
	 * @since 2.0.3
	 *
	 * @param string $raw_user_email The user's email.
	 */
	$user_email = apply_filters( 'pre_user_email', $raw_user_email );

	/*
	 * If there is no update, just check for `email_exists`. If there is an update,
	 * check if current email and new email are the same, or not, and check `email_exists`
	 * accordingly.
	 */
	if ( ( ! $update || ( ! empty( $old_user_data ) && 0 !== strcasecmp( $user_email, $old_user_data->user_email ) ) )
		&& ! defined( 'WP_IMPORTING' )
		&& email_exists( $user_email )
	) {
		return new WP_Error( 'existing_user_email', __( 'Sorry, that email address is already used!' ) );
	}
	$nickname = empty( $userdata['nickname'] ) ? $user_login : $userdata['nickname'];

	/**
	 * Filter a user's nickname before the user is created or updated.
	 *
	 * @since 2.0.3
	 *
	 * @param string $nickname The user's nickname.
	 */
	$meta['nickname'] = apply_filters( 'pre_user_nickname', $nickname );

	$first_name = empty( $userdata['first_name'] ) ? '' : $userdata['first_name'];

	/**
	 * Filter a user's first name before the user is created or updated.
	 *
	 * @since 2.0.3
	 *
	 * @param string $first_name The user's first name.
	 */
	$meta['first_name'] = apply_filters( 'pre_user_first_name', $first_name );

	$last_name = empty( $userdata['last_name'] ) ? '' : $userdata['last_name'];

	/**
	 * Filter a user's last name before the user is created or updated.
	 *
	 * @since 2.0.3
	 *
	 * @param string $last_name The user's last name.
	 */
	$meta['last_name'] = apply_filters( 'pre_user_last_name', $last_name );

	if ( empty( $userdata['display_name'] ) ) {
		if ( $update ) {
			$display_name = $user_login;
		} elseif ( $meta['first_name'] && $meta['last_name'] ) {
			/* translators: 1: first name, 2: last name */
			$display_name = sprintf( _x( '%1$s %2$s', 'Display name based on first name and last name' ), $meta['first_name'], $meta['last_name'] );
		} elseif ( $meta['first_name'] ) {
			$display_name = $meta['first_name'];
		} elseif ( $meta['last_name'] ) {
			$display_name = $meta['last_name'];
		} else {
			$display_name = $user_login;
		}
	} else {
		$display_name = $userdata['display_name'];
	}

	/**
	 * Filter a user's display name before the user is created or updated.
	 *
	 * @since 2.0.3
	 *
	 * @param string $display_name The user's display name.
	 */
	$display_name = apply_filters( 'pre_user_display_name', $display_name );

	$description = empty( $userdata['description'] ) ? '' : $userdata['description'];

	/**
	 * Filter a user's description before the user is created or updated.
	 *
	 * @since 2.0.3
	 *
	 * @param string $description The user's description.
	 */
	$meta['description'] = apply_filters( 'pre_user_description', $description );

	$meta['rich_editing'] = empty( $userdata['rich_editing'] ) ? 'true' : $userdata['rich_editing'];

	$meta['comment_shortcuts'] = empty( $userdata['comment_shortcuts'] ) || 'false' === $userdata['comment_shortcuts'] ? 'false' : 'true';

	$admin_color = empty( $userdata['admin_color'] ) ? 'fresh' : $userdata['admin_color'];
	$meta['admin_color'] = preg_replace( '|[^a-z0-9 _.-@]|i', '', $admin_color );

	$meta['use_ssl'] = empty( $userdata['use_ssl'] ) ? 0 : $userdata['use_ssl'];

	$user_registered = empty( $userdata['user_registered'] ) ? gmdate( 'Y-m-d H:i:s' ) : $userdata['user_registered'];

	$meta['show_admin_bar_front'] = empty( $userdata['show_admin_bar_front'] ) ? 'true' : $userdata['show_admin_bar_front'];

	$user_nicename_check = $wpdb->get_var( $wpdb->prepare("SELECT ID FROM $wpdb->users WHERE user_nicename = %s AND user_login != %s LIMIT 1" , $user_nicename, $user_login));

	if ( $user_nicename_check ) {
		$suffix = 2;
		while ($user_nicename_check) {
			$alt_user_nicename = $user_nicename . "-$suffix";
			$user_nicename_check = $wpdb->get_var( $wpdb->prepare("SELECT ID FROM $wpdb->users WHERE user_nicename = %s AND user_login != %s LIMIT 1" , $alt_user_nicename, $user_login));
			$suffix++;
		}
		$user_nicename = $alt_user_nicename;
	}

	$compacted = compact( 'user_pass', 'user_email', 'user_url', 'user_nicename', 'display_name', 'user_registered' );
	$data = wp_unslash( $compacted );

	if ( $update ) {
		if ( $user_email !== $old_user_data->user_email ) {
			$data['user_activation_key'] = '';
		}
		$wpdb->update( $wpdb->users, $data, compact( 'ID' ) );
		$user_id = (int) $ID;
	} else {
		$wpdb->insert( $wpdb->users, $data + compact( 'user_login' ) );
		$user_id = (int) $wpdb->insert_id;
	}

	$user = new WP_User( $user_id );

	// Update user meta.
	foreach ( $meta as $key => $value ) {
		update_user_meta( $user_id, $key, $value );
	}

	foreach ( wp_get_user_contact_methods( $user ) as $key => $value ) {
		if ( isset( $userdata[ $key ] ) ) {
			update_user_meta( $user_id, $key, $userdata[ $key ] );
		}
	}

	if ( isset( $userdata['role'] ) ) {
		$user->set_role( $userdata['role'] );
	} elseif ( ! $update ) {
		$user->set_role(get_option('default_role'));
	}
	wp_cache_delete( $user_id, 'users' );
	wp_cache_delete( $user_login, 'userlogins' );

	if ( $update ) {
		/**
		 * Fires immediately after an existing user is updated.
		 *
		 * @since 2.0.0
		 *
		 * @param int    $user_id       User ID.
		 * @param object $old_user_data Object containing user's data prior to update.
		 */
		do_action( 'profile_update', $user_id, $old_user_data );
	} else {
		/**
		 * Fires immediately after a new user is registered.
		 *
		 * @since 1.5.0
		 *
		 * @param int $user_id User ID.
		 */
		do_action( 'user_register', $user_id );
	}

	return $user_id;
}
更新版本 源码位置 使用 被使用
5.3.0 wp-includes/user.php 18 18

笔记(Notes)

数据库中的用户url长度限制为100。

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[] $plugins, string $redirect = '', bool $network_wide = false, bool $silent = false )激活多个插件。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 $gpc )添加斜线以转义字符串。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 $value )仅当提供的值是字符串时才添加斜杠。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 $tag, callable $function_to_add, int $priority = 10, int $accepted_args = 1 )将函数挂接到特定操作上。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 $id, string $option, mixed $value )为给定的博客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 $table, string $index )向指定表添加索引。Adds an index to a specified table.目录锚点:#参数#返回#源码#笔记参数(Parameters)参数类型必填说明 $table (string) 必需 数据库表名。 ...

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

add_comments_page()

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

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