In my last WordPress project, I encountered a situation where the client’s requirement was to set the ACF fields as read-only in the backend as it was getting data from the API. By default, there is no option for adding read-only fields in ACF but after searching for a couple of minutes I encountered a useful ACF hook called load_field, This hook can be used to modify the ACF field options dynamically. By adding minor customizations to it I created a perfect solution to my problem. If you are looking for a similar solution then please feel free to use these short functions to add read-only/disabled ACF fields to your WordPress website.
Note – In both code snippets I have added an If condition so that this code will only work when the user is editing default post types, you can modify this condition to include other custom post types or remove it at all if you want to use it for all post types.
If there is only one ACF field that needs to be converted into a read-only field then the following code snippet can be used.
//Readonly acf fields
add_filter('acf/load_field/name=acf_field_key', 'disable_fields_in_backend');
function disable_fields_in_backend( $field ) {
global $typenow;
if( 'post' === $typenow){
$field['disabled'] = 1;
}
return $field;
}
If there are multiple ACF fields then the following code snippet can be used
//Readonly acf fields
$disabled_fields = [
'acf_field_1_key',
'acf_field_2_key',
'acf_field_3_key',
];
foreach($disabled_fields as $disabled_field){
add_filter('acf/load_field/name='.$disabled_field, 'disable_fields_in_backend');
}
function disable_fields_in_backend( $field ) {
global $typenow;
if( 'post' === $typenow){
$field['disabled'] = 1;
}
return $field;
}
Whether you're facing website issues or struggling with code implementation, our team is here to assist. Hire us to get your website back on track.
Hire Us