wp_ajax_add_user()
云策文档标注
概述
wp_ajax_add_user() 是一个 WordPress AJAX 处理函数,用于通过 AJAX 请求添加用户。它验证权限、处理用户创建,并返回 AJAX 响应。
关键要点
- 函数参数 $action 是必需的,用于指定操作,默认为 'add-user'。
- 使用 check_ajax_referer() 验证 AJAX 请求的安全性。
- 要求当前用户具有 'create_users' 权限,否则通过 wp_die() 终止执行。
- 调用 edit_user() 创建或编辑用户,返回用户 ID 或 WP_Error。
- 成功时,通过 WP_Ajax_Response 返回用户数据,包括表格行和补充信息。
- 错误处理包括 wp_die() 和 WP_Ajax_Response 响应。
代码示例
function wp_ajax_add_user( $action ) {
if ( empty( $action ) ) {
$action = 'add-user';
}
check_ajax_referer( $action );
if ( ! current_user_can( 'create_users' ) ) {
wp_die( -1 );
}
$user_id = edit_user();
if ( ! $user_id ) {
wp_die( 0 );
} elseif ( is_wp_error( $user_id ) ) {
$x = new WP_Ajax_Response(
array(
'what' => 'user',
'id' => $user_id,
)
);
$x->send();
}
$user_object = get_userdata( $user_id );
$wp_list_table = _get_list_table( 'WP_Users_List_Table' );
$role = current( $user_object->roles );
$x = new WP_Ajax_Response(
array(
'what' => 'user',
'id' => $user_id,
'data' => $wp_list_table->single_row( $user_object, '', $role ),
'supplemental' => array(
'show-link' => sprintf(
/* translators: %s: The new user. */
__( 'User %s added' ),
'' . $user_object->user_login . ''
),
'role' => $role,
),
)
);
$x->send();
}注意事项
- 此函数依赖于 $_POST 数据,edit_user() 使用 $_POST 来设置用户信息。
- AJAX 请求必须包含正确的 nonce,通过 check_ajax_referer() 验证。
- 返回的 AJAX 响应包含用户数据和状态,适用于前端更新。
原文内容
Handles adding a user via AJAX.
Parameters
$actionstringrequired-
Action to perform.
Source
function wp_ajax_add_user( $action ) {
if ( empty( $action ) ) {
$action = 'add-user';
}
check_ajax_referer( $action );
if ( ! current_user_can( 'create_users' ) ) {
wp_die( -1 );
}
$user_id = edit_user();
if ( ! $user_id ) {
wp_die( 0 );
} elseif ( is_wp_error( $user_id ) ) {
$x = new WP_Ajax_Response(
array(
'what' => 'user',
'id' => $user_id,
)
);
$x->send();
}
$user_object = get_userdata( $user_id );
$wp_list_table = _get_list_table( 'WP_Users_List_Table' );
$role = current( $user_object->roles );
$x = new WP_Ajax_Response(
array(
'what' => 'user',
'id' => $user_id,
'data' => $wp_list_table->single_row( $user_object, '', $role ),
'supplemental' => array(
'show-link' => sprintf(
/* translators: %s: The new user. */
__( 'User %s added' ),
'<a href="#user-' . $user_id . '">' . $user_object->user_login . '</a>'
),
'role' => $role,
),
)
);
$x->send();
}
Changelog
| Version | Description |
|---|---|
| 3.1.0 | Introduced. |