Hi,
I would like to display a few (related) posts from a custom post type by matching a custom field from the currently viewed ingle post.
So I have a Group field setup for Location Details (listing_location_details).
Within this group I have a select dropdown with predefined options for counties/states (listing_location_county).
I would like to display 4 posts that have the same county as the currently viewed post. I am using a custom single post template.
Here is my code at the moment which doesn’t display anything.
<?php
add_action( 'astra_entry_content_after', 'add_related_listings' );
function add_related_listings() {
echo '<h1>Related Listings</h1>';
global $post;
// get the value without the formatting so we can search it in the database
$location_county = get_sub_field('listing_location_county', $post->ID, false);
$args = array(
'numberposts' => 4,
'post_type' => 'post_type_listings',
'meta_key' => 'listing_location_details_listing_location_county',
'meta_value' => $location_county,
);
$the_query = new WP_Query( $args );
?>
<?php if( $the_query->have_posts() ): ?>
<ul>
<?php while( $the_query->have_posts() ) : $the_query->the_post(); ?>
<li>
<a href="<?php the_permalink(); ?>">
<?php the_title(); ?>
</a>
</li>
<?php endwhile; ?>
</ul>
<?php endif; ?>
<?php wp_reset_query(); // Restore global post data stomped by the_post().
};
?>
I have tried hard coding the meta_value to a county that I know has posts, but do not get any results either.
Any help would be appreciated, thank you.
This solved my issue: https://code.tutsplus.com/tutorials/show-wordpress-related-posts-with-taxonomy-and-a-custom-post-type–cms-32303
$productterms = get_the_terms( get_the_ID(), 'listing_location' );
if( $productterms ) {
$producttermnames[] = 0;
foreach( $productterms as $productterm ) {
$producttermnames[] = $productterm->name;
}
}
$args = array (
'post_type' => 'post_type_listings',
'tax_query' => array(
array(
'taxonomy' => 'listing_location',
'field' => 'slug',
'terms' => $producttermnames,
),
),
);
$the_query = new WP_Query( $args );
if( $the_query->have_posts() ): ?>
<section class="product-related-posts">
<?php echo '<h2>' . __( 'Related Posts', 'tutsplus' ) . '</h2>'; ?>
<ul class="product-posts">
<?php while ( $the_query->have_posts() ) : $the_query->the_post(); ?>
<li><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></li>
<?php endwhile; ?>
<?php wp_reset_postdata(); ?>
</ul>
</section>
<?php endif;
};
You must be logged in to reply to this topic.
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.