I have 3 post types between which I need to build a relationship. I am able to build the relationship back and forth between 2 post types, that works fine.
Custom post types
product_range
has no relationship custom field
industry
has a relationship custom field with product_range
, field ID is related_product_range
reference
has a relationship custom field with industry
, field ID is related_industries
I need to display meta data of a reference
single page on a product_range
single page. These two are not directly related, but are via industry
.
So the goals is to display the title from the reference
posts that are related to industry
, but only from the industry
posts that are related to product_range
.
Right now I am using this to grab data from industry
into product_range
, but it needs some extending so it grabs data a stap further:
$options = get_field('portfolio', 'option');
$reference = new WP_Query(array(
'posts_per_page' => -1,
'post_type' => 'industry',
'meta_query' => array(
array(
'key' => 'related_product_range',
'compare' => 'LIKE',
'value' => '"' . get_the_ID() . '"'
)
)
));
if ($reference->have_posts()) {
echo '<h2>' . $options['reference']['title'] . '</h2>';
while($reference->have_posts()) {
$reference->the_post(); ?>
<h5><?php the_title(); ?></h5>
<?php }
}
wp_reset_postdata();
Any suggestions? 🙂
I am not exactly clear on the relationships but I gather that it’s something like
Post Type 1 <> Post Type 2 <> Post Type 3
and you want to show either Post Type 1 on Post Type 3 or vice versa.
To eliminate a lot of extra querying, the first thing I would do is to make these relationships bidirectional. This can be done by coding, although this doc is for bidirectional relationships on the same post type https://www.advancedcustomfields.com/resources/bidirectional-relationships/, or you can use a plugin like https://wordpress.org/plugins/post-2-post-for-acf/ and your can find some additional resources in my github repo https://github.com/Hube2/acf-filters-and-functions.
Then instead of doing queries you just get what you need without doing all the reverse relationship queries.
// get relationship field on current post
$related_x = get_field('1st relatioship field name');
foreach ($related_x as $related_x_post) {
$related_y = get_field('2nd relationship field', $related_x_post->ID);
}
You must be logged in to reply to this topic.
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.