I am trying to output related posts of the current post by tag_ID
. With the current code, posts will output all posts from the property
tag instead of specific tag.
How can I only return posts based on the current posts tag_ID
?
<?php $post_tag = get_the_tags($post->ID)?>//Not sure if correct
<?php
$args = array(
'post_type' => 'property',
'tag' => $post_tag,
);
$related_posts = new WP_Query( $args );
?>
<?php while ( $related_posts -> have_posts() ) : $related_posts -> the_post(); ?>
<h2><?php echo get_the_title()?></h2>
//etc
<?php endwhile; wp_reset_query(); ?>
Solution:
Might not be the best solution but manages to query related posts that are within city
and the current posts tag.
$tags = wp_get_post_terms( get_queried_object_id(), 'city', ['fields' => 'ids'] );
// Now pass the IDs to tag__in
$args = array(
'post_type' => 'property',
'post__not_in' => array( $post->ID ),
'tax_query' => array(
array(
'taxonomy' => 'city',
'terms' => $tags,
),
),
);
$related_posts = new WP_Query( $args );