#91: The WordPress Loop

There is no shortage of documentation on WordPress' famous content-spewing structure, but I still feel like there is more confusion and mystery surrounding "The Loop" than there should be. In this screencast I try and explain what it is, how it works, related parts, and then demonstrate some alterations and various tricks. Things like running multiple loops, writing your own custom queries, and handling pagination with your own custom loops.

Links from Video:

Comments

  1. User Avatar
    Kawohi
    Permalink to comment#

    Chris, maybe you should include this post in your others? Not everyone will have a RSS reader to see your new screencast.

    Thank you for showing me the wordpress loop though!

  2. User Avatar
    Toni Kukurin
    Permalink to comment#

    Haha Chris, great stuff with WordPress! :D

    I must say that, although I was familiar with most of this stuff, after that eighth minute or so (the_excerpt) I had to watch it all the way through. It was basically awesome, just double squared.

    Man, you should really keep going with these videos way past the #100 (or #1000), we’d miss them too much. :)

  3. User Avatar
    Chris Vilchez
    Permalink to comment#

    Great screencast Chris! This will definitely help TONS of people who are getting caught up with custom query / pagination issues. I was just battling this myself but ended up using the paged variable differently. Just out of curiosity, what are the benefits of using the offset parameter vs the paged parameter?

    For example –

    <?php 
    	$paged = (get_query_var('paged')) ? get_query_var('paged') : 1;
    	$ppp = 2;
    	
    	query_posts("posts_per_page=$ppp&paged=$paged");
    ?>
    • User Avatar
      Chris Coyier
      Permalink to comment#

      Hey whatever works man =). That actually seems smarter to me. It’s too bad the $paged variable doesn’t return a 1 by default.

    • User Avatar
      Aaron
      Permalink to comment#

      I was having trouble with “offset” as /page/0/ == /page/1/ that was basically ruining everything for me. I battled for a while, saw this, used it and it work perfectly.

    • User Avatar
      Barry
      Permalink to comment#

      @Chris Vilchez I think I’m having the same problem you had right now, would you mind posting the full query? I’ve inserted what you have there into my query and the links show up but they don’t actually work (The same posts are shown on the “next” page”.

      Cheers!

    • User Avatar
      Chris Vilchez
      Permalink to comment#

      That’s really about all the code I’m using there. The paged parameter is what keeps track of what page you’re on and should change the posts.

      I have an ajax paginated section on my home page that calls out 10 posts at a time and excludes a certain category. I hope this helps! Let me know!

      <?php

      $paged = (get_query_var('paged')) ? get_query_var('paged') : 1;
      query_posts("posts_per_page=10&cat=-6&paged=$paged");

      if (have_posts()) : while (have_posts()) : the_post(); ?>

      // Posts Here

      <?php endwhile; endif; ?>

    • User Avatar
      Balka
      Permalink to comment#

      Awesome, thanks Chris

  4. User Avatar
    Natalie
    Permalink to comment#

    Great screen cast Chris.

    I have muddled through this before (even making my own custom query loops), but not truly understanding the mechanics behind it. All trial and error until I got it to behave the way I wanted to. After this, I am going back to check out my code to more fully get it. Thanks for this one!

  5. User Avatar
    Merlot
    Permalink to comment#

    I love your video’s… especially because I am obsessed with php and wordpress right now. Do some more on MAMP! I actually went backwards and took my site from the web and imploded it into the local host. I’m kinda hoping this route is the “more difficult” way because of all the trouble I’ve run into… and exploding it back to the server will be much easier.

  6. User Avatar
    Alistair
    Permalink to comment#

    Thanks Chris,

    I never quite understood why multiple loops don’t work, having applied wp_reset_query() it was entirely the wrong context. It was after a custom loop altogether and not the query string. It will never make sense :s.

    Anywho, this live example really helped when you said passing over variables instead of parameters to query_posts it gave a deeper understanding of how WP is built. i guess they use stored procedures. Really gives good cause to look more into the core files and functions of WP moreso now.

    Thanks again.

  7. User Avatar
    Paul
    Permalink to comment#

    Excellent cast Chris. Thanks
    I’ve got two loops running here: http://silvanadesoissons.com/blog/
    One loop pulls the latest post from ‘blog’ category and puts it on the left, the other pulls the next 6 latest posts and puts them on the right. The trick was to get the second loop to ignore the post which was pulled in the first loop!

  8. User Avatar
    Bert de Vries
    Permalink to comment#

    Nice one, thanks.
    One thing i allways wondered about though is the constant opening and closing tags for PHP, like:

    The exact same thing will be executed with

    I think the last method gives a more readable code. Any comments?

    • User Avatar
      Bert de Vries
      Permalink to comment#

      Somehow my example lines didn’t show up. What i meant was:

      <?php do something; ?>
      <?php do something else; ?>

      versus

      <?php
      do something;
      do something else;
      ?>

    • User Avatar
      Chase Adams
      Permalink to comment#

      If “do something” returns something, the first way will add a new line return for do something else. The second way will return on the same line.

      Does that give any insight into what you were asking?

    • User Avatar
      Lucy Thompson
      Permalink to comment#

      Hi Bert,
      I suppose it is really personal preference. I had to go look at some of my projects to see what I usually did, and it seems I use a lot of php tags. Less is probably better, but I think I use them like a security blanket.

  9. User Avatar
    Lucy Thompson
    Permalink to comment#

    Well done Chris,
    Very entertaining, and it is always interesting to see how people approach the loop. As for the whole wp-query versus query_posts thing, I’m no stickler for either. If I am passing a lot of parameters to the loop I will use wp-query, but for quick changes query_posts does the job nicely.

  10. User Avatar
    Sathish
    Permalink to comment#

    Most Enthusiastic Screen cast Ever.. Got a great overview on wordpress loop..

  11. User Avatar
    Yosy
    Permalink to comment#

    Thank you Chris for this awesome screencast.
    There is an option for the old video player?With the current video player I can`t maximize the window to full screen (I can maximize only to full screen).

    • User Avatar
      Paul
      Permalink to comment#

      I’m with Yosy – it’s not as clear as before.

    • User Avatar
      Chris Vilchez
      Permalink to comment#

      Just as my two cents.. I actually prefer the new player. It allows me to view the video in a ‘full screen’ mode in one monitor while coding away in the other without reverting the video to normal size. When trying to go true full screen I just set my browser to full screen mode and achieve the same thing.

  12. User Avatar
    cristian
    Permalink to comment#

    dude i love you, you are the men

  13. User Avatar
    Anthony
    Permalink to comment#

    Awesome screencast Chris! I love how you always make this stuff so approachable and this particular video was very entertaining at the same time.

    I’m just getting into trying to make my own wp themes and this video has come right on cue for me…thanks a lot.

    I’ve yet to watch all of your screencasts (I subscribe through iTunes) but this one is my favorite so far.

    Please keep up the great work :)

  14. User Avatar
    Harald
    Permalink to comment#

    Sweet episode! Learned a lot. Thanks!

    I saw you where struggling a bit with the echoing of the html. I find it easier to not echo the html, but just write is plainly outside the <?php ?> stuff and use the <?= ?> quick echo/template stuff php has. Then I don’t need to think so much about the ” og ‘. Ex:

    <pre><code>
    ?
    </code></pre>

    Maybe you already knew this, but chose not do it. If not I hope it could be helpful for you or some others.

    Thanks a lot for the great screencast!:-)

    (hope I got the html escaping right)

    • User Avatar
      Harald
      Permalink to comment#

      Looks I messed up the actual code:P

      <pre><code>
      <h1>?</h1>
      </code></pre>

  15. User Avatar
    Harald
    Permalink to comment#

    Fail yet again. Last try:

    <pre><code>
    <h1><?= the_title() >?</h1>
    </code></pre>

    • User Avatar
      surfingtonio
      Permalink to comment#

      not all php setup supports short syntax for echo. this only works with the short_open_tag configuration setting enabled.

      also, you may use the_title() function to get AND echo the title. if you only need to get the value, add get_ before the function name ie. get_the_title().

  16. User Avatar
    Harald
    Permalink to comment#

    There should be a possibility to preview or delete the newly made comment so this doesn’t happen;)
    I’ll probably be banned for spamming soon, aren’t I?:P

    So one should not escape the pre or code tags but the html inside it? Is that how it works?

  17. User Avatar
    Hayley Williamson
    Permalink to comment#

    Thanks so much for this video! Wow, the loop seems much simpler now. I always struggled with pagination in a query_post, now I feel like I can understand it. Awesomeness!

  18. User Avatar
    Tholithemba
    Permalink to comment#

    ‘Chrisp’ screencast Chris :)

  19. User Avatar
    w1sh
    Permalink to comment#

    Nice screencast Chris.
    Why not code your loops like:

    <div class="post">
    <h2><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></h2>
    <?php the_content(); ?>
    </div>

    ?

    Seems so much cleaner/legible.

  20. User Avatar
    veerendra
    Permalink to comment#

    Hi chris,
    Thank you so much for doing screencast on this subject. as you say there is lots of content on net about this but the way you explained it got fit in may brain. Actually i was struggling with a problem u mentioned in last few moments. about wp reset query i was totally unaware of it. after watching i applied it in my sidebar and it made my day ! thanks a ton !

  21. User Avatar
    David
    Permalink to comment#

    Awesome screencast!

    and… have to say it

    StarCraft II — AWESOME! haha

  22. User Avatar
    Boni
    Permalink to comment#

    This is a great website…
    Awesome tutorials for free….
    Great, I hope find this long-long time ago..

  23. User Avatar
    Tilano
    Permalink to comment#

    Wow! Why can’t you be my teacher at university? ;)

  24. User Avatar
    arnold
    Permalink to comment#

    Great , Its nice to see again a screencast from Chris, I hope you do more

  25. User Avatar
    Darfuria
    Permalink to comment#

    I’ve never quite known the difference between showposts= and posts_per_page= – as posts_per_page always seems to be overwritten by the setting in WordPress’ settings.

    It’s interesting, Chris, that you write your HTML inside PHP echo, instead of just putting the PHP inside the HTML, like:

    <a href="">

  26. User Avatar
    Darfuria
    Permalink to comment#


    <h1><?php the_permalink(); ?>

  27. User Avatar
    wireframe
    Permalink to comment#

    Excellent article..you have knack of uncovering some less documented items within WP that are in need of explanation.

    Did heaps of searching for the page pagination issue a few weeks ago but being more a designer wasn’t able to pull this off. I reverted to using posts with a plugin which allows posts to use a page template instead..which eventually did the job..Wish I had of seen this earlier..thanks!

  28. User Avatar
    Nicolas
    Permalink to comment#

    This was a great screencast Chris! There are a lot of useful information on those Codex pages but sometimes just seeing it is easier than attempting to read through all of it. Thanks for a great familiarization session with the Loop!

  29. User Avatar
    byronyasgur
    Permalink to comment#

    Great video – you have the best web dev tutorials on the net ..
    +1 for the visual quality not being as good as usual though :-(

  30. User Avatar
    A
    Permalink to comment#

    swell.

  31. User Avatar
    azul
    Permalink to comment#

    awesome wp loop video..
    could you make video tutorial “create some wordpress plugin”

    • User Avatar
      arnold
      Permalink to comment#

      yeah, I agree with Azul!

    • User Avatar
      Mark
      Permalink to comment#

      Totally agree with azul too.
      Your Screencasts are fantastic, and I’d love to see your take on building a Plugin… or even a WP Theme Admin Panel.

  32. User Avatar
    Joln
    Permalink to comment#

    Great! Thought I knew it all up to reset query. That will save me a ton of work in the future!. :)

  33. User Avatar
    Rob
    Permalink to comment#

    What is with the new video player and fullscreen? Why doe the fullscreen button not open fullscreen but rather pop up another button that says Go Fullscreen?

    • User Avatar
      Rob
      Permalink to comment#

      Ooops does not doe, does the question make more sense now?

  34. User Avatar
    Desene online
    Permalink to comment#

    Very nice but you can make anathar another video ?

  35. User Avatar
    Amit
    Permalink to comment#

    great video tutorial. please please keep going past #100!

  36. User Avatar
    Jeff
    Permalink to comment#

    you’re videos are very informative, and hilarious. I totally wanted to tell you through the video that your page didn’t have any content yet. Then you said it, and I lol’d.

  37. User Avatar
    Jeff
    Permalink to comment#

    wow. Did I just say “you’re” instead of “your”? I’m an idiot.

  38. User Avatar
    Boba
    Permalink to comment#

    Just love watching you debug, so funny :)

    Anyway, nice screencast, i learned something new (that you don’t need the “WordPress loop” when retrieving a single post.

    Just 2 things:

    1) echo ‘<a href=”‘; the_permalink(); echo… Why so many echoes, use the functions that return the values instead of echoing them (get_permalink(), get_the_title()…) :)

    2) 25min, when you added “posts_per_page=20” to the $query_string, shouldn’t it be “&posts_per_age=20” since you’re just continuing on the original query_string varible which doesn’t end with “&”.

    Anyway i would like to see more screencasts on WordPress :) Maybe about the Walker class, i always found it confusing but i guess all i need is a good explanation, since there are no tuts on the net explaining it.

  39. User Avatar
    louis
    Permalink to comment#

    swell

  40. User Avatar
    Alexandru Nastase
    Permalink to comment#

    Chris….dude……THANK YOU…you released this video right when I got a huge project that I started in WP. and believe me this helped me through it…..the loop and the query_post rock man…..many many many much deserved thanks

  41. User Avatar
    martycud
    Permalink to comment#

    Chris, this was a great screen cast, thanks for sharing your great knowledge with others.

  42. User Avatar
    Dionisis
    Permalink to comment#

    Nice screencast Cris.

    i want to say this. query_posts() vs WP_Query()

    The difference is that query_posts() is the wordpress’s core loop. The default one. So it might be better not mess with that in order to avoid any upcoming bugs. We don’t want that…

    So i suggest use WP_Query() for your own NEW loops to sleep better at nights ;)

    Do you agree with that??

  43. User Avatar
    Fabian
    Permalink to comment#

    Dude!!, thank you!… thank you!… thank you!…

    It’s the most clarifying video I have seen about the word press loop in ages. It makes things so clear to me now after banging my head against the codex for a while.

    thank you again..

    keep with the videos, they’re simply awesome!.

    ( by the way, the guitar riff at the beginning of each video is you?
    nice touch!. ).

  44. User Avatar
    John
    Permalink to comment#

    thanks for this one chris. really helped me wrap my head around The Loop!

  45. User Avatar
    Sebastian Dalipi
    Permalink to comment#

    Great Video :)

    Thanks!!

  46. User Avatar
    bill
    Permalink to comment#

    I just installed version 3.2.1 and was trying to follow along. But when I click the Template Dropdown on the Add a new page, I don’t see the new file I created: wp-content\themes\portfolio-press\loopdemo.php. Your video shows quite a long list of items in that dropdown.

    This particular theme only has 4 templates. In that directory, I see the file loopdemo.php and two of the templates that populate the dropdown. The default and portfollio values in the dropdown do not have corresponding files in that directory.

    I have tried a couple of themes with the same results. Did something change with the way that dropdown is populated?

    Thanks in advance for any pointers you might provide.

  47. User Avatar
    bill
    Permalink to comment#

    Never mind. The comment does require the specific phrase: Template Name: whatever.

    I thought comments were not part of the “code” and didn’t bother to add them. In this case that is not true. I’ve never seen core functionality dependent on comments before except for a convention to generate other documentation like javadoc.

  48. User Avatar
    Alexander Nastase
    Permalink to comment#

    You have no idea how much this video helped me man. HUGE HUGE HUGE THANK YOU CHRIS !!!

  49. User Avatar
    Rhonda Clark
    Permalink to comment#

    Hi Chris,

    Excellent tutorial and I like your new site design! I’ve been watching your tutorials on WordPress and CSS for a while and I really enjoy them. Keep them coming.

  50. User Avatar
    Andrej
    Permalink to comment#

    Man, you made my day, you are fukcing amazing :) i love your work !
    greets from germany

  51. User Avatar
    Kamrul Hasan
    Permalink to comment#

    Pretty Cool! Pretty Cool!
    :)

  52. User Avatar
    Ricardo
    Permalink to comment#

    Very entertaining chris. This should it be in the official Codex (as a further refference in the bottom , at least in the ‘The Loop in Action’ page)

    • User Avatar
      charlie
      Permalink to comment#

      I would agree if he would improve his php conventions. Very good video, really helped me understand the wp-loop, but your php programming is painful to watch.

  53. User Avatar
    frESH
    Permalink to comment#

    THANK YOU SO F****KIN MUCH! MAN!! i finnaly got it i never understand the wordpress docs and stuff but this is so easy how you explained thanks!

  54. User Avatar
    sam east
    Permalink to comment#

    Great tutorial proper funny made me laugh, reminds me off my own coding forgetting simple stuff. ;)

  55. User Avatar
    kaidez
    Permalink to comment#

    Great, informative screencast!!

    Question: What’s the Dock app that divides the icons?

    Thanx in advance!!!!

  56. User Avatar
    Joe
    Permalink to comment#

    Well done Chris, amazing screencast explaining a very important part of WordPress. You just helped me out a lot!

  57. User Avatar
    Felipe
    Permalink to comment#

    hmm, how to paste code?

  58. User Avatar
    flyper
    Permalink to comment#

    hahahahaha!
    “Chris is dumb!” …I feel with you, we are very funny humans :D
    Thanks for you video, it´s very helpfull!
    Greetings from Munich

  59. User Avatar
    Fardeem
    Permalink to comment#

    hey chris, I am downloading this video and it’s a .txt file (?!). HELP!!

  60. User Avatar
    Pablo
    Permalink to comment#

    Very usefull, i might even start learning some wordpress, i liked it.

  61. User Avatar
    Peter
    Permalink to comment#

    Thank you so much for this. It helped me alot. But I had to include this to get the $paged working:

    $paged = get_query_var( ‘page’ ) ? get_query_var( ‘page’ ) : false;
    if ( $paged === false )
    {
    // This is not a paginated page (or it’s simply the first page of a paginated page/post)

    }
    else
    {
    // This is a paginated page.

    }

    Found here:
    http://codex.wordpress.org/Conditional_Tags#Testing_for_paginated_Pages

    But now the next_posts_link is finally working……

  62. User Avatar
    CiNiTriQs
    Permalink to comment#

    Still a relevant screencast ;) Nice refresher too. Keep it up!

  63. User Avatar
    martcol
    Permalink to comment#

    Loved it!

    Hey Chris, come and live with me! You’d get your own_room (‘outside’ , ‘lock’) and all you’d have to do is teach me to WordPress!

    Sounds_good(“to me”)

Submit a Comment

Posting Code

You may write comments in Markdown. This makes code easy to post, as you can write inline code like `<div>this</div>` or multiline blocks of code in triple backtick fences (```) with double new lines before and after.

Code of Conduct

Absolutely anyone is welcome to submit a comment here. But not all comments will be posted. Think of it like writing a letter to the editor. All submitted comments will be read, but not all published. Published comments will be on-topic, helpful, and further the discussion or debate.

Want to tell us something privately?

Feel free to use our contact form. That's a great place to let us know about typos or anything off-topic.

icon-closeicon-emailicon-linkicon-logo-staricon-menuicon-nav-guideicon-searchicon-staricon-tag