2

I want to hide the add new page button from users that are not administrators. I managed to hide the submenu item from the right column like this:

$page = remove_submenu_page( 'edit.php?post_type=page', 'post-new.php?post_type=page' );

I tried to hide the button in the page with css proposed in this question but didn't work. How I can achieve that? Here is my -failed- attempt:

if (isset($_GET['post_type']) && $_GET['post_type'] == 'page') {
            echo '<style type="text/css">
            #favorite-actions, .add-new-h2, .tablenav { display:none; }
            </style>';
        }
1

This can be achieved easy enough with just CSS. First we are going to add a function that will output a class to the body tag based on what role the user is. Then we will enqueue a stylesheet to show up in the admin. Then use the class in the body to target and hide the button.

Add Body Class Based on User Role - Add to functions.php

function custom_role_admin_body_class( $classes ) {
    global $current_user;
    foreach( $current_user->roles as $role )
        $classes .= ' role-' . $role;
    return trim( $classes );
}
add_filter( 'admin_body_class', 'custom_role_admin_body_class' );

Enqueue Admin Styles - Add to functions.php

function custom_admin_styles(){
    wp_enqueue_style(
        'admin_css', 
        get_stylesheet_directory_uri() . '/css/admin-styles.css', array(), filemtime( get_stylesheet_directory() . '/css/admin-styles.css') 
    );
}
add_action('admin_enqueue_scripts', 'custom_admin_styles');

Use Body Class to Hide Button for NON admin users

body.edit-php.post-type-page:not(.role-administrator) .page-title-action {
    display: none;
}
  • I added these lines in functions.php and created a new file css/admin-styles.css for the third code snippet but didn't work – aggtr Dec 17 '18 at 14:38
  • Can you tell me where exact I create the admin-style.css? Probably I ve put in in wrong directory thats why is not working.... I've tested it under wp-content/themes/my_theme/css/ and under wp-admin/css/ – aggtr Dec 17 '18 at 14:55
  • hmmm no its not there... doesn't show up in source – aggtr Dec 17 '18 at 15:00
  • if you inspect the page (f12) are you getting a 404 error? find the stylesheet in the inspector and clikc the link – RiddleMeThis Dec 17 '18 at 15:01
  • ok thank you! it was a typo :( . Thank you very much for your effort and time. I appreciate it – aggtr Dec 17 '18 at 15:04
1

install User Role Editor this plugin that will give you the option to hide options by user roles and let me know this works or not so i can give another option to do it.

  • 1
    I would like to do it without using a plugin. is that possible? – aggtr Dec 17 '18 at 11:31

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.