Code Snippet

Home » Code Snippets » WordPress » Run Loop on Posts of Specific Category

Run Loop on Posts of Specific Category

<?php query_posts('cat=5'); ?>
<?php if ( have_posts() ) : while ( have_posts() ) : the_post(); ?>
   <?php the_content(); ?>
<?php endwhile; endif; ?>

If you were to use this, for example, in a left sidebar which ran before the main loop on your page, remember to reset the query or it will upset that main loop.

<?php wp_reset_query(); ?>

Subscribe to The Thread

  1. Jake

    Is there a way to display a certain number of items and then have a link at the bottom for older posts?

    • Webweaver

      Yes to question1. I have imported the most recent posts of a category into my website by using query_posts('category_name=whatevernameyouuse &posts_per_page=6');

      I have not looked at linking just to older posts, I just linked to my blog but I bet there is a way to do it…

    • Webweaver

      Or for a more authoritative look at how to do recent posts, look on this website for the recent posts article. http://css-tricks.com/snippets/wordpress/recent-posts-function/

  2. veru nice..
    thanks for sharing..
    i need this tuts for my web project..

  3. I want to create a loop that contains only posts that are in two specified categories – I just don’t get how to do this. Is anyone here to help me out of this problem?

    • ubrayj02

      See where it says cat=5?

      <?php query_posts('cat=5'); ?>

      Make it say cat=5,6,7

      Then, you will have fetched posts from categories 5, 6, and 7.

      If you want to limit the number of posts, stick a “showposts” in there to make something like this:

      <?php query_posts("showposts=2&cat=13,14"); ?>

  4. Brian

    This is awesome. Where are the valid places I can use this snippet of code? I want to display a custom loop on a page.

  5. Ferik

    where I have to placephp wp_reset_query();?

  6. Ben Yates

    Hi,
    Your post was a great help.

    The only difficulty I am having is setting the category to show from an id entered into a custom field when writing the post.

    I’ve tried PHP echo and grabbing the field using a plugin but still struggling to set the category based on what the custom field value is.

    Any help would be greatly appreciated.

    Ben

Speak, my friend

At this moment, you have an awesome opportunity* to be the person your mother always wanted you to be: kind, helpful, and smart. Do that, and we'll give you a big ol' gold star for the day (literally).

Posting tips:
  • You can use basic HTML
  • When posting code, please turn all
    < characters into &lt;
  • If the code is multi-line, use
    <pre><code></code></pre>
Thank you,
~ The Management ~