从 ACF 组内获取字段作为变量

问题描述 投票:0回答:2

我正在尝试从 ACF 获取值

group
但无法通过两种方法获取它们:

这是我的

ACF fields
的设置方式供参考:

方法一:

<?php

$welcome_screen_content = get_field('welcome_screen_content'); // type: group

if( $welcome_screen_content ):
  $title = get_field('title');
endif;


echo $title; // prints nothing

?>

方法2:

<?php

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

  $title = get_sub_field('title');

  echo $title; // prints nothing

  endwhile;
endif;

?>

在我的帖子模板上,

title
确实有一个值:

不确定为什么在这两次尝试中,回显

$title
没有任何作用?

html wordpress advanced-custom-fields
2个回答
3
投票

上使用get_field时,高级自定义字段会返回包含组字段的关联数组。因此,要将标题放入其中,您可以这样做:

$welcome_screen_content = get_field('welcome_screen_content'); // type: group

if( $welcome_screen_content ):
  $title = $welcome_screen_content['title'];
endif;

方法 1 无法按预期工作,因为

get_field('title')
要求 ACF 获取与“welcome_screen_content”组处于同一级别的字段。

方法 2 无法按预期工作,因为

get_subfield
Repeater 或灵活内容字段一起使用。


0
投票

我遇到了这个辅助函数来从字段组中获取值并发现它很方便。

你可以像这样使用它:

get_group_field( '{group field name}', '{sub field name}' );

© www.soinside.com 2019 - 2024. All rights reserved.