Lookhappy Design

12 March 2015

ACF Relationship Query

So this was a tricky one to wrap my head around, just because the logic makes sense, but is difficult to word.
So basically what I wanted to do was create a new Custom Post Type, which would have a selection list of all the published posts for you to be able to select to apply that Custom Post to, and then for the Custom Post to show up on whatever pages where selected.
I hit a snag with something I thought would work, but didn’t and then had a brainwave this morning. And here was the solution for anyone interested:

<?php
$special_offers = get_posts(array(
'post_type' => 'special_offers',
'meta_query' => array(
array(
'key' => 'applies_to', // name of custom field
'value' => '"' . get_the_ID() . '"',
'compare' => 'LIKE'
)
)
));

if( $special_offers ): 
foreach( $special_offers as $offer ):
// Do something to display the articles. Each article is a WP_Post object.

echo "<div class='special_offer'><h3>";
echo $offer->post_title;  // The post title
echo "</h3><span class='offer_text'>";
echo $offer->post_content;  // The post content
echo "</span></div>";

endforeach;
endif;
?>