How to Display Related Posts in WordPress Custom Theme


In this blog we will learn how to show related posts in WordPress custom theme. Here I will show you two ways how you can manually display related posts in your custom theme.

Related Posts in WordPress Custom Theme We also make our custom theme more attractive by filtering a post that is opened by its category ID and displaying related posts.

1. Add functions

2. Manually with custom code

How to Display Related Post Using Function

To display related posts using functions you need to open your functions.php file and put the following code in it.


// Function related_post_display

function example_cats_related_post() {

$post_id = get_the_ID();
$cat_ids = array();
$categories = get_the_category( $post_id );

if(!empty($categories) && !is_wp_error($categories)):
foreach ($categories as $category):
array_push($cat_ids, $category->term_id);
endforeach;
endif;

$current_post_type = get_post_type($post_id);

$query_args = array( 
'category__in'   => $cat_ids,
'post_type'      => $current_post_type,
'post__not_in'    => array($post_id),
'posts_per_page'  => '3',
);

$related_cats_post = new WP_Query( $query_args );

if($related_cats_post->have_posts()):
while($related_cats_post->have_posts()): $related_cats_post->the_post(); ?>

Now put in the single.php File where you want to show related posts.

How to Display Related Posts with Custom Code

Add the following code to your single.php File to Display Related Posts with Custom Code



Related Post

ID, 'category', array('fields' => 'ids') ); //query arguments $args = array( 'post_type' => 'post', 'post_status' => 'publish', 'posts_per_page' => 4, 'orderby' => 'rand', 'tax_query' => array( array( 'taxonomy' => 'category' , 'field' => 'id', 'terms' => $customTaxonomyTerms ) ), 'post__not_in' => array ($post->ID) ); //the query $relatedPosts = new WP_Query( $args ); //loop through query if($relatedPosts->have_posts()){ $imgpath = wp_get_attachment_image_src( get_post_thumbnail_id(),'large'); while($relatedPosts->have_posts()){ $relatedPosts->the_post(); ?>

How to Display Related Posts for Custom Post Type in WordPress

To Display Related Posts for a Custom Post Type in WordPress, you simply add the post type and category slug to the array.


Related Post

ID, 'category', array('fields' => 'ids') ); //query arguments $args = array( 'post_type' => 'News', 'post_status' => 'publish', 'posts_per_page' => 4, 'orderby' => 'rand', 'tax_query' => array( array( 'taxonomy' => 'News_category' , 'field' => 'id', 'terms' => $customTaxonomyTerms ) ), 'post__not_in' => array ($post->ID) ); //the query $relatedPosts = new WP_Query( $args ); //loop through query if($relatedPosts->have_posts()){ $imgpath = wp_get_attachment_image_src( get_post_thumbnail_id(),'large'); while($relatedPosts->have_posts()){ $relatedPosts->the_post(); ?>

Leave a Comment