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.

Post a Comment