如何在高级自定义字段中列出带有标签和值的转发器子字段?

how to list a repeater sub fields with label and value in Advanced Custom Field?

我搜索过,但找不到任何解决方案来列出带有子字段标签及其值的转发器字段行。

在我的例子中,我想列出一个带有标签和值的转发器字段子字段。 例如:

'Sub Field Label' = 'Value'

有什么办法吗?

如果您知道要从 Repeater Field 中检索的标签,只需使用标准方法:

if( have_rows('repeater_field_name') ):
    while ( have_rows('repeater_field_name') ) : the_row();
        echo 'Label = ' . get_sub_field('sub_field_name') . '<br>';
    endwhile;
endif;

如果您不在单个 post/page 中或 The Loop 之外,只需将 $post_id 作为第二个参数添加到 ACF 函数调用中。例如:have_rows('repeater_field_name', $post_id).


如果您不知道标签名称,我想您可以使用 get_fields() 获取当前 post 的所有自定义字段的数组并迭代它。类似于:

$fields = get_fields($post->ID);
foreach ($fields as $field_type => $field) {
    if ( $field_type == 'repeater_field' ) {
        foreach ($field as $row) {
            foreach ($row as $label => $value) {
                // In this case you should be aware that
                // $value could be an Array too...
                echo $label . ' = ' . $value;                    
            }
        }
    }
}

总之,推荐大家看看ACF Documentation。它完整​​、清晰,并且包含许多涵盖最常见用途的代码片段。

 <?php $args = array('post_type' => 'post');
            $the_query = new WP_Query( $args );
            query_posts( $args );
            while ( have_posts() ) : the_post();
   $field = get_field_object('field_name'); 
   echo $field['label']; //print label name
   echo the_field('field_name'); //and its value
    endwhile; wp_reset_query(); ?>

请试试这个希望对你有帮助