Home › Forums › General Issues › What's the best way to get the fields in a group in order, for display?
Hi there,
I’ve set up a post type where the site users can add and remove fields at will, as well as change the order (by editing the field group).
I’m trying to display these fields on the front end, in the same order in which they appear in the admin, which is determined by dragging and dropping when editing the field group.
However, when I use get_field_objects()
, the fields are returned in some other order. What’s the best way to get the list as it appears when editing the field group?
Well, after posting (isn’t it how this always works?) I figured out the brute force way to do it. It would be great if there were a function for this.
// get the list of fields in order.
$args = array(
'post_type' => 'acf-field',
'post_parent' => $group_id, // field group
'posts_per_page' => 100,
'orderby' => 'menu_order',
'order' => 'ASC'
);
$all_fields = new WP_Query($args);
$fieldnames = array();
if ($all_fields->have_posts()){
foreach($all_fields->posts as $f){
$fieldnames[] = $f->post_excerpt;
}
}
// get the fields
$fields = get_field_objects();
if( $fields )
{
foreach($fieldnames as $fn){
if (isset($fields[$fn])){
$field = $fields[$fn];
if ($field['value'] == '') continue;
/* do stuff */
}
}
}
Since you posted that the post type is acf-field
that tells me that your using ACF5, because 4 did not use separate fields.
I’m not sure that your query will deal with nested fields, like repeaters or flexible content.
ACF does have a function you can use to get all the field objects, as well as nested field objects that will return the fields in the same format as what is output when you export a field group to PHP.
$fields = acf_get_fields($group_key);
echo '<pre>'; print_r($fields); echo '</pre>';
Ah, good ol’ undocumented functions. Thanks for the reference, that’s going to help a lot.
Hmm. How do I unmark my solution so I can flag yours?
It’s more of an internal function that ACF uses. Not documented only because it would not be used by most theme developers.
The topic ‘What's the best way to get the fields in a group in order, for display?’ is closed to new replies.
Welcome to the Advanced Custom Fields community forum.
Browse through ideas, snippets of code, questions and answers between fellow ACF users
Helping others is a great way to earn karma, gain badges and help ACF development!
We use cookies to offer you a better browsing experience, analyze site traffic and personalize content. Read about how we use cookies and how you can control them in our Privacy Policy. If you continue to use this site, you consent to our use of cookies.