customization - how to make a custom field readonly or disabled by user role?

i am trying to make a simple custom field (made without a plugin) readonly or disabled for a specific user role in funct

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
  • By "custom field", you mean an <input> field? – Sally CJ Commented Mar 1, 2020 at 16:53
  • yes please, thanks – sofdesigne Commented Mar 1, 2020 at 17:28
  • And are you referring to the current user? If not, can add your code to the question? – Sally CJ Commented Mar 1, 2020 at 17:37
  • yes the current user with a specific role, can just view the field content, not able to change it, but the admin can – sofdesigne Commented Mar 2, 2020 at 9:11
  • I posted an answer. Let me know. – Sally CJ Commented Mar 2, 2020 at 9:39
Add a comment  | 

1 Answer 1

Reset to default 1

First, 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).

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744702851a4588875.html

相关推荐

  • customization - how to make a custom field readonly or disabled by user role?

    i am trying to make a simple custom field (made without a plugin) readonly or disabled for a specific user role in funct

    1天前
    30

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信