Search code examples
wordpresshtml-tableadvanced-custom-fieldsrepeater

ACF Repeater Fields in table - Within PHP Template


I am using ACF to display a repeater field within a table of my template file in Wordpress. The fields are displaying - however the table seems to create a new "table" for each row, rather than including both rows of sub field data within the same table.

this is my code:

<?php if(get_field('monthly_expenses')): ?>

<ul>

<?php while(has_sub_field('monthly_expenses')): ?>

<table>
<tbody>
<tr>
<td><strong>&nbsp;Monthly Expense</strong></td>
<td><strong>Estimated Amount</strong></td>
<td><strong>Registered Supplier</strong></td>
</tr>
<tr>
<td><?php the_sub_field('monthly_expense'); ?></td>
<td><?php the_sub_field('estimated_amount'); ?></td>
<td><?php the_sub_field('registered_supplier'); ?></td>
</tr>
<tr>
<td>&nbsp;</td>
<td>&nbsp;</td>
<td>&nbsp;</td>
</tr>
<tr>
<td>&nbsp;</td>
<td>&nbsp;</td>
<td>&nbsp;</td>
</tr>
</tbody>
</table>
<!-- DivTable.com -->


<?php endwhile; ?>

</ul>

This is how it is displaying. I need both rows of info (both the electricity and telephone rows) to be in the first table rather than in seperate tables please. Current display on page


Solution

  • Everything within the while loop is repeated for each sub-field. Thus, you need to limit what you output to only the table row and get rid of the empty rows like so:

    <?php if(get_field('monthly_expenses')): ?>
    
    <ul>
    <table>
    <tbody>
    <tr>
    <td><strong>&nbsp;Monthly Expense</strong></td>
    <td><strong>Estimated Amount</strong></td>
    <td><strong>Registered Supplier</strong></td>
    </tr>
    
    <?php while(has_sub_field('monthly_expenses')): ?>
    
    <tr>
    <td><?php the_sub_field('monthly_expense'); ?></td>
    <td><?php the_sub_field('estimated_amount'); ?></td>
    <td><?php the_sub_field('registered_supplier'); ?></td>
    </tr>
    <!-- DivTable.com -->
    
    <?php endwhile; ?>
    </tbody>
    </table>
    
    </ul>
    

    I've left the <ul> in there, however I have no idea what that initially was for. Also, I hope you closed the if block.