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:
- 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
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.