首页 > 解决方案 > 使用 word press 和 ACF 删除循环中的重复代码

问题描述

我有一个简单的引导手风琴,我还添加了一个在手风琴左侧显示图像的功能。

该图像显示了与手风琴相关的图像。

我应该左手风琴(col-6)和右图(col-6) 我知道它是我的循环,但我不确定最好的布局方式。

我目前有一个解决方案,我重复循环两次.. 这太糟糕了,我看不到清理它的方法。

有人可以指出我错在哪里以及如何简化这一点。

<div class="row-flex">
    <?php
    // check if the repeater field has rows of data
    if (have_rows('accordion_repeater')):
        $i = 1; // Set the increment variable
        $ii = 1; // Set the increment variable
        ?>
        <div class="accordion col" id="accordion">
            <?php
            // loop through the rows of data for the tab header
            while (have_rows('accordion_repeater')) :
                the_row();
                $header = get_sub_field('accordion_header');
                $content = get_sub_field('accordion_content');
                $i++; // Increment the increment variable
                ?>
                <div class="card mb-2">
                    <div class="card-header" id="heading-<?php echo $i; ?>">
                        <h4 class="tablinks p-2" id="defaultOpen" type="button" data-toggle="collapse"
                            data-target="#collapse-<?php echo $i; ?>"
                            aria-expanded="true"
                            aria-controls="collapse-<?php echo $i; ?>"
                            onclick="openCity(event, 'image-<?php echo $i; ?>')">
                            <?php echo $header; ?>
                            <i class="fa" aria-hidden="true"></i>
                        </h4>
                    </div>
                    <div id="collapse-<?php echo $i; ?>" class="collapse "
                         aria-labelledby="collapse-<?php echo $i; ?>" data-parent="#accordion">
                        <div class="card-body">
                            <?php echo $content; ?>
                        </div>
                    </div>
                </div>
            <?php
            endwhile; //End the loop
            ?>
        </div>
        <div class=" col">
            <?php
            // loop through the rows of data for the tab header
            while (have_rows('accordion_repeater')) :
                the_row();
                $image = get_sub_field('accordion_image');
                $ii++; // Increment the increment variable
                ?>
                <div id="image-<?php echo $ii; ?>" class="tabcontent">
                    <?php
                    if (!empty($image)): ?>
                        <img src="<?php echo esc_url($image['url']); ?>"
                             alt="<?php echo esc_attr($image['alt']); ?>"/>
                    <?php endif; ?>
                </div>
            <?php
            endwhile; //End the loop
            ?>
        </div>
    <?php

    else :
        // no rows found
        echo 'no content';
    endif;
    ?>
</div>

标签: phpwordpressloopswhile-loopadvanced-custom-fields

解决方案


推荐阅读