Most WordPress themes, by default, come with Recent Posts displayed automatically. Depending on the type of blog you run, it is possible that you would prefer to display Recent Posts per category. If this is the case, here is what you need to do to only display recent posts for specific categories.

First, you’ll want to find your Recent Posts code, which is usually found in the sidebar. It will look something like this:

<h2>Recent Posts</h2>
<ul>
<?php get_archives('postbypost', 10); ?>
</ul>

As always, make sure you have a backup of the file in question before making any changes. You’ll then want to replace the above code with the following code:

<ul>
<?php $recent = new WP_Query("cat=1&showposts=10"); while($recent->have_posts()) : $recent->the_post();?>
<li><a href="<?php the_permalink() ?>" rel="bookmark">
<?php the_title(); ?>
</a></li>
<?php endwhile; ?>
</ul>

Where is says cat=1, you’ll want to insert the number assigned to the category that you want to display the posts from. You can find this from your Manage -> Categories page. You can also adjust the number of posts to be displayed where it says showposts=10.

This could be useful to someone who wants to display the most recent few posts from a few different categories in their sidebar.

[via ReadyWPThemes]

Want automatic updates? Subscribe to our RSS feed or
Get Email Updates sent directly to your inbox!
Digg This | Stumble it | Add to Del.icio.us | | Print This

There Are 10 Responses So Far. »

  1. 1 Alexandre Pereira
    Wednesday, February 6th, 2008 at 8:45 am

    Thanks for the tip.

  2. 2 Alexandre Pereira
    Tuesday, February 19th, 2008 at 12:26 am

    One more question. How to show posts of various categories excluding the one we have put before, using the code above?

  3. 3 Brock Hamilton
    Saturday, July 26th, 2008 at 11:57 pm

    Exactly what I was looking for thanks. its amazing how the wordpress support forum just tells you to go figure it out for yourself,  but I can come here and get the answer. you guys rock.

  4. 4 Phil
    Monday, September 1st, 2008 at 11:27 am

    Hi, thanks, works a charm, I wondered how you would go about adding (and controlling the length of) a few lines of the article text to this.

  5. 5 John McCue
    Monday, December 22nd, 2008 at 3:10 pm

    Thanks for this tip. I’ve been trying to figure this out for a couple of months. Does this only work in the sidebar?

  6. 6 James Marr
    Tuesday, January 27th, 2009 at 10:12 am

    Great!!!
    Worked first time, tried loads of other tutorial but this was the best by far.
    Thanks for your help
    ;)

  7. 7 Sciabb
    Thursday, July 2nd, 2009 at 4:41 am

    I can’t get it to work, if after cat I place the name of the category it still shows me all posts. Instead of placing the name I tried to place a numeric value… but the result is that it shows me nothing if I place 0 and 4, it shows me all posts if I type 1,2 or 3. Can anybody help? thanks



Leave A Comment