1

I have a flexible content field set up with just one type of layout. I need to get the total count of layouts but my count is only returning 1 every time. Here is the ACF field setup:

enter image description here

And here is my code. Even when I add more than one table the count outputs 1.

<?php if( have_rows('pricing_tables') ): ?>

    <div class="columns">

        <?php while ( have_rows('pricing_tables') ) : the_row(); ?>

            <?php if( get_row_layout() == 'price_table' ): ?>

                <?php $count = count(get_sub_field('price_table')); ?>

                <div class="one-half first count-<?php echo $count; ?> index-<?php echo get_row_index(); ?>">

                    <?php the_sub_field('title'); ?>

                </div>

            <?php endif; ?>

        <?php endwhile; ?>

    </div>

<?php endif; ?>

Can anyone help?

1 Answer 1

3

If your count is purely just to add a number on the end of your count- class then you can achieve this by using a variable just outside the loop and adding to the variable at the end.

<?php if( have_rows('pricing_tables') ): ?>

<div class="columns">
    <?php $count = 0; ?>
    <?php while ( have_rows('pricing_tables') ) : the_row(); ?>

        <?php if( get_row_layout() == 'price_table' ): ?>

            <?php $count = count(get_sub_field('price_table')); ?>

            <div class="one-half first count-<?php echo $count; ?> index-<?php echo get_row_index(); ?>">

                <?php the_sub_field('title'); ?>

            </div>
            <?php $count++; ?>
        <?php endif; ?>

    <?php endwhile; ?>

</div>

You keep getting the value 1 because each time the loop got to your module layout price_table you were counting the layout.

If you wanted to count the total number of layouts used within your flexible content area for your page then you should count the field which is your flexible content area and not the individual layout

$count = count(get_field('pricing_tables'));

I hope that helps

1
  • Perfect! Thanks for the explanation. That final code snippet worked perfectly.
    – Xav
    Commented Jul 8, 2018 at 13:56

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.