如何在页面模板中将ACF关系帖子显示为循环

时间:2019-04-02 17:08:07

标签: php wordpress advanced-custom-fields

我正在建立一个具有ACF Pro和Bootstrap设置的新网站。我尝试了各种不同类型的代码,以使用关系自定义字段显示来自自定义帖子类型的帖子。

以下代码当前显示该自定义帖子类型中的所有帖子,而不显示在自定义字段中选择的帖子。为方便起见,自定义帖子类型和字段名称都称为“供应商”

<div class="partners-container solution-container">
<div class="container">
  <div class="row">
    <div class="col-md-12">
      <h2 style="margin-bottom: 0px; padding-bottom: 0px; width: 100%; text-align: center;">
        Show posts below
      </h2>
    </div>
  </div>
      <?php 

query_posts('post_type=vendors');
$vendorposts = get_field('vendors');

if( $vendorposts ): ?><div class="row justify-content-md-center">
     <?php
            $args = array( 'post_type' => 'vendors' );
            $loop = new WP_Query( $args );
            while ( $loop->have_posts() ) : $loop->the_post(); ?>

  <div class="col-xs-6 col-sm-4 col-md-2"><a href="<?php the_permalink(); ?>"><?php the_post_thumbnail( 'single-post-thumbnail' ); ?></a></div>

  <?php endwhile; ?> </div>
    <?php wp_reset_postdata(); ?>
<?php endif; ?>       
    </div>
      </div>    

````````````````````````````````````````````````

1 个答案:

答案 0 :(得分:0)

尝试一下:

$vendorposts = get_field('vendors');

if( $vendorposts ): ?>
    <ul>
    <?php foreach( $vendorposts as $post): // variable must be called $post (IMPORTANT) ?>
        <?php setup_postdata($post); ?>
        <li>
            <a href="<?php the_permalink(); ?>"><?php the_title(); ?></a>
        </li>
    <?php endforeach; ?>
    </ul>
    <?php wp_reset_postdata(); // IMPORTANT - reset the $post object so the rest of the page works correctly ?>
<?php endif; ?>

文档:

ACF Relationship Field

Function Reference/setup postdata