我有一些自定义角色,例如角色1、角色2、角色3。 另外,我有一些相同名称的帖子标签,例如角色1、角色2、角色3。 现在我想检查每个帖子,用户是否处于相应的角色才能看到它。 编写类似脚本的钩子或入口点是什么?那么哪个操作负责检查某人是否可以查看帖子。 此致 弗罗林
要在 WordPress 中根据用户角色和帖子标签控制帖子可见性,您可以使用
pre_get_posts
操作挂钩(在查询帖子之前触发),或使用 the_posts
过滤器根据自定义逻辑修改帖子列表。
创建自定义角色: 假设您已经创建了自定义角色(
role1
、role2
等)。
为帖子分配标签: 您已为帖子分配了特定标签,如
role1
、role2
等,以匹配自定义角色。
挂钩
pre_get_posts
:
该挂钩允许您在 WordPress 获取帖子之前修改查询。在这种情况下,您可以通过用户的角色和相应的标签来过滤帖子。
将以下代码添加到主题的
functions.php
或作为自定义插件:
function restrict_posts_by_role( $query ) {
// Only modify the main query in frontend and when it's a post query
if ( !is_admin() && $query->is_main_query() && is_post_type_archive('post') ) {
// Get current user roles
$user = wp_get_current_user();
$user_roles = $user->roles;
// Initialize an empty array to hold matching tags
$role_tags = [];
// Map user roles to corresponding tags (custom roles and tags should match)
foreach( $user_roles as $role ) {
if ( in_array( $role, ['role1', 'role2', 'role3'] ) ) {
$role_tags[] = $role; // Add corresponding tag to filter
}
}
// If user has a matching role, modify the query to show only posts with that tag
if ( !empty( $role_tags ) ) {
$query->set( 'tag', implode(',', $role_tags) );
} else {
// If no matching role, prevent posts from showing
$query->set( 'post__in', [0] ); // No posts will be displayed
}
}
}
add_action( 'pre_get_posts', 'restrict_posts_by_role' );
pre_get_posts
: 此挂钩会在 WordPress 检索帖子之前修改帖子查询。wp_get_current_user()
: 检索当前用户及其角色。$query->set('tag', ...)
: 修改查询以仅获取具有与用户角色匹配的标签的帖子。如果您想将没有正确角色的用户重定向到其他页面:
function redirect_unauthorized_users() {
if ( is_single() && ! current_user_can('role1') && ! current_user_can('role2') && ! current_user_can('role3') ) {
wp_redirect( home_url() ); // Redirect to homepage or any URL
exit;
}
}
add_action( 'template_redirect', 'redirect_unauthorized_users' );