In this article we will learn about “How to show Related Posts for Custom Post Type in WordPress“. In WordPress, Related post is very important to engage the visitors of your website.
Wordprss provides us the capability to display the related posts of specific post category type. Show the related post of the any category article is very simple and you can add related posts list to your blog without using any wordpress plugins.
If you want to show related posts for custom post type, then you need to be fetched by custom taxonomy terms of custom post type. You do not need to use any plugin for related post of custom post type.
Here you will learn where you need to change code for custom post type. Generally, Single post details page (Single.php) is used to dislay custom post type. You need to open “single-custom_post_type.php” file and place the below code where you want to display the related posts of custom post type. Below code will get post of the same category custom post and same custom taxonomy terms of the current single post.
Single-custom_post_type.php
2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 |
<?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(); ?> |
Pradeep Maurya is the Professional Web Developer & Designer and the Founder of “Tutorials website”. He lives in Delhi and loves to be a self-dependent person. As an owner, he is trying his best to improve this platform day by day. His passion, dedication and quick decision making ability to stand apart from others. He’s an avid blogger and writes on the publications like Dzone, e27.co