WordPress模板中ACF Repeater字段表格重复生成问题求助
解决ACF Repeater字段生成多个表格的问题
嘿,这个问题其实是代码结构的小疏漏导致的——你把整个<table>标签都放到while循环里了,所以每一条Repeater数据都会触发一次表格的创建,自然每条数据都是独立表格啦。
只需要把表格的外层结构(包括表头)移到循环外面,循环里只负责输出每条数据对应的行就行,修改后的代码如下:
<?php if(get_field('monthly_expenses')): ?> <table> <tbody> <!-- 表头只输出一次,放在循环外面 --> <tr> <td><strong> 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> <!-- 如果需要空行分隔,也可以放在循环里,每条数据后加空行 --> <tr> <td> </td> <td> </td> <td> </td> </tr> <?php endwhile; ?> </tbody> </table> <?php endif; ?>
关键修改点:
- 把
<table>、<tbody>和表头<tr>都移到while循环外面,确保整个Repeater数据只生成一个表格 - 循环内部只保留数据行和你需要的空行,这样所有数据都会被放到同一个表格的
<tbody>里 - 去掉了原来没用的
<ul>标签,表格不需要嵌套在列表里
这样修改后,电费、电话等所有Repeater里的内容就都会显示在同一个表格里啦!
内容的提问来源于stack exchange,提问作者ultramel1987
相关产品推荐
相关产品推荐

