Own your WordPress loop with wp_query

14 Apr, 2008 The Loop

Image by yaz36

The WordPress loop is arguably the heart of any WP powered site. With all this power at its fingertips, it obviously has some serious customization potential. I’m going to explain a couple of ways here of how you can fully use the potential of your WP CMS’s loop to display custom content anywhere on your site. Get ready to own your WP Loop!

The Scenario

Remembering that content is king, I always recommend to my clients that they have a blog of some sort: a style blog, Pokerblog, Tech blog – whatever it is they do, they need a blog. Thus somewhere in your custom WP theme, you’re going to want to display maybe the latest 2 or 3 articles from their blog. Usually, you could just use query_posts() to bring in posts from a specific category.

However, I’ve found in the past that if I use this method before the normal loop for the page’s content, it messes with the functionality of the main loop because of issues with rewind_posts() and such.

To altogether avoid this issue, it’ll be best if you get used to making your own WP query.

Making your loop

Before looping, you need to tell WordPress what to loop through. So firstly, setup your query.

 $recentPosts = new WP_Query();

Then you can join it up with a loop to process the information that your query finds.

<? while ($recentPosts->have_posts()) : $recentPosts->the_post(); ?>
<?php endwhile; ?>

So when you add it all together:

 $recentPosts = new WP_Query();
 while ($recentPosts->have_posts()) : $recentPosts->the_post();
<?php endwhile; ?>

The query itself can have many different arguments to help you filter down to exactly what you’re looking for. For example:

  • cat=3 – specify the category that you want to display. If you have more posts that you want to include than exclude, then it might be easier to just filter out the ones you don’t want to see by using: cat=-1, -2, -3 etc
  • showposts=3 – specify how many posts you want to show
  • orderby=name – determine how you want your results to be ordered by: author, date, category, id, title, modified, parent and rand. orderby=rand is a great means of having a news area that displays a random news article from the archives.
  • year=2004 – display posts from only a specific year

You can string a whole bunch of these arguments together like so:

<? query_posts('cat=3,4,5&showposts=10&orderby=date'); ?>

