0

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...

<?php

$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; ?>

    </div>

<?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

2

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):

<?php
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.

1

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' );
  • 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 clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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