Support

Account

Home Forums General Issues Relationships Query Help

Solved

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 while ( $the_query->have_posts() ) : $the_query->the_post(); ?>

    • <?php the_title(); ?><br /> <?php the_field(‘applies_to’); ?>
    • <?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;
    										
    ?>
Viewing 2 posts - 1 through 2 (of 2 total)

You must be logged in to reply to this topic.