将以下函数放在您的 functions.php 中。在$hidden_slugs 添加你想隐藏的蛞蝓。我们需要页面 id 来过滤它们。使用get_page_by_path 有助于根据 slug 查找 id。
具有能力的解决方案 1:
add_filter('parse_query', 'hide_pages_by_slug_if_not_admin');
function hide_pages_by_slug_if_not_admin($query) {
if(!is_admin()) return;
if( is_admin() && current_user_can('manage_options')) {
return;
} else {
// Create array of all the slugs you wanna hide
$hidden_slugs = array( 'products', 'policy','services');
// Loop through slugs & pass each slug as page path value
foreach ($hidden_slugs as $hidden ) {
$hidden_slugs[] = get_page_by_path( $hidden )->ID;
// In case you need to hide the home page too uncomment
//$hidden_slugs[] += get_option('page_on_front');
}
$query->query_vars['post__not_in'] = $hidden_slugs;
}
}
具有用户角色的解决方案 2:
add_filter('parse_query', 'hide_pages_by_slug_if_not_admin');
function hide_pages_by_slug_if_not_admin($query) {
if(!is_admin()) return;
$user = wp_get_current_user(); // Current user
$allowed_roles = array('administrator'); // Allowed roles
if( is_admin() && array_intersect($allowed_roles, $user->roles ) ) {
return;
} else {
// Create array of all the slugs you wanna hide
$hidden_slugs = array( 'products', 'policy','services');
// Loop through slugs & pass each slug as page path value
foreach ($hidden_slugs as $hidden ) {
$hidden_slugs[] = get_page_by_path( $hidden )->ID;
// In case you need to hide the home page too uncomment
// $hidden_slugs[] += get_option('page_on_front');
}
// Pass the array as value to the query vars filter
$query->query_vars['post__not_in'] = $hidden_slugs;
}
}
请记住,这不会阻止他们进行编辑。如果有权编辑页面的人只需输入 url wp-admin/post.php?post=postID&action=edit 仍然可以进行编辑。可以通过多种方式找到某个帖子的 ID。
以下是一种快速解决方案,您可以使用它来防止编辑这些页面:
// Prevent access to restricted pages
if(isset($_GET['post'])) {
$current_postID = $_GET['post'];
if (in_array($current_postID, $hidden_slugs)) {
$url= admin_url().'edit.php?post_type=page';
wp_redirect($url);
exit;
}
}
在$query->query_vars['post__not_in'] = $hidden_slugs;之后添加以下内容