Any help with this would be greatly appreciated - I've been grappling with it for days :)
I have 2 post types - product
+ offer
I have an ACF relationship field related_products
.
This field returns an array of post IDs Array ( [0] => 395 [1] => 120 [2] => 388 [3] => 391 )
I am using related_products
on the offer
post type - it's a one-way relationship (not bi-directional).
Each of my post types has a "card" template part that I use in all my loops - that's what I want to do here ... use the related_products
IDs to get the product
card parts and show them on the offer
.
I had no luck with the ACF documentation - but that's probably because I'm a noob.
- https://www.advancedcustomfields.com/resources/querying-relationship-fields/
- https://www.advancedcustomfields.com/resources/acf-fields-relationship-query/
Instead, I set up a custom WP_Query
that get's me close, but not there.
The if ( $custom_query->have_posts() )
IS working - when an offer
has related products, the correct product cards ARE displayed.
But, when an offer
has no related_products
, ALL products are being shown.
My questions are:
- Is a custom
WP_QUERY
the right/best way to go about this? - If so, what do I need to fix in the query?
Thank you for your time and help :)
// Array ( [0] => 395 [1] => 120 [2] => 388 [3] => 391 )
$related_products = get_field('related_products');
$args = array(
'post_type' => 'product',
'post__in' => $related_products,
'fields' => 'ids',
'cache_results' => false,
'update_post_meta_cache' => false,
'update_post_term_cache' => false,
'posts_per_page' => -1,
'paged' => false,
);
$custom_query = new WP_Query( $args );
if ( $custom_query->have_posts() ) :
while ( $custom_query->have_posts() ) :
$custom_query->the_post();
get_template_part( 'parts/card', get_post_type() );
endwhile;
else :
// do something else
endif;
wp_reset_query();