php - 在嵌套循环中从父级获取值
问题描述
我使用高级自定义字段嵌套了转发器字段,在我的模板中我使用 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(); ?>
>
<?php the_sub_field('category_name'); ?><!-- DOESN'T WORK -->
>
<?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; ?>
解决方案
如果我理解正确,您想在第二个循环中显示来自第一个循环的数据。这可以通过首先存储数据来完成。像这样:
<?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(); ?>
>
<?php echo $category_name; ?><!-- NOW IT WORKS -->
>
<?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 将在每个外部循环中获得一个新值。
推荐阅读
- apache-spark - 错误:调用 fit() 函数时“Python worker 无法连接回来”
- c# - How do I display details from single column in a modal in Angular 7?
- reactjs - aws amplify auth 自定义注册无法映射未定义
- javascript - 使用变量按值选择jquery集合中的元素
- c# - SharePoint 更新列表项
- python - 从多个文本苍蝇中提取,附加结果
- jbpm - 如何根据用户任务结果设置 BPMN 流程变量?
- swift - 在字符串中创建占位符值的属性文本
- javascript - 分配一个变量以及使用另一个数组的项目迭代 for 循环
- python - 标签值超出有效范围