Home › Forums › Backend Issues (wp-admin) › Set fields to readonly based on user-role in wp-admin
Hi!
For a tracking system i use a custom-post-type and acf-fields. The user with the user-role “shop-manager” should be able to create a new custom-post and set all the acf-fields. After he saved the custom-post, the user should not be able to edit any of the acf-fields in the backend.
I was looking for a solution everywhere but couldnt find one. Is this even possible?
Thx for your help and best regards.
It is not possible to set every field type in ACF to read only, at least I’m pretty sure that it’s not possible. It really depends on the type of field it is. The fields types that use Select2 are the most problematic.
If it can be done you would do this using a prepare field filter on each field https://www.advancedcustomfields.com/resources/acf-prepare_field/. In this filter you would need to see if the post is a new post of not (post_type = “auto-draft”) and then you’d need to check the user role. Depending on these, some of the fields can be set to read only by
$field['readonly'] = 1;
Some fields you’d need to use the disabled propery
$field['disabled'] = 1;
and some fields you’d need to research and probably us custom javascript. I don’t begin to know how to do this with the select2 fields.
Hi John
Thanks for your help. Sorry but i dont know how to use this acf-prepare_field for a specific field to set it read-only. Can you give me an example? Do i need the field key?
I can give you a basic example
add_filter('acf/prepare_field/key=field_123abc456
, ‘maybe_set_readonly’);
function maybe_set_readonly($field) {
// check post type to see if it’s a new post
global $post
$new_post = true
if (get_post_type($post->ID)) != ‘auto-draft’) {
// this is not a new post
$new_post = false;
}
// check current user role
// I really don’t know off the top of my head how to check this
// if conditions are not met to allow editing
// set field to readonly
if (your conditions here) {
$field[‘readonly’] = 1;
}
return $field;
}
`
You must be logged in to reply to this topic.
Welcome to the Advanced Custom Fields community forum.
Browse through ideas, snippets of code, questions and answers between fellow ACF users
Helping others is a great way to earn karma, gain badges and help ACF development!
🤔 Curious about the ACF user experience? So are we! Help guide the evolution of ACF by taking part in our first ever Annual Survey and guarantee you’re represented in the results. https://t.co/0cgr9ZFOJ5
— Advanced Custom Fields (@wp_acf) May 8, 2023
© 2023 Advanced Custom Fields.
We use cookies to offer you a better browsing experience, analyze site traffic and personalize content. Read about how we use cookies and how you can control them in our Cookie Policy. If you continue to use this site, you consent to our use of cookies.