I am using Avanced custom fields to output some extra data to each post. I am doing it by adding this to the post.php file in wordpress:
<ul>
<?php foreach( $fields as $field ): ?>
<?php if( $field['value'] ): ?>
<li><?php echo $field['label']; ?>: <div class="new_color_test"> <?php echo $field['value']; ?></div></li>
<?php endif; ?>
<?php endforeach; ?>
</ul>
This used to work PERFECT! But after updating some field Labels, this php loop sorts after date, and NOT the field order. Look at this image:
https://i.sstatic.net/6Qabg.jpg
What i marked with red is being showed first! I would love to sort this loop, so it ouputs after the Field Order instead! and not some date..
You can order fields as you like with array_multisort function. Let me show:
ACF fields are stored in groups. And each field has menu_order parameter. In admin fields are always sorted by it, but on frontend this order may be broken.
So, first of all we need to get fields from our group. We need to know ACF field group ID. You can find it in url on group edit page, for example:
http://site.ru/wp-admin/post.php?post=340&action=edit
In this case group ID is 340. If you don't want to use hardcoded ID (if your groups are changing from time to time), you can get it, using group name (in this example group name id Technic CPT):
global $wpdb;
$group_ID = $wpdb->get_var( "SELECT ID FROM $wpdb->posts WHERE post_title = 'Technic CPT'" );
Then we get our fields array:
$acf_fields = acf_get_fields_by_id( $group_ID );
Next step will be to create array for new order. We need to order fields by menu_order parameter:
$order = array();
foreach ( $acf_fields as $key => $field ) :
$order[ $key ] = $field[ 'menu_order' ];
endforeach;
Note, that keys for $acf_fields will be also keys for $order! Finally, we can sort our fields:
array_multisort(
$order, SORT_DESC,
$acf_fields
);
SORT_DESC wil be used if you want to sort from bigger to smaller. And SORT_ASC - from smaller to bigger.
That's all. Now $acf_fields array is sorted by menu_order parameter.