Search code examples
wordpress

how to remove/hide wordpress menu from admin dashboard for specific users


I'm using this to hide menu items for a specific user. What's the best way to do this for more than one user using the id.

add_action( 'admin_init', 'remove_menu_pages_for_user' );
function remove_menu_pages_for_user() {

if (get_current_user_id() == 1) {
    //remove_menu_page( 'index.php' );              //Dashboard
    remove_menu_page( 'edit.php' );                 //Posts
    remove_menu_page( 'upload.php' );               //Media
    remove_menu_page( 'edit.php?post_type=page' );  //Pages
    remove_menu_page( 'edit-comments.php' );        //Comments
    remove_menu_page( 'themes.php' );               //Appearance
    remove_menu_page( 'plugins.php' );              //Plugins
    remove_menu_page( 'users.php' );                //Users
    remove_menu_page( 'tools.php' );                //Tools
    remove_menu_page( 'options-general.php' );      //Settings
}
}

This code works for user 1 but need to add one or 2 additional users.


Solution

  • You can do this by getting current user id and then check if that user exsists in array we have created.

    so you just need to replace

    if (get_current_user_id() == 1) {
    

    with

     $user_ids = array( 1, 2, 3 ); //here you can replace 1,2,3 as per the User ID for which you want to remove menu.
     $current_user_id = get_current_user_id();
     if ( in_array( $current_user_id, $user_ids ) ) {
    

    It should works for you.