You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Wordpress插件中为新用户以编程方式创建应用密码

实现方案

WordPress 5.6及以上版本已经内置了应用密码的核心接口,你可以直接调用内置类的方法实现编程生成指定名称的应用密码,不需要额外引入第三方库。


前置说明

  • 默认HTTPS站点自动开启应用密码功能,HTTP本地开发环境需要先在插件代码中添加以下过滤器开启功能:
add_filter( 'wp_is_application_passwords_available', '__return_true' );
  • 应用密码的明文仅会在生成时返回一次,数据库仅存储哈希值,无法二次查询获取明文,生成后请及时存储到你需要的位置。

完整代码示例

在你现有创建用户的代码之后,新增应用密码生成逻辑即可:

// create the user
$user_id = wp_create_user(
    $this->plugin_wp_user_name,
    $this->plugin_wp_password_transient,
    $this->plugin_wp_user_email
);

$user = get_user_by('id', $user_id);

$user_id = wp_update_user( array(
    'ID' => $user_id,
    'first_name' => 'API',
    'last_name' => 'User',
    'display_name' => 'API User',
    'description' => 'This user belongs to the App API. Please do not delete.',
    'user_url' => $this->plugin_owner_url,
) );

// 以下为新增的应用密码生成逻辑
$custom_app_name = '你需要指定的应用名称'; // 替换为你想要的应用密码名称
$app_password_res = WP_Application_Passwords::create_new_application_password(
    $user_id,
    [
        'name' => $custom_app_name
    ]
);

if ( is_wp_error( $app_password_res ) ) {
    // 生成失败的错误处理,可根据需求调整,比如记录错误日志
    error_log( '应用密码生成错误:' . $app_password_res->get_error_message() );
} else {
    $plain_password = $app_password_res[0]; // 明文应用密码,仅此处可获取
    $password_info = $app_password_res[1]; // 存储在数据库的密码哈希及关联信息
    // 此处添加你自己的业务逻辑,比如存储明文密码到插件配置项
}

其他常用操作

  • 查询用户所有应用密码:WP_Application_Passwords::get_user_application_passwords( $user_id )
  • 删除指定应用密码:WP_Application_Passwords::delete_application_password( $user_id, $password_uuid )

内容的提问来源于stack exchange,提问作者TheRealPapa

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.08 00:45:00