With WordPress, I wanted to display a list of the latest 5 posts from the category in which the displaying post is located. I needed to do this outside the loop because I wanted to list the posts in the sidebar. For the life of me couldn’t find anywhere on the net how to do this. Being as I wanted to display these in the sidebar, I had to work out a way of calling the cat_id globally. I’m no programer and at best can only edit or manipulate the simplest of variable, but finally mashed together an answer, several hours later o_O. Ordinarily, inside the loop one would only need to use get_the_category() but in this case the following code is required in order to pull the category ID for use outside the loop:
<?php
global $post;
$categories = get_the_category();
$category = $categories[0];
$sidebar_cat_id = $category->cat_ID;
$sidebar_cat_name = $category->cat_name;
?>
Notice I have included cat_name at the end, so that it can be called for a header perhaps, like so:
<h3>Latest Posts in <?php echo $sidebar_cat_name; ?></h3>
Next I wanted to list the latest 5 titles below the title. This was accomplished with the help of acquiring the $sidebar_cat_id.
<?php
$sidebar_related_query = new WP_Query(‘cat=’ . $sidebar_cat_id . ‘&showposts=5&offset=0&orderby=post_date&order=desc’);
while ($sidebar_related_query->have_posts()) : $sidebar_related_query->the_post();
$do_not_duplicate = $post->ID;
?><div class=”sidebar_recent_title” id=”post-<?php the_ID(); ?>”>
<a xhref=”<?php the_permalink(); ?>” rel=”bookmark”><?php the_title(); ?></a>
</div><?php endwhile; ?>
Et voila.
8 Comments. Leave new
Brilliant idea and excellent solution for using recent_posts by category outside the loop.
This might help me solve problem trying to display most viewed posts on side bar for each of the categories.
Thanks
Unfortunately when it come to the sidebar the $categories variable become null. I don’t know how to fix it yet.
Do you know how to fix that?
Thanks.
Good post.
Thanks for the great tips.
Hmm. Good.
Hi! Is it Okay if I ask anything kind of off topic? I’m trying to view this page on my iphone nonetheless it will not show up properly, do you may have any options? Thanks in advance!
Sorry. This website was built a long time ago and there are currently no plans to make it iPhone friendly.
I recommend that you try and use your mate’s Android handset while you’re out until you switch 😉
[…] I got this from: https://www.finaldesign.co.uk/blog/wordpress/displaying-the-latest-current-category-articles-in-the-s… […]