Reputation: 256
I have an ACF field called sale_or_charter with three radio options – for sale, charter or new build.
Each custom post type will have one of these values – I would like to then display related posts that have the same value for the sale_or_charter field as the current page.
I can’t work out what I am doing wrong?
I have consulted the ACF documentation and it looks correct. When I remove the 'key' and 'value' - it works, but I need it filtered by posts that have the same $type as the current post.
Any help appreciated
<?php
$type = get_field( "sale_or_charter", get_the_ID() );
$args = array(
'post_type' => 'yachts',
'posts_per_page' => 3,
'orderby' => 'date',
'order' => 'DESC',
'meta_query' => array(
array(
'key' => 'sale_or_charter',
'value' => $type
)
),
);
$my_posts = new WP_Query($args);
if ( $my_posts->have_posts() ) {
while ( $my_posts->have_posts() ) : $my_posts->the_post();
EDIT** After adding the bounty, I decided to add a screenshot and (like an idiot) immediately realised I had it set to label and not Value which is the issue.
Upvotes: 1
Views: 6111
Reputation: 3684
Your issue is that your field is returning the "Label" and not the field value so the database query is not comparing the correct values.
Change the "Return Value" to Value
, see screenshot below.
Recommendation
I would also suggest excluding the current post from your results, this prevents the current post from appearing in your related items. For example...
$type = get_field( 'sale_or_charter', get_the_ID() );
$my_posts = new WP_Query([
'post_type' => 'yachts',
'posts_per_page' => 3,
'orderby' => 'date',
'order' => 'DESC',
'post__not_in' => [ get_the_ID() ], // Exclude current post
'meta_query' => [
[
'key' => 'sale_or_charter',
'value' => $type
]
]
]);
Upvotes: 1