Archived topic
Show Related Posts from same category - best way to do it
3 replies · Started by Jon on September 13, 2021
Hi -
I have created a hook and added the following code to display a list of related posts after my entry content:
<?php $orig_post = $post;
global $post;
$categories = get_the_category($post->ID);
if ($categories) {
$category_ids = array();
foreach($categories as $individual_category) $category_ids[] = $individual_category->term_id;
$args=array(
'category__in' => $category_ids,
'post__not_in' => array($post->ID),
'posts_per_page'=> 5, // Number of related posts that will be shown.
'ignore_sticky_posts'=>1,
'orderby'=> rand
);
$my_query = new wp_query( $args );
if( $my_query->have_posts() ) {
echo '<div id="related_posts"><h3>Related Posts:</h3><ul>';
while( $my_query->have_posts() ) {
$my_query->the_post();?>
<li>
<div class="relatedcontent">
<a href="<?php the_permalink()?>" rel="bookmark" title="<?php the_title(); ?>"><?php the_title(); ?></a>
</div>
</li>
<?
}
echo '</ul></div>';
}
}
$post = $orig_post;
wp_reset_query(); ?>
This is working fine for me but I've just read this post https://generatepress.com/forums/topic/related-popular-posts-widget/#post-1785158 which shows how to do it using the WP Show Posts plugin (which I'm already using elsewhere).
Which method is 'better' and if your suggestion is to use WP Show Posts how does it determine which related posts to show from within the category e.g. is it most recent or ? (you'll notice that in my code I have randomized the posts shown so that users don't see the same suggestions all the time & some of my older posts are surfaced.
Thanks in advance for any advice.
Hi Jon,
If you are satisfied with your current code, I would recommend keeping what you are using now as WP show posts is not a plugin specifically for the purpose of generating related posts :)
OK thanks
No problem :)