WordPress插件开发:用户/角色/权限

2025-10-29 69
WordPress

类型:CMS系统

简介:一款开源的内容管理系统(CMS),用于构建和管理网站。

用户名、密码和邮箱组成一个WordPress用户,一般存储在wp_user数据表中。WordPress支持给不同用户分配不同额角色和权限,同时支持创建一些自定义权限分配给不同的用户。本教程详细介绍了WordPress插件开发中用户、角色和能力的管理方法。

一、WordPress用户管理

1、添加用户

我们可以使用wp_create_user()或wp_insert_user()函数添加WordPress用户。其中wp_create_user()就是常规的通过用户名、密码和邮箱创建;wp_insert_user()则通过描述用户及属性的数组或对象进行创建。

2、创建用户

wp_create_user(
string $username,
string $password,
string $email = ''
);

以上函数使用 wp_slash() 转义参数,使用 compact() 函数把上面的值创建为数组,然后使用 wp_insert_user() 函数将用户数据插入到到数据库中。

3、创建WordPress用户的示例

// check if the username is taken
$user_id = username_exists($user_name);

// check that the email address does not belong to a registered user
if (!$user_id && email_exists($user_email) === false) {
// create a random password
$random_password = wp_generate_password(
$length = 12,
$include_standard_special_chars = false
);
// create the user
$user_id = wp_create_user(
$user_name,
$random_password,
$user_email
);
}

4、插入用户:

wp_insert_user(
array|object|WP_User $userdata
);

以上函数为大部分预定义属性添加了 Filter 钩子,创建用户的时候(参数中没有 ID),执行 user_register Action 钩子,更新用户的时候(参数中有用户 ID),执行 profile_update Action 钩子。

5、插入用户示例

以下示例展示了插入WordPress用户并添加资料的流程:

$username = $_POST['username'];
$password = $_POST['password'];
$website = $_POST['website'];
$user_data = [
'user_login' => $username,
'user_pass' => $password,
'user_url' => $website,
];

$user_id = wp_insert_user($user_data);

// success
if (!is_wp_error($user_id)) {
echo 'User created: ' . $user_id;
}

6、更新用户

在更新数据库中的某一个用户是,可以通过$userdata数据/对象中传递,若需要更新用户的元数据,可以使用update_user_meta()函数。需要注意的是,如果更新了某个用户的密码,Cookies 会被清除,该用户需要重新登录。

wp_update_user(
mixed $userdata
);

7、更新用户示例

$user_id = 1;
$website = 'https://wordpress.org';

$user_id = wp_update_user(
[
'ID' => $user_id,
'user_url' => $website,
]
);

if (is_wp_error($user_id)) {
// error
} else {
// success
}

8、删除用户

WordPress中的用户被删除后会自动执行deleted_user钩子。可以选择把用户创建的内容重新分配给其他用户。如果没有设置$reassign参数,或者该参数不是一个有效的用户ID,被删除用户创建的所有内容也会被删除。

wp_delete_user(
int $id,
int $reassign = null
);

二、WordPress用户元数据

WordPress中的user数据中包含了用户的基本信息,我们可以在wp_usermeta数据表中存储任意多的用户数据。这个表使用用户 ID 字段和 wp_user 数据表关联。

目前可以使用以下两种方法操作WordPress用户元数据:

  • 通过个人资料编辑界面中的表单;
  • 通过程序的方式使用相关函数操作。

1、通过表单字段

此方法适合可以访问WordPress管理界面的情况,过程中涉及两个钩子:

  • edit_user_profile:用户编辑自己的配置文件会触发;
  • show_user_profile:用户编辑其他人的用户资料会触发。

示例:在用户资料编辑界面天开一个生日选项,并在用户更新资料室保存到数据库:

<?php
/**
* The field on the editing screens.
*
* @param $user WP_User user object
*/
function wporg_usermeta_form_field_birthday($user)
{
?>
<h3>It's Your Birthday</h3>
<table class=form-table>
<tr>
<th>
<label for=birthday>Birthday</label>
</th>
<td>
<input type=date
class=regular-text ltr
id=birthday
name=birthday
value=<?= esc_attr(get_user_meta($user->ID, 'birthday', true)); ?>
title=Please use YYYY-MM-DD as the date format.
pattern=(19[0-9][0-9]|20[0-9][0-9])-(1[0-2]|0[1-9])-(3[01]|[21][0-9]|0[1-9])
required>
<p class=description>
Please enter your birthday date.
</p>
</td>
</tr>
</table>
<?php
}

