Traversing multiple related CPTs
- This topic has 2 replies, 2 voices, and was last updated 3 years, 5 months ago by
anjo65.
-
AuthorPosts
-
November 22, 2021 at 1:51 AM #32085
anjo65
ParticipantHello,
I created the following CPTs and relationships: Trip > TripDay > Event; Trip to TripDay 1:m, TripDay to Event 1:m.
I am trying to create a query in MB Views that retrieves and displays data from a Trip, its associated TripDays and all events associated with each TripDay.
With the help of the following support topic https://support.metabox.io/topic/displaying-2-custom-post-types-via-a-relationship-custom-post-type/ I was able to create a working writing PHP code (see below).
<?php the_title(); ?> <?php $connected_tripday = new WP_Query( [ 'relationship' => [ 'id' => 'relationship-trip-to-tripday', 'from' => get_the_ID(), ], 'nopaging' => true, ] ); while ( $connected_tripday->have_posts() ) : $connected_tripday->the_post(); the_title(); $connected_event = new WP_Query( [ 'relationship' => [ 'id' => 'relationship-trip-day-to-event', 'from' => get_the_ID(), ], 'nopaging' => true, ] ); while ( $connected_event->have_posts() ) : $connected_event->the_post(); the_title(); endwhile; $connected_event->wp_reset_postdata(); endwhile; wp_reset_postdata(); ?>
However I would much rather accomplish this in MB Views but have been unable to so far. I am able to retrieve TripDays related to a trip but not Events related to a TripDay.
How can I accomplish this use case in MB Views?Thank you in advance.
AndyNovember 22, 2021 at 9:22 PM #32105Long Nguyen
ModeratorHi,
Here is an example code to show
tripday
andevent
from the singletrip
view. Screenshot https://imgur.com/P7nTxfm<h1>Trip: {{ post.title }}</h1> {% set tripday_args = { relationship: { id: 'relationship-trip-to-tripday', from: post.ID }, nopaging: true, post_type: 'tripday' } %} {% set tripdays = mb.get_posts( tripday_args ) %} <ul> {% for tripday in tripdays %} <li>Tripday: {{ tripday.post_title }}</li> {% set event_args = { relationship: { id: 'relationship-trip-day-to-event', from: tripday.ID }, nopaging: true, post_type: 'event' } %} {% set events = mb.get_posts( event_args ) %} <ul> {% for event in events %} <li>Event: {{ event.post_title }}</li> {% endfor %} </ul> {% endfor %} </ul>
Refer to this topic https://support.metabox.io/topic/query-in-relationship-post-per-page/
November 23, 2021 at 1:15 AM #32108anjo65
ParticipantHi Long,
Thank you. The provided code works perfectly.
Andy -
AuthorPosts
- You must be logged in to reply to this topic.