Wordpress Code to Display Contents of One Category by Title

Posted by admin on January 8, 2010

This code was a PITA to find and i have a new ulcer forming that I am going to name, “Wordpress Codex.” What I wanted was to have just my most recent news items display separately from my articles and update dynamically in the body of an otherwise static homepage. (ie. NOT as a widget). You’d think this would be very basic in a blog.

As cool as blogs are about keeping things dynamic and up-to-date, there are certain things that human beings want to remain in a predictable location. Merging the two took a lot of digging and I don’t want to lose the code since I can think of several clients who could benefit from this.

It can be installed in the page appropriate template, but I wanted a bit more flexibility on where it appeared on my pages, so I put it directly into the post.

If you’re going to put it in a post, you need to run the Exec-PHP plugin.

Here is the precious code:

<ul>
<?php
global $post;
$myposts = get_posts(‘numberposts=5&offset=0&category=1′);
foreach($myposts as $post) :
setup_postdata($post);
?>
<li><a href=”<?php the_permalink(); ?>”><?php the_title(); ?></a></li>
<?php endforeach; ?>
</ul>

Which displays like:

This is displaying the latest 5 posts in my News and Events category, which is category ID 1.
To change which category it’s pulling from, identify the category ID number in the category page and swap out the number here:
category=1

To change the number of posts displaying, swap this number out:
numberposts=5

If you want to start the list of articles at the second one:
offset=1

Why would you want to do this last? Let’s say you want to feature the latest article at the top of the page and then have a list of the 5 previous. Then you might want the offset to be 1 rather than 0.

Enjoy! I know I am.

Post to Twitter Post to Delicious Delicious Post to Digg Digg This Post Post to Facebook Facebook Post to Reddit Reddit Post to StumbleUpon Stumble This Post

top