For a recent project I wanted to do something a little different with the list of categories in the sidebar. Instead of simply listing each category, I wanted to list an excerpt from the last post in that category.
I wasn’t quite sure how to do this although I did know that I needed an array of the categories I wanted to use. After a little trial and error and asking a friend a question, I came up with the following piece of code.
<?php $cats_to_get = array('facebook', 'pinterest', 'wordpress'); ?> <?php foreach($cats_to_get as $cat_to_get): ?> <?php query_posts('category_name='.$cat_to_get.'&posts_per_page=1'); ?> <strong><?php single_cat_title() ?></strong> <?php while (have_posts()) : the_post(); ?> <a href="<?php the_permalink() ?>" rel="bookmark" title="Permanent Link to <?php the_title(); ?>"> <?php the_excerpt(); ?> <?php endwhile; ?> <?php endforeach; ?>
The code will produce the following:
Ajith Edassery says
I was in fact trying to change the homepage of my new theme with excerpts from various categories and finally gave up. I would have taken your piece of code had I stuck to my last theme.
Frustration is the right word with theme frameworks lol
Hillary says
Nice I had tried to do that before and got so frustrated I gave up and didn’t think about it again till now. Thanks for the fix.