How to Disable Password Fields for Non-Admins in WordPress

Home » Snippets » How to Disable Password Fields for Non-Admins 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

Security is a top concern for any website, and one way to enhance it is by limiting access to sensitive areas. In this case, we’ll focus on disabling password fields for non-admin users. By doing this, you can prevent unauthorized access to user passwords and improve your site’s security. In this article, we’ll show you how to disable password fields for non-admin users in WordPress.

					function WPTurbo_disable_password_fields(){
	if ( ! current_user_can( 'manage_options' ) ) {
		echo '<style>#pass1,#pass2{display:none;}</style>';
	}
}
add_action( 'admin_head-user-new.php', 'WPTurbo_disable_password_fields' );
add_action( 'admin_head-user-edit.php', 'WPTurbo_disable_password_fields' );
				

The purpose of this code snippet is to disable the password fields in WordPress user profile forms for non-administrator users. This can be useful in scenarios where the administrator wants to restrict access to user passwords.

First, we define a function called WPTurbo_disable_password_fields(). The function uses the current_user_can() function to check if the current user has the 'manage_options' capability, which is a capability assigned only to administrators.

If the current user does not have the 'manage_options' capability, we use the echo statement to output some CSS code that hides the password fields from the user profile form.

if ( ! current_user_can( 'manage_options' ) ) {
    echo '<style>#pass1,#pass2{display:none;}</style>';
}

The password fields in WordPress user profile forms have ID attribute values of "pass1" and "pass2". We use CSS to hide these fields by setting their display to none.

Finally, we use the add_action() function to hook our WPTurbo_disable_password_fields() function into the admin_head-user-new.php and admin_head-user-edit.php actions. This ensures that our function is executed when the user profile form is displayed in the WordPress admin panel.

By doing this, the password fields will be hidden for users who are not administrators.

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