Related Posts In Custom Post Type
in the main loop, we create a related article in the main loop is simple but this is not easy, not everyone knows. this article I will guide you to create related posts for custom post type
Here is the code, you copy and past the place where you want to display related posts, the file is usually structured as follows: single-post-type-name
//Get array of terms
$terms = get_the_terms( $post->ID , 'product_tags', 'string');
//Pluck out the IDs to get an array of IDS
$term_ids = wp_list_pluck($terms,'term_id');
//Query posts with tax_query. Choose in 'IN' if want to query posts with any of the terms
//Chose 'AND' if you want to query for posts with all terms
$second_query = new WP_Query( array(
'post_type' => 'products',
'tax_query' => array(
array(
'taxonomy' => 'product_tags',
'field' => 'id',
'terms' => $term_ids,
'operator'=> 'IN' //Or 'AND' or 'NOT IN'
)),
'posts_per_page' => 3,
'ignore_sticky_posts' => 1,
'orderby' => 'rand',
'post__not_in'=>array($post->ID)
) );
//Loop through posts and display...
if($second_query->have_posts()) {
while ($second_query->have_posts() ) : $second_query->the_post(); ?>
<div>
<?php if (has_post_thumbnail()) { ?>
<a href="<?php the_permalink() ?>" title="<?php the_title(); ?>"> <?php the_post_thumbnail( 'related_sm', array('alt' => get_the_title()) ); ?> </a>
<?php } else { ?>
<a href="<?php the_permalink() ?>" title="<?php the_title(); ?>"><?php the_title(); ?></a>
<?php } ?>
</div>
<?php endwhile; wp_reset_query();
}
in the above code you change something like this, “parameter product_tags” you change to the other term you want eg: price, size … that you have declared in the taxonomy
the ‘post_type’ => ‘products’ you instead of “products” in Post Type that you have declared in the function.
I wish you success