【问题标题】:Wordpress ACF get_field( ) not returning valueWordpress ACF get_field() 没有返回值
【发布时间】:2014-09-13 06:15:14
【问题描述】:

我正在为Wordpress 使用advanced custom field 插件。我很难在我的页面上显示field

基本上我已经创建了一个字段组并将id's 分配给该组的成员。然后我使用get_field('field_name') 函数将此字段的值存储在一个变量中,并将echo 存储在屏幕上。然而,这将返回false

我也尝试过使用the_field('field_name'),但这会返回null。然后我在某处读到如果您尝试访问 Wordpress 循环之外的字段,则必须将 post id 作为参数传递给 get_field()/the_field() 方法。

我试过了,结果还是一样...有人知道问题出在哪里吗?

这是我的代码:

<?php get_header();
      $postID = get_the_ID();
      the_field('the-title', $postID); //Nothing being returned...
      die(); 
?>

【问题讨论】:

  • 同样的问题你有想过吗?帖子 ID 存在,数据库中存在字段我正在呼应 get_field 和 nada。

标签: php wordpress advanced-custom-fields


【解决方案1】:

ACF 多了一项功能

get_fields([$post_id], [$format_value]);

返回提供的 ID 的值。 但是如果我们只提供 id 那么默认情况下它被认为是 post id

但如果您提供的 ID 不是帖子的 ID,而是用户、术语类别、评论和选项表 ID,那么您必须像这样为其添加前缀:

// Get values from the current post.
$fields = get_fields();

// Get values from post ID = 1.
$post_fields = get_fields( 1 );

// Get values from user ID = 2.
$user_fields = get_fields( 'user_2' );

// Get values from category ID = 3.
$term_fields = get_fields( 'term_3' );

// taxonomy name.
$term_fields = get_fields( 'category_3' );

// Get values from comment ID = 4.
$comment_fields = get_fields( 'comment_4' );

// Get values from ACF Options page.
$option_fields = get_fields( 'options' );

// using 'option'.
$option_fields = get_fields( 'option' );

如官方docs中所述

当我必须在需要类别术语 ID 值的项目上工作时,我发现了这一点。这在循环之外对我有用。

【讨论】:

    【解决方案2】:

    我遇到了这个问题。这是函数的格式:

    function get_field( $selector, $post_id = false, $format_value = true ) {
      // ...
    }
    

    我是这样使用它的:

    get_field( 'event_date', false, false) {
      // ...
    }
    

    【讨论】:

      【解决方案3】:

      如果您在使用get_field() 之前使用WP_Query(),则需要使用wp_reset_query() 函数重置查询。我希望它能解决这个问题。

      【讨论】:

      • 这通常是答案。使用多个模板部分(可能有许多从不重置的查询)会导致混淆。在这种情况下,即使使用 global $post 也无济于事。
      • 这解决了我的问题。谢谢!
      • 谢谢!终于解决了我的问题!
      【解决方案4】:

      您需要创建一个循环,然后在该循​​环内您可以检索数据。

      <?php while( have_posts() ) : the_post() ?>
           <?php $variable = the_field('the-title'); ?>
      <?php endwhile; ?>
      

      【讨论】:

        【解决方案5】:

        您在循环之外使用 get_the_ID()。

        http://codex.wordpress.org/Function_Reference/get_the_ID

        你可以试试:

        global $post;
        the_field( 'the-title', $post->ID );
        

        但这取决于你在哪个页面。

        这是在哪个模板文件中使用的?

        【讨论】:

        • 我建议避免拨打global - 至少拨打$GLOBALS['post']-&gt;ID,更好的是,只需使用get_queried_object_id() :-)
        猜你喜欢
        • 2019-11-03
        • 2019-11-16
        • 2020-03-04
        • 2017-05-28
        • 1970-01-01
        • 2016-05-01
        • 1970-01-01
        • 2020-05-20
        • 2017-08-22
        相关资源
        最近更新 更多