I have created a custom post type 'CPT_A' with CPT UI plugin. I have also created custom taxonomy 'Category_A' and 'Category_B' for 'CPT_A'. I have Posts 'Post_A', 'Post_B', 'Post_C', 'Post_D', 'Post_E' for 'CPT_A' and assigned 'Post_A', 'Post_B', 'Post_C' them to custom taxonomy 'Category_A' and 'Post_D', 'Post_E' to category 'Category_B'.
I have created archive page 'archive-CPT_A.php' to display all posts of 'CPT_A' post type. and WP archive.php handles posts listings for all Categories of the 'CPT_A' Posts. And there is 'single-CPT_A.php' to display contents of single 'CPT_A' Post.
Now, What I am trying to do is I have created a sidebar and trying to display related posts of 'CPT_A' in sidebar. If the post is from 'Category_A' it should display other posts from same category and if the post is from 'Category_B' it should display other posts from 'Category_B' So I used this code:
<?php
$cats = get_terms('CPT_A');
$args = array(
'post_type' => 'CPT_A',
'post__not_in' => array( get_the_ID() ),
'posts_per_page' => 5,
'cat' => $cats[0]->term_id,
);
$query = new WP_Query( $args );
?>
<?php if( $query->have_posts() ) : while( $query->have_posts() ) : $query->the_post(); ?>
<li>
<a href="<?php the_permalink(); ?>"><?php the_title(); ?></a>
</li>
<?php endwhile; endif; wp_reset_postdata(); ?>
But it's displaying hiding current post from list (which is correct) but also displaying other posts from 'Category_B' too. After some research I tried this code:
<?php
$cats = get_terms('tour_category');
$args = array(
'post_type' => 'tour_package',
'post__not_in' => array( get_the_ID() ),
'posts_per_page' => 5,
'cat' => $cats[0]->term_id,
'tax_query' => array(
array(
'taxonomy' => 'tour_category',
'field' => 'slug',
'terms' => $custom_term->slug,
)
)
);
$query = new WP_Query( $args );
?>
<?php if( $query->have_posts() ) : while( $query->have_posts() ) : $query->the_post(); ?>
<li>
<a href="<?php the_permalink(); ?>"><?php the_title(); ?></a>
</li>
<?php endwhile; endif; wp_reset_postdata(); ?>
But it's displaying nothing for me.
What is the best way to do this? I didn't find any suitable tutorial for me so posting this question here.
cat
is not a general taxonomy query var, it is specifically for the built-incategory
taxonomy, and won't work with a custom taxonomy. In your second code block, you use$custom_term
, but you never give it a value.