How to List the Last Post from a Specific WordPress Category with an Excerpt
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:
WordPress Tips
Hide the comments link when comments are closed.
- After array, list the categories that you want to include. In my example I am using three – facebook, pinterest and wordpress.
- &posts_per_page=1 – this says to show the last post in the specified category. If you want to show more than one post, you can increase this number.
- I use the excerpt field when writing my posts, which is why my excerpts are customized and are usually only one sentence. Most of this time this will be the first x number of words from the beginning of your post. You could also link the title of the post, if you didn’t want to use the excerpt.
- I linked the excerpt to the permalink for the post, so the user can click the excerpt and read the entire post.
Do you think this is useful? Do you think it’s something that you would use?
photo credit: zerojay
Keep Reading:
Did you enjoy this article? I can assist you with your WordPress or Facebook project. Contact me and I will provide you with an estimate. You can also connect with me on Facebook or follow me on Twitter. If you are looking for Hosting, WordPress Theme, Newsletter or other recommendations, please view my detailed list.











March 31, 2012 at 10:22 am
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
Ajith Edassery´s last post ..Moving to Genesis Framework and New Theme!
April 4, 2012 at 7:01 pm
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.