【问题标题】:Wordpress ACF fields how to get_option from custom post typesWordpress ACF 字段如何从自定义帖子类型中获取选项
【发布时间】:2021-07-22 21:37:19
【问题描述】:

我使用 ACF 并有一个名为“关于”的页面模板,我的“关于我们”页面使用该模板。我还有一个主页模板,它使用我的“主页字段组”中的字段。我的“关于我们”页面显示了“关于字段组”中的 ACF 字段以及我的“主页字段组”中的一些字段。

我通过使用以下 php 代码引用 ACF 字段从我的主页组中获取字段:

<?php $home = get_option('page_on_front'); ?>
<h3><?php the_field('featured_text' , $home); ?></h3>
<p><?php the_field('intro');?></p>
<h2><?php the_field('header', $home);?></h2>

H3 来自主页上的主页字段组,段落来自“关于字段组”中的“关于我们”页面介绍字段。

我想做类似的事情,但从自定义帖子类型(不是主页)中提取字段。

我的自定义帖子类型称为“通用模块”(slug = common_modules)。

有没有办法做到这一点,例如:

<?php $custom_post_type = get_post_type('Common Modules'); ?>
<h3><?php the_field('featured_text' , $custom_post_type); ?></h3>
<p><?php the_field('intro');?></p>
<h2><?php the_field('header', $custom_post_type);?></h2>

我的页面上有很多引用主页字段的字段,因此我需要能够在整个页面中频繁调用 $custom_post_type。

我想不通?

感谢您的帮助。

【问题讨论】:

  • 您的cpt 是否有带有featured_text 字段的特定帖子?如果是这样,该帖子的ID是什么?我们可以从它的 id 中检索值。
  • 是的,它的一篇文章 ID 为 495。
  • 好的,我刚刚更新了我的答案,看看这是否适合你!
  • 完美。出色的帮助。感谢您的耐心:-)
  • 没问题!我很高兴它有帮助!顺便说一句,你可以为你的“$home”价值做同样的事情。您可以使用您的页面 id 而不是使用get_option

标签: php wordpress wordpress-theming advanced-custom-fields custom-post-type


【解决方案1】:

我会使用WP_Query 的自定义查询:

<?php
$custom_query = new WP_Query(array(
  "post_type" => "common_modules" // use the name of your cpt here. The name when you register it using "register_post_type"
));

while ($custom_query->have_posts()) {
  $custom_query->the_post();?>
<h3><?php the_field('featured_text'); // you don't need to pass the second argument. it defaults to the current post in the while loop?></h3>
<?php };
wp_reset_postdata();
?>

<p><?php the_field('intro');?></p>

让我知道它是否适合你!


更新

<h3><?php the_field('featured_text', '495'); //You could use the id of that specific post to get the value of your acf field?></h3>

<p><?php the_field('intro');?></p>

<h2><?php the_field('header', '495');?></h2>

【讨论】:

  • 您在我的模板文件中以不同的风格编写 php。我如何以我的 php 格式编写您的代码?
  • 在您的模板文件中只包含打开和关闭 php 标签。我将编辑我的答案并为您添加这些标签,因此您可以“复制/过去”。
  • 我刚刚更新了我的答案,只需在您的模板文件中“复制/粘贴”它,如果它不为空,它将输出您的字段值!
  • 谢谢。它可以工作但不能正常工作,因为我的模板引用了主页 ACF 字段中的字段以及另一个字段组中的 ACF 字段。因此,当我添加您的代码时,它会从我的主页组中获取字段,但不再从我的其他组中获取字段。这就是为什么我需要指定一个 $home 以便它知道专门从主页字段组中获取字段。这可能吗?
  • 是的,绝对可行!所以您已将这些field groups 分配给不同的自定义帖子类型?您有多少种“自定义帖子类型”?他们叫什么?我们也可以将这些添加到我们的$custom_query 中。
猜你喜欢
  • 2021-11-30
  • 1970-01-01
  • 2020-10-25
  • 2017-08-10
  • 1970-01-01
  • 2020-06-11
  • 2015-11-21
  • 2016-10-28
  • 2018-10-02
相关资源
最近更新 更多