ankara escort bayan ankara escort bayan ankara escort
How to show related posts Archives - WpDevcodes

Tag Archives: How to show related posts

Display Related posts in WordPress it’s very useful to drive the audience of your website. Using WordPress we can show the related posts of a specific post type. To display the related post of the contents it’s very easy and you can display related posts to the blog page without using any plugin.

To show related posts for custom post type, all the posts needs to be achieved by custom taxonomy-terms of the custom post type. In this tutorial, we will show you how to display the related posts for custom post type in WordPress. No need to use any extra plugin for showing related posts for custom post type in WordPress.

There default post details page is single.php. But when when we create custom post type in that case we need to create another php file for the custom post type. The php file should be like this single-custom_post_type_name.php. Open this file and add this following code to display related posts for custom post type in WordPress.

<?php
//get the taxonomy terms of custom post type
$customTaxonomyTerms = wp_get_object_terms( $post->ID, 'your_taxonomy_name', array('fields' => 'ids') );

//query arguments
$args = array(
'post_type' => 'your_custom_post_type_name',
'post_status' => 'publish',
'posts_per_page' => 6,
'orderby' => 'rand',
'tax_query' => array(
array(
'taxonomy' => 'your_custom_taxonomy_name',
'field' => 'id',
'terms' => $customTaxonomyTerms
)
),
'post__not_in' => array ($post->ID),
);

//the query
$relatedPosts = new WP_Query( $args );

//loop query
if($relatedPosts->have_posts()){ ?>
<div class="post_repeat">
<?php while($relatedPosts->have_posts()){
$relatedPosts->the_post();
?>
<div class="content"><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></li></div>
<?php
} ?>
</div>
<?php }else{
//no posts found
}

//restore post data
wp_reset_postdata();
?>

Here custom post type declared in post_type and custom taxonomy term of that post type in taxonomy. Also, specified the number of related posts in posts_per_page that you want to display.