首页 > 解决方案 > 在嵌套循环中从父级获取值

问题描述

我使用高级自定义字段嵌套了转发器字段,在我的模板中我使用 if while 循环来显示它们。这些字段是类别(帖子)> 子类别> 产品。在底层(产品)我触发了一个模式,在这个模式的标题中我想要 category_name > subcategory_name > product_name ...第一个工作正常,因为我只是使用帖子标题(the_title)最后一个也工作,因为我在该级别只需要调用 the_sub_field('product_name') 但我不知道如何调用子类别名称值,我尝试了 the_sub_field('subcategory_name') 和 the_field('subcategory_name') 都返回空白。有没有办法将值从父循环传递给子循环?

这是它的样子:

<?php if( have_rows('category') ): while ( have_rows('category') ) : the_row(); ?>
    <h3><?php the_sub_field('category_name'); ?></h3>
    <?php if( have_rows('product') ): while ( have_rows('product') ) : the_row(); ?>
        <a href="#<?php the_sub_field('modal_id'); ?>" data-toggle="modal" >
            <?php the_sub_field('product_name'); ?>
        </a>
        <!-- THE MODAL -->
        <div id="<?php the_sub_field('modal_id'); ?>" class="modal fade" ...>
        <div class="modal-dialog" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <h4 class="modal-title" id="myModalLabel">
                    <?php the_title(); ?>
                    &gt;
                    <?php the_sub_field('category_name'); ?><!-- DOESN'T WORK -->
                    &gt;
                    <?php the_sub_field('product_name'); ?>
                </h4>
            </div>
            <div class="modal-body">
                Product details here
            </div>
        </div>
        </div>
        </div>
    <?php endwhile; endif; ?>
<?php endwhile; endif; ?>

标签: phpwordpressadvanced-custom-fields

解决方案


如果我理解正确,您想在第二个循环中显示来自第一个循环的数据。这可以通过首先存储数据来完成。像这样:

<?php if( have_rows('category') ): while ( have_rows('category') ) : the_row(); ?>
    <h3><?php the_sub_field('category_name'); ?></h3>
    <?php $category_name = get_sub_field( 'category_name' ); ?>
    <?php if( have_rows('product') ): while ( have_rows('product') ) : the_row(); ?>
        <a href="#<?php the_sub_field('modal_id'); ?>" data-toggle="modal" >
            <?php the_sub_field('product_name'); ?>
        </a>
        <!-- THE MODAL -->
        <div id="<?php the_sub_field('modal_id'); ?>" class="modal fade" ...>
        <div class="modal-dialog" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <h4 class="modal-title" id="myModalLabel">
                    <?php the_title(); ?>
                    &gt;
                    <?php echo $category_name; ?><!-- NOW IT WORKS -->
                    &gt;
                    <?php the_sub_field('product_name'); ?>
                </h4>
            </div>
            <div class="modal-body">
                Product details here
            </div>
        </div>
        </div>
        </div>
    <?php endwhile; endif; ?>
<?php endwhile; 

$category_name 将在每个外部循环中获得一个新值。


推荐阅读