Close
Article

ACF Repeater – Building an if/else query based on the number of repeater iterations

The repeater field in Advanced Custom Fields is one of the most powerful fields available, allowing you to easily build out entire blocks of content with just a single block of code inserted into your theme.

But what if you want to alter your code output in specific situations such as when a certain number of rows are present, or for a specific row?

Output for a Specific Row

Altering the output for a specific row is pretty easy.

Here is what standard code for your repeater might look like – this example is taken directly from

if(have_rows('repeater_field_name')): while (have_rows('repeater_field_name')) : the_row();
	the_sub_field('sub_field_name');
endwhile;

Adding a counter is pretty easy:

$counter = 0;
if(have_rows('repeater_field_name')): while (have_rows('repeater_field_name')) : the_row();
	the_sub_field('sub_field_name');
	$counter++;
endwhile;

This inserts a counter and increases it by one every time the repeater loops, thereby allowing you to have a specific output for specific iterations:

$counter = 0;
if(have_rows('repeater_field_name')): while (have_rows('repeater_field_name')) : the_row();
	if($counter == 2){
		the_sub_field('another_sub_field');
	}
	the_sub_field('sub_field_name');
	$counter++;
endwhile;

This loop inserts an additional subfield output only for the third iteration of the repeater loop.

In this way, you can alter output for specific repeater items.

What if I want to update the code based on the total number of repeater items?

You can also count the total number of iterations and alter the output code.

Imagine a scenario where you want to output content from the repeater into columns that span the full width of a page. You won’t necessarily know in advance how many repeater elements might be added so therefore, you won’t know how many columns you need.

The first thing you need to do is to count the total number of rows:

$total_rows = count(get_field('repeater_field_name'));

Once you have the total number of rows, altering the output is a simple if/else query:

if($total_rows == ('2' || '3'|| '4')){
	// Upto 4 columns
	echo '<div class="columns three">';
} elseif ($total_rows == ('5' || '6')){
	// 5 or 6 columns
	echo '<div class="columns two">';
} elseif ($total_rows >= 7){
	// Greater than 7 columns
	echo '<div class="columns one">';
}

Using this code, you can build layouts that dynamically update based on the number of rows a user has entered.

Questions? Comments?

Let me know below in the comments.

[tipjarwp]

Leave a Reply

Your email address will not be published.