Home › Forums › General Issues › Relationships Query Help
Hi there,
I’m using ACF on a custom post type called Special Offers, to allow a user to select what Posts the Special Offers should be displayed on.
So basically in single.php I want to display a Special Offer, if the Current Post is one of the posts selected in the backend. Hard to explain properly.
I have some of the code but it doesn’t seem to work how I think it should and was wondering if you may be able to help.
The code I have is:
<?php
// args $args = array( ‘numberposts’ => -1, ‘post_type’ => ‘special_offers’, ‘meta_key’ => ‘applies_to’, ‘meta_value’ => ‘”‘ . get_the_ID() . ‘”‘, );
// get results $the_query = new WP_Query( $args );
// The Loop ?> <?php if( $the_query->have_posts() ): ?>
<?php endwhile; ?>
<?php endif; ?>
<?php wp_reset_query(); // Restore global post data stomped by the_post(). ?>
I’ve actually managed to work this out myself. I used a different method, get_posts, and I also used meta_query to return an array and compare the page ID to the custom field. So my final code looked like this:
<?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;
?>
The topic ‘Relationships Query Help’ is closed to new replies.
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.