0

I want to remove some of the menu links from all users except the administrator. How can I do it?

4
  • You can use Nav Menu Roles plugin. – Ivan Shatsky Jun 24 '20 at 13:29
  • Thank you but it would be better if i could do it with the code. – Mehmet Şar Jun 24 '20 at 13:48
  • You can look how is this plugin work. Its sets a wp_get_nav_menu_items hook. How do you suppose to distinguish the menu items, what to hide and what to show? By their posts ID or by their labels or somehow else? – Ivan Shatsky Jun 24 '20 at 14:38
  • I looked but I did not understand much. Could you share a code block based on roles? – Mehmet Şar Jun 24 '20 at 19:34
0

If you want to exclude menu items by their labels:

function hide_menu_items( $items ) {
    $items_to_exclude = ['Menu Item 1', 'Menu Item 2'];
    if ( !current_user_can( 'manage_options' ) ) foreach ($items as $key => $item) if ( in_array( $item->title, $items_to_exclude ) ) unset( $items[$key] );
    return $items;
}
add_filter( 'wp_get_nav_menu_items', 'hide_menu_items', 20 );
6
  • Thank you. This code sets which user role. – Mehmet Şar Jun 24 '20 at 19:37
  • @MehmetŞar This code assumes that only the administrator has a 'manage_options' capability, which is true by default. Check this article for details. – Ivan Shatsky Jun 24 '20 at 19:42
  • Thank you so much – Mehmet Şar Jun 24 '20 at 20:20
  • @MehmetŞar When you check this code in production, if it would work for you, please mark the answer as accepted. – Ivan Shatsky Jun 24 '20 at 20:39
  • This code doesn't work. There is no change. – Mehmet Şar Jul 1 '20 at 11:36
0

I found the code I was looking for, thank you.


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

global $user_ID;

if ( current_user_can( 'author' ) ) {
remove_menu_page( 'tools.php' );
remove_menu_page( 'edit-comments.php' );
remove_menu_page( 'wpcf7' );
remove_menu_page( 'upload.php' );
remove_menu_page( 'index.php' );
}
}

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.