I want to connect companies with products using Advanced Customs Fields. These are some pages on my website:
www.example.com/companies/apple/
www.example.com/companies/microsoft/
www.example.com/products/iphones/
www.example.com/products/ipods/
For example I want to connect Apple with their products (iPhones and iPods).
I have added a relationship field in ACF that is called related_articles
that is only available when the pages parent is the /companies/-page.
So on Apple’s company-page – the products iPhones and iPods have been selected in the custom relationship field related_articles
.
On page.php I added the following:
<?php
$posts = get_field('related_articles');
if( $posts ): ?>
<?php foreach( $posts as $p ): // variable must NOT be called $post (IMPORTANT) ?>
<a href="<?php echo get_permalink( $p->ID ); ?>"><?php echo get_the_title( $p->ID ); ?></a><br>
<?php endforeach; ?>
<?php endif; ?>
On the page www.example.com/companies/apple/
the following is returned:
<a href="http://www.example.com/products/iphones/">iPhones</a><br>
<a href="http:// www.example.com/products/ipods/">iPods</a><br>
Which works exactly as I want.
The problem is that http://www.example.com/products/iphones/
and http:// www.example.com/products/ipods/
is empty. Here I want the relationship to be reversed and <a href="http://www.example.com/companies/apple/">Apple</a><br>
to be displayed. How can I solve this? Is it possible with a code that is compatible in both ways?
I do not wish to make a second “connection”, from products to the companies – this needs to be handeled from a single page and not two. Custom post types is also a no go.
Updated – New code from the Querying relationship fields documentation:
<?php
$related_articles = get_posts(array(
'post_type' => 'post',
'meta_query' => array(
array(
'key' => 'related_articles', // name of custom field
'value' => '"' . get_the_ID() . '"',
'compare' => 'LIKE'
)
)
));
?>
<?php if( $related_articles ): ?>
<?php foreach( $related_articles as $article ): ?>
<a href="<?php echo get_permalink( $article->ID ); ?>"> <?php echo get_the_title( $article->ID ); ?></a><br>
<?php endforeach; ?>
<?php endif; ?>
This dosen’t return anything (blank).
This is certainly possible – ACF allows for 2 way or reverse querying of related items. So, your product page, you could do the following (with your own relevant acf names)
The whole process is explained in detail on the ACF site: http://www.advancedcustomfields.com/resources/querying-relationship-fields/
Although, whether this is possible without using Custom Post Types, I’m not certain.