2

I'm using the advanced custom fields repeater plugin to create a a big grid of images with links. I would like the newest items I create at the top, so what I'm asking is how do I reverse the the order via the code?

Any help would be great. Here is my current code

<?php if( have_rows('shop_product') ): while ( have_rows('shop_product') ) : the_row(); ?> <div class="shop-item"> <div class="image-hover"> <div class="image-hover-inner"> <img src="<?php the_sub_field('product_image');?>"> <div class="image-caption"> <div class="image-caption-inner"> <a href="<?php the_sub_field('product_url');?>" target="_blank"><?php the_sub_field('product_brand');?><br> Buy Now</a> </div> </div> </div> </div> </div> <?php endwhile; else : endif; ?> 

3 Answers 3

7

You can use get_field('my_repeater') to get the repeater fields as an array which you can loop over.

Then using PHP's array_reverse() function, you get a reversed array you can loop over.

The only difference is you have to access the fields as array keys rather than using ACF's sub_field functions.

For your example:

<?php $products = array_reverse(get_field('shop_product')); foreach ($products as $product): ?> <img src="<?php echo $product['product_image']; ?>"> <a href="<?php echo $product['product_url']; ?>">Buy now</a> <?php endforeach; ?> 
Sign up to request clarification or add additional context in comments.

1 Comment

This is an old question now but for those returning in the far future, I think this should be the accepted answer.
5

It may not answer the actual question, but may solve the problem. If you are displaying rows of repeater, you could use CSS display:flex together with flex-flow:row/column-reverse;

As it may only be necessary to swap order to DISPLAY it

Example:

display:flex; flex-flow:row-reverse; 

1 Comment

While this would work from a display/visual-only perspective, it's not great in terms of user journey, screen-readers, etc. so I'd advise against it. Far better practice to structure your DOM in the order you want to display things in the first place.
4

off the top of my head, using output buffer - not the cleanest way though

<?php $outs = array(); if( have_rows('shop_product') ): while ( have_rows('shop_product') ) : the_row(); ob_start(); ?> <div class="shop-item"> <div class="image-hover"> <div class="image-hover-inner"> <img src="<?php the_sub_field('product_image');?>"> <div class="image-caption"> <div class="image-caption-inner"> <a href="<?php the_sub_field('product_url');?>" target="_blank"><?php the_sub_field('product_brand');?><br> Buy Now</a> </div> </div> </div> </div> </div> <?php $outs[] = ob_get_clean(); endwhile; else : endif; $outs = array_reverse($outs); echo implode($outs); ?> 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.