How to Show Related Posts for Custom Post Type in WordPress

Related posts in WordPress is the very useful to engage the audience of your website. WordPress gives you the capability to show the related posts of a specific post type. Display the related post of the article is very easy and you can add related posts list to your blog without using any plugin.

If you want to show related posts for custom post type, the posts need to be fetched by custom taxonomy terms of custom post type. In this tutorial, we will show how you can easily display the related posts for custom post type in WordPress. You don’t need to use any WordPress plugin for showing the related post of custom post type.

Generally, specific post details page (single.php) is used for custom post type. Open the single-custom_post_type.php file and place the following code where you want to display the related posts list of custom post type. This code will get posts of the same custom post type and same custom taxonomy terms of the current single post.

<?php

//get the taxonomy terms of custom post type
$customTaxonomyTerms wp_get_object_terms$post->ID'your_taxonomy', array('fields' => 'ids') );
//query arguments
$args = array(
    
'post_type' => 'your_custom_post_type',
    
'post_status' => 'publish',
    
'posts_per_page' => 5,
    
'orderby' => 'rand',
    
'tax_query' => array(
        array(
            
'taxonomy' => 'your_custom_taxonomy',
            
'field' => 'id',
            
'terms' => $customTaxonomyTerms
        
)
    ),
    
'post__not_in' => array ($post->ID),
);
//the query
$relatedPosts = new WP_Query$args );
//loop through query
if($relatedPosts->have_posts()){
    echo 
'<ul>';
    while(
$relatedPosts->have_posts()){ 
        
$relatedPosts->the_post();
?>
        <li><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></li>
<?php
    
}
    echo 
'</ul>';
}else{
    
//no posts found
}
//restore original post data
wp_reset_postdata();
?>

Specify the custom post type in post_type and custom taxonomy term of that post type in taxonomy. Also, specify the number of related posts in posts_per_page that you want to show.

Are you want to get implementation help, or modify or enhance the functionality of this script? Click Here to Submit Service Request

If you have any questions about this script, submit it to our QA community - Ask Question

7 Comments

  1. David Said...
  2. Devid Cols Said...
  3. Rokun Said...
  4. Erfan Said...
  5. Luiz Said...
  6. Arjun Amgain Said...
  7. Sagar Nandwani Said...

Leave a reply

keyboard_double_arrow_up