增加WordPress的用户角色和等级系统

WordPress本身是没有等级系统的,只是简单的通过权限来划分不同的用户角色,默认的分组如果觉得还不够细致,可以通过代码来添加一些自定义权限的用户组。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
//从官网抄了个
function xx__update_custom_roles() {
//添加一项'custom_roles_version'保证代码只执行一次
if ( get_option( 'custom_roles_version' ) < 1 ) {
//添加‘注册会员’,权限方面完全拷贝“订阅者”。
add_role( 'custom_role', '注册会员', get_role( 'subscriber' )->capabilities );
//自定义权限
//add_role( 'custom_role', '注册会员', array( 'read' => true, 'level_0' => true ) );
//......
//
update_option( 'custom_roles_version', 1 );
}
}
add_action( 'init', 'xx__update_custom_roles' );

很多人还是更喜欢积分系统,根据用户的行为计算积分,然后再根据积分水平来划分等级。

获得积分的方式可以是签到,评论,点赞或者是其他什么操作。举个例子:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
//评论获得积分+15
add_action('comment_post', 'add_point');
function add_point( ){
if ( is_user_logged_in() ) {
//如果是登录用户评论,则获取用户
$current_user = wp_get_current_user();
//查询当前积分点数
$current_point = get_user_meta($current_user->ID, 'point', true);
//+15点积分
$point = intval($current_point)+15;
update_user_meta($current_user->ID, 'point', $point);
}
......
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
//后台显示积分
add_action('show_user_profile','user_point_fields',10,1);
function user_point_fields($profileuser){
$point = get_user_meta($profileuser->ID, 'point', true);
//随便写两句
switch ($point){
case (intval($point)<10):
$level = '小会员';
break;
default:
$level = '大会员';
}
?>

<h3>积分</h3>
<table class="form-table">

<tr>
<th>
<label for="point">我的积分</label></th>
<td>
<p><?php echo $point; ?></p>
</td>
</tr>
<tr>
<th>
<label for="level">我的等级</label></th>
<td>
<p><?php echo $level; ?></p>
</td>
</tr>

</table>
<?php
}

限制仅部分高等级可见:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
//用短代码实现[level_2]大会员可见内容[/level_2]
add_shortcode( 'level_2', 'level_2_only' );
function level_2_only( $atts, $content = "" ) {
if ( is_user_logged_in() ){
$current_user = wp_get_current_user();
$current_point = get_user_meta($current_user->ID, 'point', true);
if(intval($current_point)>10){
return $content;
}
else{
return '大会员限定';
}
}
else{
return '大会员限定';
}

}