Easiest way to make ACF field readonly

Sometimes we need to restrict ACF field editing, but allow viewing it value (readonly). For example, we have cron job which update field value. To keep value correct we can allow admin only to view it, but not edit.

For this purpose, we will use one of acf/load_field filters.

Function for changing ACF field readonly values

First we need to write a function which will change given field array element value. Function must set value 1 for array element where key is ‘readonly’ and return array back.

function acf_read_only($field) {
	$field['readonly'] = 1;
	return $field;
}

Now we must hook this function to specific filter action using add_filter function.

Hooking ACF filter

Advanced custom fields has four ways to hook into fields.

  1. acf/load_field – hook every field.
  2. acf/load_field/type={$field_type} – hook only specific type field.
  3. acf/load_field/name={$field_name} – hook field by name.
  4. acf/load_field/key={$field_key} – hook field by key value.

I chose to use acf/load_field/key={$field_key} filter, because we changing parameter only for one field. In my particular situation field key is field_5b3a30ca02e47. So we need to hook ‘acf_read_only’ function to acf/load_field/key=field_5b3a30ca02e47 filter using add_filter function.

add_filter('acf/load_field/key=field_5b3a30ca02e47', 'acf_read_only');

Final code

add_filter('acf/load_field/key=field_5b3a30ca02e47', 'acf_read_only');
function acf_read_only($field) {
	$field['readonly'] = 1;
	return $field;
}