在 WordPress/WooCommerce 中,我有一个使用用户角色的网上商店,根据这些角色,您可以看到不同的页面/产品。
我想要做的是添加一种方法,允许某些用户角色临时查看与其他用户角色相同的内容。
比方说,我有 4 个不同的用户角色:
- 管理员
- 高级成员(member)
- 标准成员(member)
- 默认成员(member)
我是否可以制作(比方说一个按钮),当按下时,将向“默认成员(member)”显示受限制的内容,以使其像“高级成员(member)”一样查看?
我最好不要永久更改用户的角色,然后再将其更改回来。这在某种程度上是可能的吗?
谢谢
最佳答案
是的,如果您在页面模板中为现有用户角色 View (或显示)条件添加OR
条件,这是可能的。此条件将基于用户元数据中设置的自定义字段。
因此,当您单击该“按钮”时,它将更新用户自定义字段的值,并允许显示“高级内容”(例如)。为此,您可以使用 get_user_meta()
和 update_user_meta()
WordPress 函数。
首先在 php 文件或模板的开头定义这 2 个变量:
// Getting the user iD
$user_id = get_current_user_id();
// Looking if our user custom field exist and has a value
$custom_value = get_user_meta($user_id, '_custom_user_meta', true);
那么你的情况会有点像:
if($user_role == 'premium' && $custom_value){
// Displays the premium content
}
现在,当按下“按钮”时,它会将 $custom_value 更新为 true,从而允许该用户在提交表单时看到优质内容(或使用 ajax)。
因此,您必须将此代码放在上面的 2 个变量之后:
if('yes' == $_post['button_id']){
// $custom_value and $user_id are already defined normally (see above)
if($custom_value){
update_user_meta($user_id, '_custom_user_meta', 0); // updated to false
} else {
update_user_meta($user_id, '_custom_user_meta', 1); // updated to true
}
}
这应该有效......
Update (based on your comment)
Alternatively, for The Admin as in your comment, You can target
'administrator'
user role in your condition AND (&&
) a special cookie that will be set by your "button". This way you will not have to use a custom field.
关于php - 暂时允许某些用户角色观看某些受限制的内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41826055/