Support

Account

Home Forums ACF PRO How to get the number of posts from Relationship field?

Solved

How to get the number of posts from Relationship field?

  • – I have custom post type “producers”.

    – And i have custom post type “movies”.

    – I have relationship field “movies_of_this_producer”.
    On the page of edit/creation new post of custom post type “movies” i have this relationship field “movies_of_this_producer”. And in this relationship field “movies_of_this_producer” i can choose a corresponding “producer” post.

    As a result, I have the correct relationship between “producers” posts and “movies” posts.

    For example, on the site I have post “Steven Spielberg” (post of custom post type “producers”), which is associated via relationship field “movies_of_this_producer” with 5 posts: “Jaws”, “Jurassic Park”, “Schindler’s List”, “The Terminal”, “Bridge of Spies” (5 posts of custom post type “movies”).

    Now i need to get for each “producers” post – the number of related “movies” posts (“movies” posts, related with the “producers” post via relationship field “movies_of_this_producer”)
    Question: How to get the number of related “movies” posts for each “producers” post? What should be the code for this?

  • Hi @danbo

    You can simply do a count on the relationship field.

    
    <?php echo $movie_count = count(get_field('movies_of_this_producer')); ?>
    
  • Hi @jonathan

    It’s work correctly in the case, when I need to get from Relationship field the number of posts – of custom post type “movies”: – given that on the page of edit/creation new post of custom post type “movies” i have this relationship field “movies_of_this_producer”. And in this relationship field “movies_of_this_producer” i can choose a corresponding “producer” post.

    But if i need to get (from Relationship field) the number of posts – of custom post type “producers”: – it’s work incorrectly.
    *Posts of custom post type “producers” – have the “reverse” relationship with posts of custom post type “movies” via relationship field “movies_of_this_producer”.

    I created a new topic with a detailed description of this problem and with my code examples: http://support.advancedcustomfields.com/forums/topic/how-to-get-the-number-of-posts-from-relationship-field-for-reverse-posts/

    Tell me please, what code should be used in case with posts, that have “reverse” relationship?

Viewing 3 posts - 1 through 3 (of 3 total)

The topic ‘How to get the number of posts from Relationship field?’ is closed to new replies.