Web Thoughts

Oct 2, 2011 Category: Code

Dynamic Sidebar – Recent Posts of Current Category

My goal was to have a list of recent posts that are in the same category as the post being viewed. I found plenty of information for hard coding a list using the category slug or name. This is great if you are organizing your blog by set categories and you have that architecture all figured out. I don’t. I just want to make categories on the fly, and see where it leads. Eventually if I see a clear pattern I may hard code, but for now I want a dynamic solution.
I had 2 problems to contend with:

  1. My templates were based on the parent category ‘blog’ so archive.php was redirecting to archive-blog.php if the page was in the blog category. If I wanted my Dynamic menu to be created for a subcategory I had to be able to un-check ‘blog’ and still have archive.php redirect.
  2. Get the recent post list from the current category on single posts, archive and category pages to show up on my sidebar.

I cobbled together various blocks of code knowing very little PHP but through trial and error I got the results I was after. For now it works on my sub categories if I do not check off the parent categories.

Here is the code:


Problem 1: For all my blog template re-directs I added code to basically include all descendants (link to more info):

 <?php if ( ! function_exists( 'post_is_in_descendant_category' ) ) {
	function post_is_in_descendant_category( $cats, $_post = null ) {
		foreach ( (array) $cats as $cat ) {
			// get_term_children() accepts integer ID only
			$descendants = get_term_children( (int) $cat, 'category' );
			if ( $descendants && in_category( $descendants, $_post ) )
				return true;
		}
		return false;
	}
}
?>

post;
  if ( in_category( '13' ) || post_is_in_descendant_category( 13 ) ){
    include(TEMPLATEPATH . '/archive-blog.php');

    } else {
    include(TEMPLATEPATH . '/archive-portfolio.php');
    }
    ?>

Problem 2: This is the code I placed in my sidebar template to generate the recent posts in each current category:

I hope this saves someone some time!

<ul>
<?php
if(is_single() || is_category || is_archive):
global $post;
$categories = get_the_category();
foreach ($categories as $category) :
?>
<li>
More <?php echo $category->name; ?> Posts
</li>
<?php
$posts = get_posts('numberposts=-1&category='. $category->term_id);
foreach($posts as $post) :
?>
<li>
<a href="<?php the_permalink(); ?>"><?php the_title(); ?></a>
<?php the_excerpt(); ?>
<?php the_time(' M j, Y') ?>    
</li>
<?php endforeach; ?>
<?php
endforeach; endif ; wp_reset_query(); ?>
</ul>

Comments are closed.


All content Copyright 2024 by ISA Web Design and Consulting.

Irrera Studio Arts in Maine • (207) 322-5260