If repeater field has 1 rows, 2 rows etc

I was wondering if this is at all possible:

I’d like a repeater loop that basically has some sort of count that says if row 1 has value then do this, if row 2 has a value do this and this.

Basically what I’m trying to achieve is if row 1 has a value display a full width column, but if there are 2 rows then display row 1 in a div then row 2 in another div etc etc.

So basically something like

if there is only 1 row present then:

SUBFIELD 1

If there are 2 row’s present then:

<div class="half"> Subfield 1</div>
<div class="half">Subfield 2</div>

If there are 3 row’s present then:

<div class="third"> Subfield 1</div>
<div class="third">Subfield 2</div>
<div class="third">Subfield 3</div>

I could do it simply with just some if has value, but all 3 fields would be present. Was wondering if its possible with the repeater?

In your frontend, you’ll have to count number of elements in the repeater field array. So something like this:

<?php

// pre define the allowed columns
$allowed_classnames = array(
    1 => 'full',
    2 => 'half',
    3 => 'third',
    4 => 'fourth',
    5 => 'fifth',
);
// get the count on the repeater field
// mabye use get_sub_field() instead of get_field() if it's nested
$number_of_cols = count( get_field( '<repeater>' ) );

// set a default classname
$classname_to_use = $allowed_classnames[1];

// check if the $number_of_cols exist in the predefined classnames
if ( array_key_exists( $number_of_cols , $allowed_classnames ) ) {
    // set the classname to be used
    $classname_to_use = $allowed_classnames[$number_of_cols];
}

while( has_sub_field( '<repeater>' ) ) : ?>
    <div class="<?php echo esc_attr( $classname_to_use ); ?>">
        <?php the_sub_field( '<repeater_content>' ); ?>
    </div>
<?php endwhile; ?>

Please not that I just briefly tested it on a site I’m working on. You’ll have to replace the '<repeater_content>' and '<repeater>' with your actual field names.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s