Home › Forums › ACF PRO › How to get the number of posts from Relationship field – for "reverse" posts? › Reply To: How to get the number of posts from Relationship field – for "reverse" posts?
Hi there,
You can achieve this by looking into this page: http://www.advancedcustomfields.com/resources/querying-relationship-fields/. On the last code example, you can see that you need to query the posts using get_posts(). It will be something like this:
<!-- TESTrel_producers -->
<?php
$TESTrel_producers = new WP_Query( array(
'post_type' => 'producers',
'post__not_in' => array($post->ID),
'posts_per_page' => 20,
'orderby' => 'title', //change it if you want to order by something else
'order' => 'ASC',
'offset' => 0,
) );
?>
<?php if( $TESTrel_producers ): ?>
<div class="content_block_wrap two_columns_right col-md-6">
<div class="content_block transparent_block_with_border">
<div class="block_title">
List of posts of custom post type “producers”, with number of related “movies” posts:
</div>
<ul>
<?php
while ( $TESTrel_producers->have_posts() ) :
$TESTrel_producers->the_post();
?>
<?php
$the_movies = get_posts(array(
'post_type' => array( 'movies' ), // uncomment it if you only want to get the result from movies post type
'posts_per_page' => -1,
'meta_query' => array(
array(
'key' => 'movies_of_this_producer', // name of custom field
'value' => '"' . get_the_ID() . '"', // matches exaclty "123", not just 123. This prevents a match for "1234"
'compare' => 'LIKE'
)
)
));
?>
<li class="content_item col-xs-12">
<a class="post_thumbnail" href="<?php echo get_permalink( $TESTrel_producers->ID ); ?>">
<?php echo get_the_post_thumbnail( $TESTrel_producers->ID, '90x60-thumb' ); ?>
</a>
<a href="<?php echo get_permalink( ); ?>"><?php echo get_the_title( ); ?></a>
<span class="sm">Number of related posts:</span> <?php
echo $producer_count = count($the_movies);
?>
</li>
<?php
endwhile;
?>
</ul>
</div>
</div>
<?php endif; ?>
<?php
wp_reset_postdata();
?>
<!-- TESTrel_producers end -->
I hope that helps.
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.