Wordpress 高级自定义字段 - 在 PAGE 模板上显示

Wordpress Advanced Custom Fields - display on PAGE template

我在 Wordpress 中使用高级自定义字段。我已经设置了一个字段,可以像这样在我的 homepage/front-page.php 模板上显示它...

<?php the_field('primary_tagline'); ?>

我想在我的 page.php 模板上使用相同的字段,但是当我放入相同的代码时,没有返回任何结果。我不明白为什么它适用于一个模板而不适用于另一个模板。我是否需要不同的代码来跨多个模板显示相同的字段结果?这是代码...

   <?php the_field('primary_tagline'); ?>

    <div id="primary" class="content-area">
        <main id="main" class="site-main">
            <?php while ( have_posts() ) : the_post(); ?>
                <?php get_template_part( 'template-parts/content', 'page' ); ?>
                <?php
                    if ( comments_open() || get_comments_number() ) :
                        comments_template();
                    endif;
                ?>
            <?php endwhile; ?>
        </main><!-- #main -->
    </div><!-- #primary -->

是循环问题吗? ACF 不会在循环外显示?

是的,应该在post里面,因为这个字段是post的一部分。

如果您想在循环外获取字段值,您必须提供 post_id 作为函数的第二个参数

the_field($field_name, $post_id); //prints value
$value = get_field( $field_name, $post_id ); //returns value

ACF - get_field()

ACF - the_field()

像这样:

<?php $value = get_field( 'primary_tagline', 288 );
echo $value; ?>

我想这里的游戏有点晚了,但我想我会参与进来,以防其他人遇到这个问题。只是尝试做完全相同的事情,下面的解决方案相当于你的问题。

<?php global $wp_query;
$post = $wp_query->post; 
$variablename = get_field('primary_tagline', $post->ID);?>

您想调用 wp 查询并查找当前 post ID,然后使用变量查找该 post ID 的字段(当前页面 - 或指定的需要时提供 ID)。我只能假设变量将请求保留在全局循环查询中,因此 returns 循环外的实际值而不仅仅是 post ID .

然后要显示您的字段,您只需调用变量即可。

<?php echo $variablename; ?>

    <div id="primary" class="content-area">
        <main id="main" class="site-main">
            <?php while ( have_posts() ) : the_post(); ?>
                <?php get_template_part( 'template-parts/content', 'page' ); ?>
                <?php
                    if ( comments_open() || get_comments_number() ) :
                        comments_template();
                    endif;
                ?>
            <?php endwhile; ?>
        </main><!-- #main -->
    </div><!-- #primary -->

我在不使用变量的情况下尝试过,由于某种原因它只显示 post ID 的数值——我在网上注意到这是这个问题的一个常见问题。即使在 ACF 论坛上,我也发现了很多关于这个的问题。

希望对其他需要这样做的人有所帮助。

将 the_field 或 _get_field 附加到 get_option 应该有效..

<h1><?php the_field('heading', get_option('page_for_posts')); ?></h1>

来自他们的文档https://www.advancedcustomfields.com/resources/value-loading-posts-page/