简体   繁体   中英

How to display ACF relationship posts as a loop in a page template

I'm building a new website which has ACF Pro and Bootstrap setup. I have tried various different types of code to display posts from a custom post type using a relationship custom field.

The below code currently display ALL posts within that custom post type and does not display the ones chosen in the custom field. For ease, both the custom post type and field name is called 'Vendors'

<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>    

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

Try this:

$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; ?>

Documentations:

ACF Relationship Field

Function Reference/setup postdata

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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