With a little imagination, your query can retrieve any number of configurable results.


  1. So easy and powerfull!
    Thanks for the tip.


  2. Thank you so much for this! After hours of attempts, this is the only thing that has worked exactly as needed!

    I am displaying posts within a page by specific category. I will use this for quite a few different pages so, many, many thanks.

  3. Glad to have helped :)

  4. How do I loop through categories? For example, I have a static home page, and I want to loop through each category and inside that, display the last 5 posts in that category… “wp_list_categories” is close, but I don’t really want to output links to the categories, any ideas?

  5. you can use this $recentPosts = new WP_Query($query_string . ‘&showposts=10′);

  6. Great, thanks!
    How do you make the comments (3 comments, leave a comment) shop up in these loops? Adding the regular comment_popup doesn’t seem to work.

  7. b02y3hpu6s1esm6g

  8. Curious who you could have the post to the right and the post info (author, date, etc) on the left directly next to the title.

  9. I wish cutomizing theme wp max, do you may explain me please the folllowing statementes (within showposts)?
    Noticias recientes

    query(‘showposts=’.$mytheme['latest'].’&cat=-’.$mytheme['video'].’,-’.$mytheme['biblia']); ?>

    have_posts()) : $latest->the_post(); ?>

    thanks a lot

  10. I’m new to WP – I created a custom field called synopsis for my static pages.

    My goal is to create a site map that lists the title [linked] and a short synopsis of the page.

    I’m stuck, not understanding how to use a loop …

    I’m able to create the link list:

    if ($children) { ?>

    Or echo the post meta key “synopsis” on the same page as the post:

    ID, $key, true); ?>

    I want my first loop to include the second output for each iteration.

    I struggling with finding a clear example of looping the list of pages getting an ID to output post meta data.

    Seems like this would be someting folks would want to do?

    Any thoughts?

    Will return the sysnopis.

  11. sorry look like the blog stripped the tags. Email me for the full source example of the problem

  12. Man, this is exactly what I need. I’ve just spent all afternoon looking for a solution, and this is perfect. Thanks!

  13. hi, thanks a lot for this nice article, its work for my WP site

  14. Great post!!!

    Would you know how to grab the two most recent posts (with excerpt), then show the next three post titles (Just the Titles)?

    Thank you!

  15. you just saved me a couple hours of work! Thank you so much.

    It looks like i can go grab a coffee!

  16. Hey Josh, what you may be able to do (and this may not be the best way to do it…

    you could 1, do a query for just that one post you want the excerpt for

    while ($recentPost->have_posts()) : $recentPost->the_post();

    <a href=”">Read More»

    Then do another query for the next 3 post titles?

    while ($onlyTitles->have_posts()) : $onlyTitles->the_post();

    You could put that in an include and put it in your header, or wherever you want it. I actually haven’t tested that code, so it may not even work. But that may give you an idea of what to look for?

    Hope it helps.

  17. well, it stripped out the php code. email me if you haven’t found out how to do what you’re trying to do.

  18. Not sure why more people don

  19. is there a way to add the category name with the post title
    so if it had a category name of category 1 and post titles of post 1 and post 2 it come out as:
    category 1 post 1
    category 1 post 2
    anyway to do that?

  20. nvm i just figured it out…

  21. any idea son how to use a search keyword filter with wp_query? I’m using several custom wp_queries with filters for different authors in place of the loop but it breaks the search and displays everything regardless of the keyword.

  22. Great!
    clear and usefull!
    you saved my day :)

  23. Cool – thanks for this. I’ve been trying to create a another loop in the sidebar and didn’t want to use the query_posts function twice. Cheers

  24. Hi,

    I eventually got this

    however if i wanted to add more pages $my_query->query(‘page_id=2,3,4 etc
    it wont show the other pages just teh first one

    please any ideas

  25. you definitely love fr.findfashiontalent at my estore

  26. this code is a different approach than i derived. thumbs up!

    but what if i want pagination of the results? can i do that with page_navi()?
    please help!

  27. Coping With Spine Ache

    Lots of back once again discomfort is resulting from muscle mishaps.
    Ligament injuries or strains may possibly lead to harm on your back again in
    numerous approaches. The following put up provides you
    some great ideas about managing spine pain. All over again
    discomfort generally is not very long lasting, nevertheless it really is difficult to cope with.

    Distribute the fats you carry evenly. Inside affair
    you find yourself carrying difficulties generally,
    use a backpack which spreads the unwanted excess
    weight throughout your rear evenly.

    Relaxation can ease your again discomfort. A person relaxation tactic
    is continually to enable your whole body to totally loosen up and go limp whenever you lie straight lower.
    Then, you can alternately tense up right after which it acquire it uncomplicated certain muscular tissues to
    carry a sensation of reduction. In these types of a way, you will be
    capable of experience whole relaxation and improved versatility.

    Recall within just your posture in any way periods.
    Keep the back again straight, ft for that ground,
    and elbows towards the sides. Area your neck within a very at ease straight placement by adjusting your distance from the laptop.

    Employ heat for the yet again when it genuinely is hurting.
    The warmth will obtain the job carried out to dilate your blood vessels which can be located inside
    your spine, and help to stimulate circulation; which will
    raise the flow from the oxygen in the direction of the
    muscle group, as a result supplying support.
    Chances are you’ll use heating pads although seated or whilst laying in mattress.

    A prevalent lead to of yet again ache could be a lousy computer system configuration. Your monitor must be at eye levels, along with your keyboard and mouse seriously really should be in front of you if you endure from back discomfort and employ a do the job at a laptop.

    Starting working with the basics is suggested when coping with discomfort inside of your rear yet again. Even resting your back again for a few of days and nights may possibly help ease ache. Opt for ibuprofen, acetaminophen, or each other anti-inflammatory medicine to ease your back all over again discomfort while that you are resting. Cold compresses can serene inflamed tissues, and warmth could be beneficial in soothing restricted muscle tissue.

    Commonly consider your back again once again discomfort seriously. Many individuals ignore the indicators that their human body is sending them. They may attempt to stroll apart from their ache, or ignore it. An excessive quantity of motion could make ache worse. The discomfort will resolve by itself sooner in case you rest, choose it effortless and deal with the ache.

    In the event you work out correctly, it is attainable to minimize your once again discomfort a superb deal. If you’ve got acquired a important all over again accidents, consult your medical physician prior to starting any kind
    of bodily work out prepare or actual remedy.
    These kinds of routines, which consist of excess fat lifting or stretching, can considerably improve the power
    within just your muscular tissues and offer you considerably additional versatility.

    When your muscle groupings are effective and adaptable, they’ll do a greater location of protecting your spine.

    Cross your legs when you will most likely be seated for any extended time frame. When your legs are crossed, your muscle tissues within your spine and hip are employed, so these muscle tissue are accomplishing 1 issue even when sitting. Be specific to range the leg which you cross from time available for you to time, as this may possible steer clear of placing all while using anxiety on a single part with the physique.

    Eat a well balanced diet plan plan abundant in nutrients and healthy vitamins, at the same time as adequate normal water to keep up by on your own hydrated. Consuming a effectively-properly well balanced consuming habits and obtaining ample h2o can truly forestall rear again discomfort and facilitate healing. Not merely can it allow you to remain thin, which avert back again ache issues, nevertheless it also emits other nutrients and chemical compounds that decrease your chance of producing the ache worse.

    Most individuals absolutely grasp what it suggests to own rear once again discomfort. They have maybe knowledgeable rear discomfort inside the previous, or have it now. The jot down-up that you might have just go through provided you with some helpful all over again ache strategies, now it’s all approximately you to set them
    into actions. Acquire some time towards the by yourself,
    and goal on your own rear pains.

  28. Hello,
    I thoroughly value your site on Own your WordPress loop with wp_query and of course will
    be back again…

  29. I think the admin of this site is genuinely working hard in favor of his web page, because here every data is quality based stuff.

  30. I like to share understanding that will I’ve accrued with the 12 months to assist improve group overall performance.

  31. Please let me know if you’re looking for a writer for your site. You have some really great posts and I think I would be a good asset. If you ever want to take some of the load off, I’d love to write some
    material for your blog in exchange for a link back to mine.
    Please blast me an e-mail if interested. Kudos!

  32. Thanks for sharing your thoughts about how to human hair extensions hair extens.


  33. whoah this weblog is fantastic i love reading your
    articles. Keep up the great work! You recognize, a
    lot of persons are hunting round for this
    info, you can aid them greatly.

  34. Greate article. Keep posting such kind of information on your
    blog. Im really impressed by your blog.
    Hi there, You’ve done an incredible job. I will certainly digg it and in my opinion suggest to my friends. I am sure they’ll be benefited from this web site.

  35. Hi there, I think your website could possibly be having internet browser compatibility issues.
    When I look at your website in Safari, it looks fine however, if
    opening in I.E., it has some overlapping issues. I just wanted to provide you with a
    quick heads up! Apart from that, wonderful site!

  36. It’s going to be ending of mine day, except before finish I am
    reading this impressive paragraph to increase my knowledge.

  37. Thanks for this wonderful content. I really enjoyed it a lot.
    What you have done is pretty inspirational.
    This is really inspirational content. I would like to use your style to better my own content on my website.

  38. I enjoyed your content that ya made. :)

  39. I’m not that much of a internet reader to be
    honest but your sites really nice, keep it up!
    I’ll go ahead and bookmark your site to come back later on.
    Many thanks

  40. Boats with seating in the front, like theTyrrell P34, and another advantage is that you should not miss out
    on the ver amazing attractions of this city. The Azera is priced competitively with the Honda Accord and Toyota Camry but
    when the standard equipment is considered car service richmond va the safest bet in the used car buyers will be willing to pay.

  41. Inspiring ques there. What occurred after? Good luck!

  42. I enjoy what you guys are usually up too.

    Such clever work and exposure! Keep up the great works
    guys I’ve incorporated you guys to my own blogroll.


  1. BaoBao Festival Website | Moon Goose Designs | WordPress Website Design and Development | Boulder, Colorado

Leave a Reply

About The WordPress Guru

Over the last 4 or 5 years, I’ve been digging into the Wonders of WordPress. From the days when the Classic theme was the shizz until now, WordPress has gone from strength to strength both as the blogging platform of choice for many big players and as a CMS with...

Learn more »