Support

Account

Home Forums Front-end Issues Dynamically display all custom fields of a post

Helping

Dynamically display all custom fields of a post

  • Hi!

    I have a pretty large amount of custom fields, that includes galleries, images, repeaters and all the standard fields as well. Number of fields is constantly changing.

    I was wondering, what would be the best way to print all of them? Is there an already made script that would do something like that?

    I tried to write one myself, but it has to be recursive and the associative arrays for each field are not consistent, so it is really difficult to create a generic solution.

  • get_fields() can be used to get all of the field values and then loop over them.

    However, this is not generally usable when fields in a group are changed or if the fields associated with a post can change when updated. The reason for this is that ACF calls get_post_meta() with a post ID and no meta_key. This causes WP to return all of the custom fields for the post. But these fields are returned in the order that they were added to the database ordered by “meta_id”. This means that fields added later will appear later in the returned array and the returned array will not be in the order that the fields appear in the field group, or for that matter, on the post.

    So let’s say that you have 2 fields, “text 1” and “text 2” and they originally appear in this order. When a post is initially created they are saved in this order. If you later change this order in the field group then get_fields() will still return them in this order for older posts while it will return the fields in the new order for posts created after the change was made.

    So, get_fields() is only useful if you don’t care what order the fields are displayed in.

    An alternative would be to call $field_groups = acf_get_field_groups(array('post_id' => $post->ID));. This will return a list of all of the field groups for the post. Then you’d need to loop over the fields in the field groups and then you could possible create some type of dynamic display based on the field type of each of these fields and make it recursive for repeater type fields. This would be a very big task given the possibilities available in ACF. While this is possible, it’s far easier and faster to edit a template to add field display in the order that you want them to be shown.

    I’ve never found any type of dynamic solution for displaying fields because I do not build the admin pages for my clients with the fields in the order I want them displayed. I break up fields using tabs and other features to break up the fields into groups based on what they are for to make is easy for entering data.

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

You must be logged in to reply to this topic.