Outputting ACF Repeater’s Sub Fields

This Pro tutorial provides the code for printing custom HTML after looping through rows of a ACF Repeater (available in ACF Pro) that has a couple of Color Picker fields and a Text field.

ACF Field:

Field populated when editing a Page:

On the frontend:

The reason for providing a field for text color is that the default dark text color will not be readable if the background color is dark. A light text color can be set for such rows.

We shall set a light gray background color when the user does not pick one. Also, ensure a grayish border-color applies for such rows’ output.

Step 1

Add this PHP code where you want to output the Repeater field:

<?php
// Output "name" subfield of "site_builders" ACF Repeater with "background_color" and "text_color" subfield values inline.
// check if the repeater field has rows of data
if ( have_rows( 'site_builders' ) ) {
  echo '<div class="site-builders">';
    // loop through the rows of data
    while ( have_rows( 'site_builders' ) ) : the_row();
      // assign name subfield's value to a variable
      $name = get_sub_field( 'name' );

      // assign background_color subfield's value to a variable
      $background_color = get_sub_field( 'background_color' );

      // construct the HTML for inline border color. If bg color is not selected, set it to show a border-color of #ddd.
      $border_html = $background_color ? '' : ' border-color: #ddd';

      // set a fallback background color
      $background_color = $background_color ?: '#f5f5f5';

      // assign text_color subfield's value to a variable
      $text_color = get_sub_field( 'text_color' );

      // construct the HTML for inline text color
      $color_html = $text_color ? ' color: ' . $text_color . ';' : '';

      printf(
        '<span class="site-builder" style="background-color: %s;%s%s">%s</span></span>',
          $background_color,
          $color_html,
          $border_html,
          $name
      );
    endwhile;
  echo '</div>';
} else {
	// no rows found.
}
?>

Replace the field and sub field names.

Step 2

Add this CSS:

.site-builders {
  display: flex;
  gap: 1em;
}

.site-builder {
  display: inline-block;
  padding: 1em 3em;
  border: 1px solid transparent;
  border-radius: 6px;
}

Reference

https://pimylifeup.com/php-ternary-operator/