我如何在仪表板中对非管理员隐藏 WordPress 页面?

How would I hide WordPress pages from non-administrators in the Dashboard?

我需要对非管理员的任何人隐藏 WordPress 页面仪表板中的某些页面,我想限制我的客户编辑它们,因为这些是自动创建的页面(在主题激活时)并且仅用于模板。

这篇文章 here 展示了如何通过 page/post“ID”隐藏页面,但我需要通过页面 slug 来完成,否则每次有人激活我的主题时,他们都必须挖掘页面 ID 以输入 functions.php 文件。

此示例中的 3 个页面的名称或别名分别为 productspolicyservices

下面的代码对我没有任何作用?

add_action('admin_head', 'hide_posts_pages');

function hide_posts_pages() {
    global $current_user;
    wp_get_current_user();
    If($current_user->user_login != 'admin') {
        ?>
        <style>
           slug ==> 'products', slug ==> 'policy', slug ==> 'services', {
                display:none;
           }
        </style>
        <?php
    }
}

~有什么建议吗? 提前致谢!

将以下函数放在 functions.php 中。在 $hidden_slugs 中添加您想隐藏的 slug。我们需要页面 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 仍然可以编辑。某些post的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;

后添加以下内容