(WP) Hide Admin Menu & Restricted Access Based On

2019-08-04 11:08发布

问题:

I want to hide admin menu and restricted access on that page for Wordpress. For hide administration menu, I've done it. Here is example code:

add_action( 'admin_init', 'my_remove_menu_pages' );

function my_remove_menu_pages() {
    // If the user does not have access to publish posts
    if(!current_user_can('manage_options')) {
        remove_menu_page('tools.php');
    }
}

I'm create new user role, for example is image_uploader. How can I do to restricted access on page that related to admin menu that I've hide based on user role? At now, it's just hide admin menu and not restricted, that mean, user who keep link will get access of that page. And this code not specific to user role, but specific to user capabilities.

What I want is hide and restricted menu and page based on specific user role. How can I do?

回答1:

You can use the hook load-$page, like:

# /wp-admin/$page.php
$pages = array( 'profile', 'tools' );

foreach( $pages as $page )
    add_action( "load-$page.php", 'block_user_so_23568456' );

function block_user_so_23568456()
{
    $user = get_userdata( get_current_user_id() );

    # Send this user role to the Dashboard /wp-admin/index.php
    if ( in_array( 'image_uploader', $user->roles ) ) 
    {
        wp_redirect( admin_url() );
        exit();
    }
}


标签: wordpress