Advanced Custom Fields Repeater Pagination

Published:

In the code below you will see an example of  Advanced Custom Fields Repeater Pagination with an image gallery mapped to a custom field named images with a sub field named image which contains an image object. The Repeater will be displayed on a page at the URL (just an example) /pictures.

12 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 /pictures/2//pictures/3/ etc.

<?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 = 12; // How many images to display on each page
$images = get_field( 'pic_images' );
$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( 'pic_images' ) ) : ?>

<?php
while( have_rows( 'pic_images' ) ): 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; } ?>
<div class="col-sm-4">
<?php $img_obj = get_sub_field( 'image' ); ?>
<a href="<?php echo $img_obj['sizes']['large']; ?>">
<img src="<?php echo $img_obj['sizes']['thumbnail']; ?>" alt="">
</a>
</div>

<?php endwhile;

// Pagination
echo paginate_links( array(
'base' => get_permalink() . '%#%' . '/',
'format' => '?page=%#%',
'current' => $page,
'total' => $pages
) );
?>

<?php else: ?>

No images found

<?php endif; ?>