繁体   English   中英

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_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查询并找到当前的帖子ID,然后使用变量来查找该帖子ID(当前页面-或需要时指定的ID)的字段。 我只能假定的变量将请求保留在全局循环查询中,因此将实际值返回到循环外部,而不仅是发布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/获取

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM