WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. It's 100% free, no registration required.

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

I have a gallery field using the advanced custom fields gallery addon.

This is how I am outputting my gallery fields/images in my theme...


$images = get_field('gallery');

if( $images ): ?>

    <div id="gallery-1">

        <?php foreach( $images as $image ): ?>

            <img src="<?php echo $image['url']; ?>" alt="<?php echo $image['alt']; ?>" />

        <?php endforeach; ?>


<?php endif; ?> 

And this is the only way in the documentation I can see how to implement it.

Does anyone now who how I can order the images by title, id or anything when they are outputted in the loop?

Many Thanks

share|improve this question
up vote 2 down vote accepted

You can use Php's usort() function with a callback. For example, if you want to sort images by ID, you could try something like this (stealing the filter that @Milo used in their answer):

function sort_callback($a,$b)
  if ($a['id'] == $b['id']) {
    return 0;
  return ($a['id'] < $b['id']) ? -1 : 1;

function my_acf_load_field( $field ){
  usort( $field, 'sort_callback');
  return $field;
add_filter( 'acf_load_field-gallery', 'my_acf_load_field' );

You can adjust the sort_callback function to sort by whichever value in the $image array that you'd like.

share|improve this answer
That seems to work nice. Thank you! – Joshc Nov 6 '12 at 16:37

see documentation for the acf_load_field-{$field_name} filter:

function my_acf_load_field( $field ){
    // sort $field
    return $field;
add_filter( 'acf_load_field-gallery', 'my_acf_load_field' );
share|improve this answer
I'm confused, the documentation does not really explain how to order re-order from the gallery. For example I'm trying to order by $image[title]. I can't envisage how to go about it :/ – Joshc Nov 6 '12 at 16:32

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.