This code will get the related posts of the current custom-post-type single post being viewed. This will get posts only of the same custom post type and the same category of the current single post. Obviously, this only works for your custom post type if you gave it support for ‘category’ when you registered it.
Use this code on the sidebar of
single.php, or on
single-custom_post_type.php. Use it to show a custom loop of related items on the sidebar or footer of the current single custom post.
Note: this code is only necessary for getting related posts by category of custom post types. For related posts by category of regular posts, see Related Posts By Category. Or, for related posts by custom taxonomy, rather than category, see Get Related Posts For Custom Post Type by Custom Taxonomy.
<!-- begin custom related loop, isa --> <?php // get the custom post type's taxonomy terms $custom_taxterms = wp_get_object_terms( $post->ID, 'category', array('fields' => 'ids') ); $args = array( 'post_type' => 'YOUR_CUSTOM_POST_TYPE', 'post_status' => 'publish', 'posts_per_page' => 3, // you may edit this number 'orderby' => 'rand', 'post__not_in' => array ( $post->ID ), 'tax_query' => array( array( 'taxonomy' => 'category', 'field' => 'id', 'terms' => $custom_taxterms ) ) ); $related_items = new WP_Query( $args ); // loop over query if ( $related_items->have_posts() ) : ?> <li class="widget widget_categories"> <h3 class="widget-title">Similar Posts</h3> <ul> <?php while ( $related_items->have_posts() ) : $related_items->the_post(); ?> <li><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></li> <?php endwhile; ?> </ul> </li> <?php endif; // Reset Post Data wp_reset_postdata(); ?> <!-- end custom related loop, isa -->
For this loop to work for you, you must make the following change to the code:
On line 9: change
YOUR_CUSTOM_POST_TYPE to the name of you custom post type. Leave in the single quotes.
You may optionally edit the HTML on lines 26–28, 32, 36, and 37. If left as is, it will show a list of 3 related posts. To show a different number of posts, you can change the “3” on line 11 to whatever number you need.