Related custom posts with custom taxonomy

Related custom posts with custom taxonomy

For easy usage, here is query for related custom posts through custom taxonomy. Do changes for customposttype and customtaxonomy and of course use your CSS classes.

 

<?php

// get the custom post type’s taxonomy terms

$custom_taxterms = wp_get_object_terms( $post->ID, ‘customtaxonomy’, array(‘fields’ => ‘ids’) );
$cat_samelevel = $custom_taxterms[0]; // choose post with same level or parent level

// arguments
$args = array(
‘post_type’ => ‘customposttype’,
‘post_status’ => ‘publish’,
‘posts_per_page’ => 0, // you may edit this number
‘orderby’ => ‘rand’,
‘tax_query’ => array(
array(
‘taxonomy’ => ‘customtaxonomy’,
‘field’ => ‘id’,
‘terms’ => $cat_samelevel
)
),
‘post__not_in’ => array ($post->ID),
);
$related_items = new WP_Query( $args );
// loop over query
if ($related_items->have_posts()) :
while ( $related_items->have_posts() ) : $related_items->the_post();
?>

<div class=”three columns”>
<a class=”link” href=”<?php the_permalink(); ?>”>
<?php $thumb_id = get_post_thumbnail_id();
$thumb_url = wp_get_attachment_image_src($thumb_id,’category-img’, true); ?>
<div class=”category-img”>
<img class=”inline” src=”<?php echo $thumb_url[0]; ?>” />
</div>
<div class=”text inline”>
<p><?php the_title(); ?></p>
</div>
</a>
</div>

<?php
endwhile;

endif;
// Reset Post Data
wp_reset_postdata();
?>

Twitter
Facebook
LinkedIn
Telegram
WhatsApp
Email