Support

Account

Home Forums ACF PRO acf/load_field add data attribute to field

Solving

acf/load_field add data attribute to field

  • Hi all,

    So I am trying to add a data attribute field to a specific textarea. I have managed to get the filter acf/load_field running and add data to the field object.

    
    public function addDataAttributeToAcfTextarea($field) {
            // Add custom class
            $field['class'] .= ' MyCustomClass';
    
            // Add 'data-any-type' attribute
            $field['data-code-type'] = 'whatever';
    
            // echo '<pre>';
            // print_r($field);
            // echo '</pre>';
    
            return $field;
        }
    

    But the result:

    
    <textarea id="acf-field_445545544" class="MyCustomClass" name="acf[acf-field_445545544]" rows="35">Some content</textarea>
    

    Desired the result:

    
    <textarea id="acf-field_445545544" class="MyCustomClass" name="acf[acf-field_445545544]" rows="35" data-code-type="whatever">Some content</textarea>
    

    Perhaps I am missing something?

    Greetz,
    Walter

  • You cannot add arbitrary attributes to an ACF fields that will be added when the field is rendered. Any attribute not already present in the $field array is simply ignored.

  • Is there a specific reason, why this is not possible/has been implemented?
    Could we filter the generated html before it is returned?

  • Hello again. Any feedback to this? Thanks!

  • I am not a developer of ACF. I cannot answer your questions. You would need to contact the developers. The developers do not monitor this forum.

    My guess is that they are not going to allow filtering of the form field itself or adding arbitrary attributes.

    My suggestion would depend on what you need that attribute for, what are you trying to do?

  • I try to add a uuid entry per field.

    In the front end I add this data attribute via JS if not present.
    When saving the form I would like to check for data-uuid, if present I’ll save it.

    Maybe there is a better approach for that?

  • Sorry, but that doesn’t help me. I haven’t got a clue what it means to or why you would want to add a uuid value to every field or how you would check for it or why you would need to do so using ACF.

Viewing 7 posts - 1 through 7 (of 7 total)

You must be logged in to reply to this topic.