Paginating an Advanced Custom Fields Repeater

Hands down my favourite WordPress plugin is Elliot Condon’s Advanced Custom Fields, and it’s made even more powerful by the Repeater Field add-on. But a Repeater can get unwieldy when it contains a large number of items, and you might find yourself wanting to paginate the results when you display them to the user. Here’s a technique for doing that.

In this example we will paginate a Repeater image gallery mapped to a custom field named image_gallery with a sub field named image which contains an image object. Our Repeater will be displayed on a page at the URL /gallery.

10 images will be displayed per page, and pagination links will allow the user to navigate between the gallery’s pages at pretty URLS such as /gallery/2//gallery/3/ and so on.

If you’re wondering what special magic you need to perform to get those pretty permalinks working, the answer is… none! WordPress automagically converts URL segments such as /2/ into a query variable named "page". Very handy!

In your page template:

[php]

/* * Paginate Advanced Custom Field repeater */ if( get_query_var(‘page’) ) { $page = get_query_var( ‘page’ ); } else { $page = 1; } // Variables $row = 0; $images_per_page = 10; // How many images to display on each page $images = get_field( ‘image_gallery’ ); $total = count( $images ); $pages = ceil( $total / $images_per_page ); $min = ( ( $page * $images_per_page ) $images_per_page ) + 1; $max = ( $min + $images_per_page ) 1; // ACF Loop if( have_rows( ‘image_gallery’ ) ) : ?> while( have_rows( ‘image_gallery’ ) ): the_row(); $row++; // Ignore this image if $row is lower than $min if($row < $min) { continue; } // Stop loop completely if $row is higher than $max if($row > $max) { break; } ?> $img_obj = get_sub_field( ‘image’ ); ?> <a href= echo $img_obj[‘sizes’][‘large’]; ?>> <img src= echo $img_obj[‘sizes’][‘thumbnail’]; ?> alt=> a> endwhile; // Pagination echo paginate_links( array( ‘base’ => get_permalink() .%#%’ . ‘/’, ‘format’ =>?page=%#%’, ‘current’ => $page, ‘total’ => $pages ) ); ?> else: ?> No images found endif; ?>

[/php]

A note about Custom Post Types

This technique will also work on Custom Post Type single templates. Your pagination permalinks will have the format /post-type/post-slug/2/.

Credits

My solution was inspired by Elliot Condon and Twansparent’s contributions to the Advanced Custom Fields forum.

Free Web Hosting