How to Restrict Admin Menu Items by Username in WordPress

Home » Snippets » How to Restrict Admin Menu Items by Username in WordPress
0

Created with:

Visibility: 

public

Creator: WPTurbo Team

Customize with WPTurbo AI
X

Add Snippet To Project

New Project
Add To Existing Project

Are you managing a WordPress site with multiple users and want to restrict access to certain menu items in the admin dashboard based on their username? This can be an important security measure to ensure only authorized users have access to sensitive areas of the site. In this article, we’ll explore a simple way to restrict admin menu items by username using a code snippet. Let’s dive in and learn how to implement this solution on your WordPress site.

					function wpturbo_restrict_admin_menu_items() {
	$user = wp_get_current_user();
	if ( $user->user_login == 'username_to_restrict' ) {
		remove_menu_page( 'menu_slug_to_remove' );
	}
}
add_action( 'admin_menu', 'wpturbo_restrict_admin_menu_items' );
				

This code snippet shows you how to restrict specific admin menu items based on the username of the current user.

First, we define a function called wpturbo_restrict_admin_menu_items(). Within this function, we use the WordPress function wp_get_current_user() to retrieve information about the current user who is logged in.

Next, we use an if statement to check if the user login matches the username that we want to restrict access for. This username can be replaced with the desired username in the code.

If the condition is met and the username matches, then we remove the menu item using the remove_menu_page() function. This function takes the menu_slug as a parameter and removes the corresponding menu item from the admin menu.

The remove_menu_page() function must be hooked into the admin_menu action hook, which happens after the admin menu has been generated by WordPress.

By using this code, you can restrict access to certain admin menu items for specific users. It is useful for limiting access to certain pages or settings that should only be available to certain users.

Register an account to save your snippets or go Pro to get more features.