Fix for Displaying Fields According to Field Order (using get_field_objects)
-
The Problem
This plugin currently allows for you to update the field order via the drag & drop reordering in the site admin, but that then doesn’t have any effect on the order of the fields being displayed which have content entered in prior to the reordering. This is the case even when using the built-in get_fields() and get_field_objects() functions as it appears they do not retrieve the fields by the field order (order_no) that’s specified.The Fix/Workaround
We need to use get_field_objects() to retrieve the full field data, sort that field array by the order_no value, and then use that to display the fields.Here’s an example which gets the fields for a post and displays any fields that have a value in the field order that’s set in the site admin:
$fields = get_field_objects($post->ID); if( !empty($fields) ){ uasort($fields,'compareOrderNo'); // compareOrderNo is located in functions.php echo '<dl>'; foreach( $fields as $field ){ if($field['value'] != ''){ if($field['label'] != ''){ echo '<dt class="label">'.$field['label'].'</dt>'; } if($field['value'] != ''){ echo '<dd class="value">'.$field['value'].'</dd>'; } } } echo '</dl>'; }
This code uses a custom compareOrderNo() function which I’ve added to the site’s functions.php file:
function compareOrderNo($elem1, $elem2) { return strcmp($elem1['order_no'], $elem2['order_no']); }
I’d love to see this behavior (display fields by the field order that’s currently set) officially adopted by the get_fields() and/or get_field_objects() functions. I’d be happy if it was an option; if not the default behavior.
I’ve gone ahead and also posted it on the official ACF support forums so others can find this: https://support.advancedcustomfields.com/forums/topic/fix-for-displaying-fields-according-to-field-order-using-get_field_objects/
- The topic ‘Fix for Displaying Fields According to Field Order (using get_field_objects)’ is closed to new replies.