使用 get_post_meta - WordPress 检索 ACF 灵活内容项的元字段值



提前感谢您的帮助。这是我想要实现的目标:

我有一个名为"广告系列"的自定义帖子类型,我有一个名为"国家/地区"的自定义分类,它与广告系列自定义帖子类型相关。当用户向广告系列添加新的国家/地区时,系统会生成一个新的广告系列帖子,该帖子是当前广告系列的子级。我正在复制分配给父广告系列的 ACF 字段并复制子帖子中的值,但是我在使用 ACF 灵活内容字段时遇到了问题。这是我的代码片段,它正在检索父帖子字段并使用该值更新子帖子中新创建的 ACF 字段。

$action_text = get_post_meta($parent_id, 'action_text', true);
update_field('action_text', $action_text, $post_id);

我尝试使用灵活的内容执行此操作,但我知道我需要遍历并找到已创建的内容块。最好的方法是什么?

// About Fields
$about_fields = get_post_meta($parent_id, 'content');
var_dump($about_fields);
$meta_key = // How to retrieve the flexible content keys
$meta_value_of_flexible_content = get_post_meta($parent_id, $meta_key);
if($about_fields) {
}

为澄清起见,"内容"是灵活的容器名称。"text_and_image"是我创建的灵活内容块之一的示例名称。

再次感谢您的任何见解。

我已经尝试过使用灵活的内容执行此操作,但我知道我需要循环 通过并查找已创建的内容块。

您可以使用get_field()update_field()函数来复制任何ACF 字段,包括灵活内容字段。

例如,要克隆整个content字段:

$about_fields = get_field( 'content', $parent_id );
if ( $about_fields ) {
update_field( 'content', $about_fields, $post_id );
}

// How to retrieve the flexible content keys

foreach ( $about_fields as $arr ) {
echo 'Layout: ' . $arr['acf_fc_layout']; // e.g. "Layout: text_and_image"
// The rest of items in `$arr` are the SUB-fields of that specific layout as
// identified by the `$arr['acf_fc_layout']`, which is the layout's name. So
// if you have two SUB-fields named `text1` and `image1` respectively, then
// these items are set: `$arr['text1']` and `$arr['image1']`
}

附加代码

要克隆所有ACF 字段,请执行以下操作:

$fields = get_fields( $parent_id );
foreach ( $fields as $name => $value ) {
update_field( $name, $value, $post_id );
}

附加说明

我会将其更改为使用get_field()函数:

$action_text = get_post_meta($parent_id, 'action_text', true);

所以:

$action_text = get_field('action_text', $parent_id);

最新更新