How to Count the Total Number of Rows in an ACF Repeater Output
Determining the total count of rows before rendering them is a fundamental requirement when applying conditional logic to ACF repeater fields. The specific goal here is to distinguish between a single row and multiple rows, allowing you to apply distinct CSS classesâsuch as adding a .only-one modifier for singular entries. The common pitfall, as seen in many initial attempts, is calculating the count during the render loop rather than before it.
Your original code snippet illustrates this exact issue:
if( have_rows('testimonials')) {
$counter = 0;
$numtestimonials = '';
while ( have_rows('testimonials') ){
the_row();
$counter++;
if ($counter < 2) {
$numtestimonials = 'onlyone';
}
echo '<div class="testimonial ' . $numtestimonials . '"';
// bunch of output here
echo '</div>';
}
}
The logic fails because have_rows() returns true for every iteration until the very last one. Inside this loop, you increment $counter and check if it is less than 2. On the first iteration, this condition is met, so the class becomes 'onlyone'. However, if there are five rows, the loop continues, increments the counter four more times, and eventually renders the remaining items with an empty or incorrect state depending on how you reset variables. You cannot reliably determine the "total" count while simultaneously iterating through the results to output them; the decision must be made prior to the output phase.
To solve this, you need to separate the counting logic from the rendering logic. The most robust approach is to leverage the ACF_PRO repeater field's built-in capabilities or, if sticking to core functions, to count the total rows first using a specific function call that doesn't trigger the loop output.
The cleanest method without relying on external plugins is to use the have_rows() check combined with a manual count, but you must ensure you don't consume the loop inside the counting phase. A better pattern involves wrapping the content in a function or structuring your code so the total count is determined before any the_row() calls occur.
Here is a corrected implementation pattern:
// First, determine if there are rows at all
if ( have_rows('testimonials') ) {
// Get the total number of rows first
$total_rows = acf_get_field($field_group, $field_name); // Requires ACF Pro or careful handling
// However, a more standard core approach without Pro functions:
// We often need to iterate once just to count, but that destroys the loop state.
// Therefore, the best practice is usually to calculate count based on have_rows()
// and then use a separate counter variable that we reset or manage carefully.
// Actually, for standard Core ACF, the most reliable way without Pro functions
// is to assume the count logic happens in two passes or use a specific trick:
$counter = 0;
$numtestimonials = '';
// We can't easily get the count without looping if using core only.
// But we can optimize the logic inside the loop.
while ( have_rows('testimonials') ) {
the_row();
// Increment counter
$counter++;
// Only apply 'onlyone' if this is the first row AND there are no more rows coming?
// No, we don't know future rows in a standard loop.
// THE SOLUTION: Check total count BEFORE the loop using acf_get_field_count (Pro)
// OR iterate twice. Since iterating twice is inefficient, let's assume ACF Pro
// availability for the simplest code, or use the 'count' logic differently.
// If sticking to Core ACF without Pro functions:
// You must loop once just to count, then loop again? No.
// The standard solution for Core ACF is often to not output inside the counting loop.
}
}
Wait, there is a simpler trick often overlooked in Core ACF scenarios if you don't have access to acf_get_field_count. You can determine the count by iterating through the rows but storing the data first, or more elegantly, by accepting that you might need to check the total count before entering the render loop.
If you are using ACF Pro, the solution is straightforward: use acf_get_field($field_group, $field_name) to get the raw value, but specifically for repeaters, there isn't a direct "count" function in the core API without looping. However, you can count the rows by simply initializing a counter and checking have_rows() inside the loop, but you must do this before outputting HTML.
The correct architectural fix is to separate the counting logic from the rendering logic entirely. Here is how you restructure the code to handle the "single vs. multiple" distinction correctly:
if ( have_rows('testimonials') ) {
$counter = 0;
// We need to know the total count before we start outputting.
// Since we cannot easily get a count without looping in Core ACF,
// we often use a pattern where we loop once to count, then loop again?
// No, that's bad performance.
// The practical solution for Core ACF is to check the condition at the start of the loop
// but store the CSS class only if we are on the last item? No, that requires knowing the end.
// Let's use the most reliable pattern: Iterate once, count, then iterate again?
// Actually, the best approach is to use a flag or simply check the counter logic differently.
// RECOMMENDED APPROACH FOR CORE ACF:
// Use a single loop but determine the class based on whether we are at index 0
// AND the total count is 1. But how do we know total count is 1 without looping twice?
// The answer lies in using acf_get_field() if Pro, or accepting that for Core ACF,
// you often need to iterate once to count.
}
Actually, the most efficient way to handle this in Core ACF (without Pro) is to realize that have_rows() returns true for every row. You can't know if there are more rows until you hit the end of the loop. Therefore, you cannot apply a CSS class conditionally based on "total count == 1" inside a single pass unless you store the classes in an array or re-iterate.
However, there is a cleaner way: Don't output HTML inside the counting loop. Instead, collect the data first, determine the class, then render. Or, simpler: Use acf_get_field() if available, but for pure Core ACF, you must iterate twice or use a different logic flow.
Wait, there is a better trick. You can check if it's the only row by checking if the loop ends immediately after the first iteration? No.
The correct solution involves separating the counting phase from the rendering phase. Here is the revised code that works reliably:
if ( have_rows('testimonials') ) {
$rows_data = [];
// First pass: Collect data and determine total count
while ( have_rows('testimonials') ) {
the_row();
$counter++;
$rows_data[] = get_sub_field('your_field_name'); // Store your content here
}
// Now we know the total count ($counter)
if ( $counter == 1 ) {
$css_class = 'onlyone';
} else {
$css_class = '';
}
// Second pass: Render with the determined class
foreach ( $rows_data as $row ) {
echo '<div class="testimonial ' . esc_attr($css_class) . '">' . $row . '</div>';
}
}
This two-pass approach ensures that the CSS class is assigned correctly based on the total number of rows, regardless of whether there is one item or many. While it requires storing data in memory, this is negligible for typical repeater field sizes and guarantees correctness without needing ACF Pro's specific count functions.
If you are using ACF Pro, you can skip the two-pass loop entirely by using acf_get_field($field_group, $field_name) combined with a specific count function if available in your version, or simply trusting that have_rows() works as expected if you structure your logic to check the counter only after verifying the total count via a separate function call.
In summary, the key takeaway is that you cannot determine "total" count while iterating and outputting simultaneously in Core ACF without storing intermediate results. By collecting the data first, calculating the class once, and then rendering, you achieve the desired visual distinction cleanly and efficiently.