Support

Account

Home Forums Feedback update_field() clarification Reply To: update_field() clarification

  • I have seen issues on and off when using the field name in the past, for this reason I haven’t actually used a field name for update_field() in a very long time and I always use the field keys. It just avoids any potential issues and me needing to dig around in code and figure out why it’s not working in some specific case. I just include comments in my code about what field key belongs to what field name.

    I’ve also done things like set up arrays

    
    $fields = array(
      "{$field_name}" => "{$field_key}"
    )
    

    So that I can refer to the field name like

    
    update_field($fields[$field_name], $value, $post_id);
    

    As far as I’m aware, and I’ve looked into the code of ACF and I don’t see anything that suggests otherwise, if you use update_field() with a field name and the meta_key "_{$field_name}" does not exist for $post_id then ACF will not create the correct field reference. It will create the meta_key "_{$field_name}", but this entry in the database will have an empty field value rather than containing the correct field key.

    Under these conditions, some fields will work and some fields will not work. It really depends on the field type and how the data is stored. It can really be hit or miss. In the case of fields that contain text, or something that is simple text, and this includes a date/time field, acf will simply return whatever text value is stored in the database. The reason for this is that without the correct field key ACF does not know what to do about formatting the value so it just assumes it’s a text based field.

    Rather than figure it out on a field-by-field basis whether you can use the field name or need to use the field key, it’s just simpler to always use the field key.