Helping you build a better website
(and other interesting web stuff)

CSSHTMLJavaScriptjQueryMSSQLMySQLPHPSilvaTechnologiesWordpress
Silva Web Designs - Blog

ACF Repeater Load More using AJAX

Have you ever wanted to show a limited amount of items when using an ACF repeater? Maybe you are using this to display images and to save on load time you only want to show a selective amount instead of loading them all. At the end of the day, having to load fewer images is going to speed up your site right?

In this example, we will show you the basics of adding load more functionality for an ACF repeater field. We are going to display a repeater called gallery and load only 9 items if there are more than 9 items we will display a ‘Load more’ button to programmatically load the rest.

So first of all our markup will look as follows:-


<div id="photo-gallery">
	<div class="row">
		<?php
		if( have_rows('media') ): 
			$total = count(get_field('media'));
			$count = 0;
			$number = 8;					
			while ( have_rows('media') ) : the_row(); ?>						
					<div class="col-md-4 col-sm-6">
						<a class="mag-pop" data-img="<?php the_sub_field('image'); ?>" href="<?php the_sub_field('image'); ?>"><img class="img-gallery" alt="BeWILDerwood Gallery" src="<?php the_sub_field('image'); ?>" /></a>
					</div>
				<?php
				if ($count == $number) {
					// we've shown the number, break out of loop
					break;
				} ?>					
			<?php $count++; endwhile;
		else : endif;
		?>
	</div>
	<a id="gallery-load-more" href="javascript: my_repeater_show_more();" <?php if ($total < $count) { ?> style="display: none;"<?php } ?>><h2 id="title-bg"><span>Load more</span></h2></a>
</div>

As you can see, $number defined the number of repeater items we want to initially display. We use the break; clause to prevent further images from loading.

Now moving on to the JavaScript:-


<script type="text/javascript">
	var my_repeater_field_post_id = <?php echo $post->ID; ?>;
	var my_repeater_field_offset = <?php echo $number + 1; ?>;
	var my_repeater_field_nonce = '<?php echo wp_create_nonce('my_repeater_field_nonce'); ?>';
	var my_repeater_ajax_url = '<?php echo admin_url('admin-ajax.php'); ?>';
	var my_repeater_more = true;
	
	function my_repeater_show_more() {
		
		// make ajax request
		jQuery.post(
			my_repeater_ajax_url, {
				// this is the AJAX action we set up in PHP
				'action': 'my_repeater_show_more',
				'post_id': my_repeater_field_post_id,
				'offset': my_repeater_field_offset,
				'nonce': my_repeater_field_nonce
			},
			function (json) {
				// add content to container
				// this ID must match the containter 
				// you want to append content to
				jQuery('#photo-gallery .row').append(json['content']);
				// update offset
				my_repeater_field_offset = json['offset'];
				// see if there is more, if not then hide the more link
				if (!json['more']) {
					// this ID must match the id of the show more link
					jQuery('#gallery-load-more').css('display', 'none');
				}
			},
			'json'
		);
	}
	
</script>

We’ve added comments within the code so you can see what is happening through the process. Now we need to add the code to the functions.php file to load the additional items.


/**
 * ACF Load More Repeater
*/

// add action for logged in users
add_action('wp_ajax_my_repeater_show_more', 'my_repeater_show_more');
// add action for non logged in users
add_action('wp_ajax_nopriv_my_repeater_show_more', 'my_repeater_show_more');

function my_repeater_show_more() {
	// validate the nonce
	if (!isset($_POST['nonce']) || !wp_verify_nonce($_POST['nonce'], 'my_repeater_field_nonce')) {
		exit;
	}
	// make sure we have the other values
	if (!isset($_POST['post_id']) || !isset($_POST['offset'])) {
		return;
	}
	$show = 9; // how many more to show
	$start = $_POST['offset'];
	$end = $start+$show;
	$post_id = $_POST['post_id'];
	// use an object buffer to capture the html output
	// alternately you could create a varaible like $html
	// and add the content to this string, but I find
	// object buffers make the code easier to work with
	ob_start();
	if (have_rows('media', $post_id)) {
		$total = count(get_field('media', $post_id));
		$count = 0;
		while (have_rows('media', $post_id)) {
			the_row();
			if ($count < $start) {
				// we have not gotten to where
				// we need to start showing
				// increment count and continue
				$count++;
				continue;
			}
			?>
			<div class="col-md-4 col-sm-6">
				<a class="mag-pop" data-img="<?php the_sub_field('image'); ?>" href="<?php the_sub_field('image'); ?>"><img class="img-gallery" alt="BeWILDerwood Gallery" src="<?php the_sub_field('image'); ?>" /></a>
			</div>
			<?php 
			$count++;
			if ($count == $end) {
				// we've shown the number, break out of loop
				break;
			}
		} // end while have rows
	} // end if have rows
	$content = ob_get_clean();
	// check to see if we've shown the last item
	$more = false;
	if ($total > $count) {
		$more = true;
	}
	// output our 3 values as a json encoded array
	echo json_encode(array('content' => $content, 'more' => $more, 'offset' => $end));
	exit;
} // end function my_repeater_show_more

As you can see above, we are going to load an additional 9 images (or repeater values) on click of the load more button. Once all loaded items have appeared, we are hiding the load more button so that is no longer visible.

And that’s pretty much it! If this has helped you, feel free to drop a comment. If you need any help with this, feel free to get in touch and we’ll be happy to assist you! 🙂

Nathan da Silva - Profile

Posted by: Nathan da Silva

Nathan is the Founder of Silva Web Designs. He is passionate about web development, website design and basically anything digital related. His main expertise is with WordPress, Magento, Shopify as well of many other frameworks. Whether you need responsive design, SEO, speed optimisation or anything else in the world of digital then get in touch. If you would like to work with Nathan, simply drop him an email at [email protected]

It’s good to share

2 thoughts on “ACF Repeater Load More using AJAX

  1. I have followed your great tutorial … I have already created a gallery by ACF (ACF Repeater Load More using AJAX). But I face a problem. When I use $number = 8 on page template It will display 9 images … Again I am clearing this issue .. when I use $number = 0; This will be shown in Figure 1. Please fix the problem … asap … I’m waiting for your solution …

Join the discussion