0

I have the ACF custom fields plugin and I am using acf_add_local_field_group to register custom fields via PHP.

When creating a field via PHP I must provide 3 properties:

  • key: ACF unique identifier
  • name: actual property name as contained in post data
  • label: string displayed on the UI

The documentation states the following:

enter image description here

Firstly, the statement about key requiring to start with "field_" seems incorrect as none of my fields key start with "field_" yet they all seem to be working properly, which brings me to 1st question:

Q1: Is the leading "field_" for keys a convention or is it really a working requirement, and if so, what won't work if I don't stick to it?

Secondly, all my fields are setup with repeaters whereby each specific field (eg a name, a URL, an image gallery) is associated with several generic fields to facilitate content management (eg a is_enabled field so I can quickly enable/disable fields without deleting/recreating data, a note field whereby I can provide explanations as to why I disabled something), which brings me to this 2nd question:

Q2: Can I have the same generic fields (eg is_enabled) with identical key/name definition within different field groups & repeaters or should I make their key and/or name unique for each occurrence?

1

Reached out to ACF support, here is what I got:

enter image description here

I've done further experimenting and for Q1 I came up with a recursive function which prepends a prefix to all fields composed of field_ and a custom namespace, that way I can define my ACF fields with simple keys (eg "url") and have them automatically converted to a proper value before the ACF gets generated.

function my_acf_key_prefix(&$value, $key)
{
    if ($key == 'key') {
        $value = 'field_myacf_' . $value;
    }
}
array_walk_recursive($acf_definition, 'my_acf_key_prefix');
acf_add_local_field_group($acf_definition);

For Q2, it turns out there is still an impact of using fields with the same key within repeaters: it's basically the same behaviour as outside repeaters, each field with a given key is assigned a given ACF configuration, this has no impact for fields such as "text" as no processing is done on them, however if you use processed fields with the same key but different config you have an issue (eg if you use multiple "select" fields with the same key but different "choices" config, there is a rendering issue in the UI whereby only 1 field config is applied and thus there is a mismatch in choices rendered).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.