how to show an excerpt from the first post in a category in wordpress

For I wanted to show the latest Book Club entry in the sidebar. For those of you who are not familiar with the way WordPress does its posts, it uses some funky wrapper functions to access (and sometimes print) the entries in your blog. The main wrapper function, and the one that controls most of the stuff on the page is called the_loop().

This might be getting too detailed… You probably just want to know how to do what I did. There’s a lot more details on about using multiple loops on one page, but basically, the technique I used was to specify a new loop by using one of its internal functions called WP_Query directly.

WP_Query() takes an argument that tells it to just get the latest post from the book-club category. That looked like this: <?php $bc_query = new WP_Query('category_name=book-club&showposts=1'); ?> This uses category slug (“book-club” in my case), which you can find by editing your category.

So then you can use the standard functions like the_title() and the_excerpt() in a while loop. So the whole thing looks like this:

<li><h2>Next Comic Book Book Club</h2>
<!-- Get the last post in the book-club category. -->
<?php $bc_query = new WP_Query('category_name=book-club&showposts=1'); ?>
<?php while ($bc_query->have_posts()) : $bc_query->the_post(); ?>
<a href="<?php the_permalink(); ?>" alt="Read more about the next book club meeting." title="Read more about the next book club meeting."><?php the_excerpt(); ?></a>
<?php endwhile;?>

…and yes, I know the_excerpt() creates paragraph tags, and anchor tags around paragraph tags probably doesn’t validate. Oh well.

One Reply to “how to show an excerpt from the first post in a category in wordpress”

  1. oops, will try again…

    you can lose the excerpt’s p tags like this …

    remove_filter(‘the_excerpt’, ‘wpautop’);

    just add the php tags

    hope that helps :)

Leave a Reply

Your email address will not be published. Required fields are marked *