treehouse : what would you like to learn today?
Web Design Web Development iOS Development

Run Loop on Posts of Specific Category

Last updated on:

<?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(); ?>
View Comments

Comments

  1. Jake
    Permalink to comment#

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

    • Webweaver
      Permalink to comment#

      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
      Permalink to comment#

      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. Permalink to comment#

    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
      Permalink to comment#

      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
    Permalink to comment#

    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
    Permalink to comment#

    where I have to placephp wp_reset_query();?

    • Permalink to comment#

      I personally place it after the ?php endwhile; endif; ?> I don’t know if it is a good practice but seen to work fine for me!

  6. Ben Yates
    Permalink to comment#

    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

  7. hamish
    Permalink to comment#

    Hey Chris,
    How would you add an if empty statement to this? Many thanks
    hamish

  8. Vinicius
    Permalink to comment#

    Thanks Mate! It really saved my life!!!!!!!

Leave a Comment

Use markdown or basic HTML and be nice.