On content-driven websites, it is common to have some material that should only be visible to users with a certain membership level, such as VIP users. Programmatically, that logic is straightforward: check the current user’s role or capability, and if the user qualifies, show the content; otherwise, hide it.
WordPress already has a solid role and capability system, along with convenient APIs for creating custom roles and capabilities. This article shows a simple way to create a VIP role and then restrict some content so only that role can view it.
Create a VIP role by copying an existing role
WordPress lets us create an entirely new role from scratch, but it also lets us build a new role based on an existing one. Since the role we need is only a slight variation of an existing default role, it is convenient to copy the subscriber role and extend it.
// 新建VIP用户角色
add_action( 'admin_init', 'remove_shop_caps');
function remove_shop_caps() {
// 首先获取订阅者角色。
$subscriber = get_role('subscriber');
// 然后基于订阅者角色的权限新建一个角色。
$vip = add_role('vip','VIP用户',$subscriber->capabilities);
$vip = get_role('vip');
// 移除新角色的一些不需要的权限
$vip->add_cap( 'read_vip_content' );
}
After adding that code to the theme’s functions.php file, the new VIP role appears in the user-editing screen in the dashboard.
Create a shortcode for VIP-only content
Once the role exists, the next step is to create a mechanism for content that only VIP users can read. In the example below, a shortcode is used for that purpose.
/* 设置VIP可以阅读的简码 */
if ( ! function_exists( 'shortcode_vip_content' ) ) {
function shortcode_vip_content( $atts ) {
$default = array(
'content' => 'VIP用户可以查看的内容。',
);
extract( shortcode_atts( $default, $atts ) );
if ( current_user_can('read_vip_content') ){
$retour = $content;
} else {
$retour = "你不是VIP,你不能查看这些内容。";
}
return $retour;
}
}
add_shortcode( 'vip_content', 'shortcode_vip_content' );
With that in place, content can be protected by inserting a shortcode such as [vip_content content="Only VIP users can read this."] into a post. The text becomes visible to VIP users and hidden from everyone else.
If you want to make this workflow easier for editors, you can also build a shortcode UI in the post editor with a tool such as Shortcake, though that goes beyond the scope of the original article.