/**
* The save action.
*
* @param $user_id int the ID of the current user.
*
* @return bool Meta ID if the key didn't exist, true on successful update, false on failure.
*/
function wporg_usermeta_form_field_birthday_update($user_id)
{
// check that the current user have the capability to edit the $user_id
if (!current_user_can('edit_user', $user_id)) {
return false;
}

// create/update user meta for the $user_id
return update_user_meta(
$user_id,
'birthday',
$_POST['birthday']
);
}

// add the field to user's own profile editing screen
add_action(
'edit_user_profile',
'wporg_usermeta_form_field_birthday'
);

// add the field to user profile editing screen
add_action(
'show_user_profile',
'wporg_usermeta_form_field_birthday'
);

// add the save action to user's own profile editing screen update
add_action(
'personal_options_update',
'wporg_usermeta_form_field_birthday_update'
);

// add the save action to user profile editing screen update
add_action(
'edit_user_profile_update',
'wporg_usermeta_form_field_birthday_update'
);

2、通过编程的方式

通过编程的方式管理WordPress用户的元数据比较适合构建自定义用户资料界面的情况,例如正打算禁用用户访问WordPress管理界面的情况下。一般使用add_user_meta(), update_user_meta(), delete_user_meta() 和 get_user_meta()函数用户。

添加:

add_user_meta(
int $user_id,
string $meta_key,
mixed $meta_value,
bool $unique = false
);

更新:

update_user_meta(
int $user_id,
string $meta_key,
mixed $meta_value,
mixed $prev_value = ''
);

删除:

delete_user_meta(
int $user_id,
string $meta_key,
mixed $meta_value = ''
);

获取:

get_user_meta(
int $user_id,
string $key = '',
bool $single = false
);

注意:如果仅传递 $user_id 参数给该函数,该函数将获取该用户的所有元数据为一个关联数组。

三、WordPress角色和权限

WordPress角色和权限一般存储在wp_options数据据表中的user_roles字段中。

1、WordPress角色

一般情况下WordPress有以下7个角色:

  • SEO Editor
  • SEO Manager
  • Translator
  • Custom Permalinks Manager
  • 订阅者
  • 贡献者
  • 作者
  • 编辑
  • 管理员

我们可以添加或删除角色:

WordPress插件开发:用户/角色/权限

2、添加角色

在WordPress中添加角色一般使用add_role()函数。注意第一次调用此函数时,角色和他的能力将被存储在数据库中,且无法控制该函数的调用顺序,包括替换能力列表。

function wporg_simple_role() {
add_role(
'simple_role',
'Simple Role',
[
'read' => true,
'edit_posts' => true,
'upload_files' => true,
]
);
}

// add the simple_role
add_action( 'init', 'wporg_simple_role' );

3、删除角色

在WordPress中删除角色可以使用remove_role()函数,还是一样,第一次调用该函数后,角色及其能力将从数据库中被删除。

function wporg_simple_role_remove() {
remove_role( 'simple_role' );
}

// remove the simple_role
add_action( 'init', 'wporg_simple_role_remove' );

建议不要删除管理员和超级管理员角色,确保将代码保留在插件/主题中,因为未来的 WordPress 更新可能会再次添加这些角色。如果我们删除了 Subscriber 这个 WordPress 角色,需要运行 update_option(‘default_role’, YOUR_NEW_DEFAULT_ROLE) 设置新的默认角色。

4、添加权限

get_role()函数可以获取角色对象,再使用add_cap()函数为角色添加新权限。

function wporg_simple_role_caps() {
// gets the simple_role role object
$role = get_role( 'simple_role' );

// add a new capability
$role->add_cap( 'edit_others_posts', true );
}

// add simple_role capabilities, priority must be after the initial role definition
add_action( 'init', 'wporg_simple_role_caps', 11 );

5、删除权限

使用remove_cap()函数可以从角色中移除某个能力。该实现类似于添加能力。

6、获取角色

get_role()函数主要用来获取角色对象,包括其所有权限。

get_role(
string $role
);

使用get_role()函数可以检查用户是否具有指定的角色或权限。

user_can(
int|object $user,
string $capability
);

使用current_user_can()函数可以判断当前登录用户的权限:

if (current_user_can('edit_posts')) {
edit_post_link('Edit', '<p>', '</p>');
}

如果是多站点的情况下需要判断当前登录用户的权限可以使用current_user_can_for_blog()函数:

current_user_can_for_blog(
int $blog_id,
string $capability
);
  • 广告合作

  • QQ群号:4114653

温馨提示:
1、本网站发布的内容(图片、视频和文字)以原创、转载和分享网络内容为主,如果涉及侵权请尽快告知,我们将会在第一时间删除。邮箱:2942802716#qq.com(#改为@)。 2、本站原创内容未经允许不得转裁,转载请注明出处“站长百科”和原文地址。