Show related posts by Custom Taxonomy for each Individual CPT?

So I’m working on a single page in which I need to display the related posts by category, the problem is that the website comes with different CPT’s as well, so basically I need a function to show all the related posts by category and by custom post type without mixing it with the categories of a different CPT.

For example in the current code that I’m using, it shows all the related post by category but when I access to a different CPT it keeps showing me the related posts(category) from a different custom CPT…

I really dont know how to explain myself but is there a way to make it possible to show me the related post(Custom Taxonomy) of each individual CPT?. All the CPT have their own taxonomies as well.

This is my code so far:

<?php
$orig_post = $post;
global $post;
$categories = get_the_category($post->ID);
if ($categories) {
$category_ids = array();
foreach($categories as $individual_category) $category_ids[] = $individual_category->term_id;
}

$args = array(
‘category__in’ => $category_ids,
‘post__not_in’ => array($post->ID),
‘orderby’ => ‘rand author title name comment_count’,
‘posts_per_page’ => 10, // Number of related posts that will be shown.
‘ignore_sticky_posts’ => 1
);

$my_query = new wp_query( $args );
?>
<?php if(is_single()) : ?>

<?php if($my_query->have_posts()) : ?>
<div class=”row”>
<div class=”col-md-12″>
<h3 style=”margin-top:0px”>Posts Relacionados</h3>
<div class=”customNavigation”> <a class=”btn btn-default btn-sm prev”><i class=”fa fa-arrow-left” aria-hidden=”true”></i></a> <a class=”btn btn-default btn-sm next”><i class=”fa fa-arrow-right” aria-hidden=”true”></i></a> <a class=”btn btn-default btn-sm play”><i class=”fa fa-play” aria-hidden=”true”></i></a> <a class=”btn btn-default btn-sm stop”><i class=”fa fa-stop” aria-hidden=”true”></i></a> </div>
<div id=”owl-demo” class=”owl-carousel”>
<?php while($my_query->have_posts()) : $my_query->the_post(); ?>
<div class=”products text-center”>
<div class=”item”>
<a href=”<?php the_permalink();?>” target=”_blank”><?php the_post_thumbnail(array(‘class’ => ‘img-responsive’)); ?></a>
</div>
</div>
<?php endwhile; ?>
</div>
</div>
</div>
<?php endif; ?>
<?php endif; ?>
<?php
$post = $orig_post;
wp_reset_query();
?>

I hope I could make myself clear,
Thanks

Read more here:: Show related posts by Custom Taxonomy for each Individual CPT?

Leave a Reply

Your email address will not be published. Required fields are marked *