ACF Wordpress 组内的中继器

osc*_*car 0 php wordpress while-loop nested-loops advanced-custom-fields

我正在使用 Wordpress 的高级自定义字段并尝试在组内循环转发器。我得到的只是“注意:数组到字符串的转换......”

出了什么问题,我该如何解决?

<?php if( have_rows('start_horlurar') ): while ( have_rows('start_horlurar') ) : the_row();  ?>

<?php $horlur = get_sub_field('horlur'); ?>

<?php if( have_rows( $horlur['arsmodeller_lankar']) ): while ( have_rows($horlur['arsmodeller_lankar']) ) : the_row();  ?>

<?php echo get_sub_field('lank'); ?>

<?php endwhile; endif; ?>

<?php endwhile; endif; ?>
Run Code Online (Sandbox Code Playgroud)

Jar*_*ice 16

我相信这是正确的回答,但对于那些寻找通用实现的人来说似乎还不够清楚。

<?php

if( have_rows('your_group') ): while ( have_rows('your_group') ) : the_row(); 

    if( have_rows('your_repeater') ): while ( have_rows('your_repeater') ) : the_row();       

        echo get_sub_field('repeater_sub_field');

    endwhile; endif;

endwhile; endif;

?>
Run Code Online (Sandbox Code Playgroud)

通常对于组,您可以使用以下方法访问特定的子字段:

<?php 

$group_var = get_field['your_group']; 

$group_sub_field_var = $group_var['group_sub_field']

?>
Run Code Online (Sandbox Code Playgroud)

但是,对于嵌套在组内的中继器,您似乎无法使用此策略,并且必须首先循环使用组have_rows()才能到达中继器。

如果您查看有关 ACF组文档,它会提到如何像中继器一样完成组的循环。该have_rows()文档还提供了有关使用have_rows().


小智 12

我发现双循环很乱,不需要。我意识到这很旧,但我只是遇到了这个问题并且不想有两个循环。

对于我的组 ('group') 和我的中继器 ('repeater'),带有子字段 ('subfield') 这就是我所做的。

     $group = get_field('group');
     $repeaters = $group['repeaters'];
     foreach($repeaters as $repeater) {
         echo $repeater["subfield"];
       }
Run Code Online (Sandbox Code Playgroud)

超级简单,而且干净多了。如果需要,您可以添加“if”语句,而不是控制我的必填字段。

我发现这种方法对于快速和肮脏很重要。我对几乎所有内容都使用组,以便能够为后端的自定义字段创建更好的用户体验。我的大多数自定义字段都是成组的并抓取参数,我希望它尽可能少的代码和尽可能干净。

如果你们发现这种方法有任何问题,特别是在性能方面,请告诉我。

  • 这对我有用,并且比双循环更整洁 (3认同)

Out*_*ess 11

在嵌套的 ACF 中继器中,您不需要添加父中继器的引用 - 只需添加中继器名称即可。像这样尝试。

<?php
if( have_rows('start_horlurar') ): while ( have_rows('start_horlurar') ) : the_row(); 
    echo get_sub_field('horlur');
    if( have_rows('arsmodeller_lankar') ): while ( have_rows('arsmodeller_lankar') ) : the_row(); 
        echo get_sub_field('lank');
    endwhile; endif;
endwhile; endif;
?>
Run Code Online (Sandbox Code Playgroud)

更新代码: 您也需要像 ACF 中继器一样循环 ACF 组字段。像这样尝试。

<?php
if( have_rows('start_horlurar') ): while ( have_rows('start_horlurar') ) : the_row(); 
    if( have_rows('horlur') ): while ( have_rows('horlur') ) : the_row();       
        if( have_rows('arsmodeller_lankar') ): while ( have_rows('arsmodeller_lankar') ) : the_row(); 
            echo get_sub_field('lank');
        endwhile; endif;
    endwhile; endif;
endwhile; endif;
?>
Run Code Online (Sandbox Code Playgroud)