WordPress / Web Development Tutorials
(Best WordPress Tutorials)

CSSHTMLJavaScriptjQueryMySQLPHPSilvaTechnologiesWooCommerceWordpress
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 have 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 have 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 and various other CMS frameworks. If you need responsive design, SEO, speed optimisation or anything else in the world of digital, you can contact Silva Web Designs here; [email protected]

It’s good to share

16 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 …

  2. Thanks for this solution, it works great. One question – is there any way to send AJAX request and get only repeater items with specific value of some field? Because I have some kind of checkbox filters for this repeater and I really don’t know how to get specific repeater items.

  3. This is so helpful! When I added everything in its place (JS in header, HTML on page, code in functions) the Load More button appears with 9 items, but nothing loads when I click on it. The Chrome dev console outputs

    Uncaught ReferenceError: my_repeater_show_more is not defined
    at :1:2
    (anonymous) @ VM776:1

    Do you know why this might be?
    Thanks!

  4. Hi, is there any way to fetch images from one ACF gallery via ajax. Acutlley I have 100 icons in one ACF gallery. I want to display 12 images on first load then show other 10 images via load more button. Please guide how we can accomplish this

  5. Its great tutorial and its working perfectly.
    It would be great, if you can create another tutorial for loading the ACF gallery images on scrolling without clicking the “Load more” button.

  6. i have 12 rows on my acf repeater, i tried the scripts but when i click load more instead of showing the last 2 rows it showing the same first 10 rows i set on $number. can you help me on this one please?

  7. If I were to add two of these to a single page, which parameters on the second one need to be modified to be different from the first one?

Join the discussion

Related Posts

Related - Our Top 10 Used Plugins For WordPress – 2021 Edition

Wordpress / 20th December 2020

Our Top 10 Used Plugins For WordPress – 2021 Edition

Read More Related - How to add Pagination on an Advanced Custom Fields Repeater

Wordpress / 20th September 2020

How to add Pagination on an Advanced Custom Fields Repeater

Read More