Roles for Custom Post Types

时间:2013-02-13 作者:Force Flow

我创建了一些自定义帖子类型,但我想在仪表板中对订阅者、作者和编辑器隐藏它们(本质上,只允许管理员访问它们)。

我可以在不安装插件的情况下执行此操作吗?

1 个回复
最合适的回答,由SO网友:Michael Ecklund 整理而成

我相信您可以在注册Post类型本身时指定一些功能。尽管如此,这里有一个更健壮的版本,可以在整个管理仪表板中广泛使用。

/**
 * Hide dashboard administrator menus from disallowed user roles.
 *
 * @author Michael Ecklund
 * @author_url https://www.michaelbrentecklund.com/
 *
 * @return void
 */
function mbe_hide_menus() {

    global $current_user, $menu;

    # Set list of disallowed user roles.
    $disallowed_roles = array( \'subscriber\', \'author\', \'editor\' );
    $disallowed       = false;

    # Check current user role against all disallowed roles.
    foreach ( $disallowed_roles as $disallowed_role ) {

        # Current user role must not be disallowed.
        if ( in_array( $disallowed_role, $current_user->roles ) ) {

            $disallowed = true;// User role disallowed.
            break;

        }

    }

    # User passed the check. Bail before hiding the menu.
    if ( $disallowed === false ) {
        return;
    }

    # Set list of disallowed dashboard administration menus.
    $restricted = array(
        __( \'INSERT MENU NAME HERE\' )// Text as it appears in the admin menu.
    );

    # Attempt to hide admin menus.
    foreach ( $menu as $index => $menu_data ) {

        if ( in_array( $menu_data[0], $restricted ) ) {
            unset( $menu[ $index ] );
        }

    }

}
要启动函数,必须添加操作。

add_action(\'admin_menu\', \'mbe_hide_menus\', 101);
上面的代码只隐藏了显示给用户的管理菜单表单。如果知道正确的URL,他们仍然可以直接访问页面。

您可以使用此选项拒绝特定管理员页面被非特权用户访问。

/**
 * Restrict admin pages from unprivileged users.
 *
 * @author Michael Ecklund
 * @author_url https://www.michaelbrentecklund.com/
 *
 * @return void
 */
function mbe_disallow_admin_pages() {

    global $pagenow;

    # Skip checking administrative users.
    if ( current_user_can( \'administrator\' ) ) {
        return;
    }

    # Set denyable & hookable list of admin pages.
    $page_slugs = apply_filters( \'mbe_disallowed_admin_pages\', array(
        \'admin.php\'           => \'jetpack\',
        \'options-general.php\' => \'\'
    ) );

    # Page parameter isn\'t always present.
    if ( ! isset( $_GET[\'page\'] ) ) {
        $page = \'\';
    }

    # Check current admin page against denied admin page list.
    if ( array_key_exists( $pagenow, $page_slugs ) && in_array( $page, $page_slugs ) ) {
        wp_die( \'You do not have sufficient permissions to access this page.\' );
    }

}
要启动函数,必须添加操作。

add_action( \'admin_init\', \'mbe_disallow_admin_pages\' );

结束