i am trying to make a simple custom field (made without a plugin) readonly or disabled for a specific user role in functions.php, is this possible ?
thanks
i am trying to make a simple custom field (made without a plugin) readonly or disabled for a specific user role in functions.php, is this possible ?
thanks
Share Improve this question asked Mar 1, 2020 at 16:07 sofdesignesofdesigne 12 bronze badges 5 |1 Answer
Reset to default 1First, you can get the current user object like so: $user = wp_get_current_user();
.
The $user
object would have a roles
property containing the user's roles, so you can do the following to check if the current user has a specific role: in_array( 'role_slug', $user->roles )
.
And then in your field HTML, you can use the disabled()
and readonly()
functions to easily add the disabled
and readonly
attributes:
<?php
// Get the current user object.
$user = wp_get_current_user();
// Check if the associated user has a specific role.
$has_role = in_array( 'administrator', $user->roles );
?>
<input name="some_name" <?php disabled( true, ! $has_role ); ?> />
<input name="some_name2" <?php readonly( true, ! $has_role ); ?> />
And the above would make the field be disabled/readonly if the current user doesn't have the role administrator
(note the ! $has_role
).
<input>
field? – Sally CJ Commented Mar 1, 2020 at 16:53