I am having an issue figuring it out. I feel like it’s s simple answer but I can’t seem to get it.
My goal is to show the firs the posts of a custom post type and then show the first three items in a relationship field for each.
Here is my code:
<?php
$args = array(
'posts_per_page' => 3,
'post_type' => 'collections'
);
$the_query = new WP_Query( $args );
?>
<?php if( $the_query->have_posts() ): ?>
<?php while( $the_query->have_posts() ) : $the_query->the_post(); ?>
<div class="col-sm-4">
<h3>
<?php the_title(); ?>
</h3>
<div class="row">
<?php
$posts = get_field('books');
if( $posts ): ?>
<?php foreach( $posts as $post): ?>
<?php setup_postdata($post); ?>
<div class="col-xs-6 col-sm-4">
<a href="<?php the_permalink(); ?>">
<?php if (has_post_thumbnail( $post->ID ) ): ?>
<?php $image = wp_get_attachment_image_src( get_post_thumbnail_id( $post->ID ), 'book-thumbnail' ); ?>
<img class="img-responsive" src="<?php echo $image[0]; ?>" alt="<?php the_title(); ?>">
<?php endif; ?>
</a>
</div>
<?php endforeach; ?>
<?php endif; ?>
</div>
</div>
<?php endwhile; ?>
<?php endif; ?>
<?php wp_reset_query();?>
You can see here what I mean. I only want three books from each post to show.
Any help would be much appreciated.
I used a counter to solve this. Found a solution for the gallery field that worked the same way.
Here you go!
<?php
$posts = get_field('books');
$max = 3;
$i = 0;
if( $posts ): ?>
<?php foreach( $posts as $post): $i++; ?>
<?php if( $i > $max){ break; } ?>
<?php setup_postdata($post); ?>
<div class="col-xs-6 col-sm-3">
<a href="<?php the_permalink(); ?>">
<?php if (has_post_thumbnail( $post->ID ) ): ?>
<?php $image = wp_get_attachment_image_src( get_post_thumbnail_id( $post->ID ), 'book-thumbnail' ); ?>
<img class="img-responsive" src="<?php echo $image[0]; ?>" alt="<?php the_title(); ?>">
<?php endif; ?>
</a>
</div>
<?php endforeach; ?>
<?php endif; ?>
Well it’s 6 years old but thought I’d highlight another way to do this as I too used the counter solution but then discovered array_slice which is less verbose.
$posts = get_field('books');
$books = array_slice( $posts, 0, 3 );
foreach( $books as $post):
setup_postdata( $post );
the_title();
endforeach;
wp_reset_postdata();
The topic ‘First 3 of relationship field’ is closed to new replies.
Welcome to the Advanced Custom Fields community forum.
Browse through ideas, snippets of code, questions and answers between fellow ACF users
Helping others is a great way to earn karma, gain badges and help ACF development!
We use cookies to offer you a better browsing experience, analyze site traffic and personalize content. Read about how we use cookies and how you can control them in our Privacy Policy. If you continue to use this site, you consent to our use of cookies.