【问题标题】:ACF get_field not returning valueACF get_field 没有返回值
【发布时间】:2019-11-03 21:37:07
【问题描述】:

我正在尝试使用 get_field 返回一个简单的文本字段,但由于某种原因它返回空。字段本身就是它应该在的位置,并且其中有文本,因此该部分已全部设置。这个 PHP 代码是通过 php sn-p 加载的,例如发布缩略图,完美显示。因此,除了 ACF 字段值之外,一切正常。

<div class="your-class">
    <?php
    $args = array(
        'post_type' => 'home_test',
        'posts_per_page' => -1,
        'orderby'   => 'name',
        'order'     => 'ASC',
    );
    $the_query = new WP_Query($args);
    $brand = get_posts($args);
    foreach ($brand as $post) {
        setup_postdata($post);
        $thumbnail = get_the_post_thumbnail_url($post->ID, 'full');

        $homelinkvalue = get_field("home_brand_link");

        if (!$thumbnail)
            continue;
        ?>
        <div>
            <p><?php echo $homelinkvalue; ?></p><img src="<?php echo $thumbnail; ?>">
        </div>

    <?php
    }
    wp_reset_postdata();
    ?>
</div>

【问题讨论】:

    标签: wordpress loops advanced-custom-fields


    【解决方案1】:

    我认为问题在于您将自定义发布循环(您的 foreachsetup_postdata())混合在一起,但随后使用了 get_field() 之类的函数,这些函数利用了 global发布对象。在这种情况下,get_field() 尝试通过检查全局 $post 来查找字段值,但它尚未正确设置。请参阅警告here 关于setup_postdata($post)

    必须传递对全局 $post 变量的引用,否则 the_title() 之类的函数将无法正常工作。

    您可以在您的代码中实现这一点,只需稍作修改:

    global $post;
    foreach ($brand as $currPost) {
        $post = $currPost;
        setup_postdata($post);
        // Rest of code as normal
    }
    

    或者,由于get_field() 可以接受特定帖子作为参数而不是自动使用全局帖子,因此您可以更改:

    $homelinkvalue = get_field("home_brand_link");
    

    到:

    $homelinkvalue = get_field("home_brand_link",$post->ID);
    

    旁注:通常,推荐的迭代帖子的方法是使用special "WP loop" pattern,类似于:

    <?php while ( $the_query->have_posts() ) : $the_query->the_post(); ?>
        <!-- Do something -->
    <?php endwhile; ?>
    

    使用上述模式会在循环时自动设置全局$post 变量,这允许开发人员使用get_field() 之类的函数,而不必担心显式传递特定的帖子;让事情变得容易一些。

    【讨论】:

    • 非常感谢,已解决! (第一个建议添加全局变量!
    【解决方案2】:

    试试这个:

    <div class="your-class">
           <?php
              $args = array(
                              'post_type' => 'home_test',
                              'posts_per_page' => -1,
                              'orderby'   => 'name',
                              'order'     => 'ASC',
              );
              $the_query = new WP_Query( $args );
              if ($the_query->have_posts) :
                  while($the_query->have_posts) : $the_query->the_post();
              ?>
           <div>
              <p><?php the_field( "home_brand_link" ); ?></p>
              <img src="<?php the_post_thumbnail_url(); ?>">
           </div>
           <?php
              endwhile;
              wp_reset_postdata();
              endif;
              ?>
        </div>
    

    【讨论】:

      猜你喜欢
      • 2014-09-13
      • 2017-05-28
      • 2019-11-16
      • 2020-03-04
      • 2016-05-01
      • 1970-01-01
      • 2017-08-22
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多