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


Wordpress Advanced Custom Fields - display on PAGE template

我在Wordpress中使用高级自定义字段。我已经设置了一个字段,可以在我的主页/fron-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_id作为函数的第二个参数

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

ACF-get_field()

ACF-字段()

如下:

<?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)。我只能假设变量将请求保持在全局循环查询中,因此返回循环外的实际值,而不仅仅是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 -->

我尝试过不使用变量,出于某种原因,它只显示帖子ID的数值——我在网上注意到这是这个问题的一个常见问题。甚至在ACF论坛上,我也发现了许多关于这方面的问题。

希望这能帮助到其他需要这样做的人。

用get_option附加the_field或_get_field应该可以。。

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

来源于他们的文件https://www.advancedcustomfields.com/resources/value-loading-posts-page/

是的,它应该在post内部,因为字段是post的一部分。