Understanding WordPress Loop
Once you installed your WP blog, it’s just a matter of time before you hear this word: The Loop.
Did you install a plugin? It probably has some advanced functions to be inserted in The Loop. Do you want to insert a banner or a Google ad after the first post (or inside it)? You have to modify The Loop.
Do you want to fully display only the first five posts and show only the title for the remaining ones?
Agan, you have to modify The Loop.
It’s time to learn what is The Loop
From WP docs: The Loop is used by WordPress to display each of your posts. Using The Loop, WordPress processes each of the posts to be displayed on the current page and formats them according to how they match specified criteria within The Loop tags. Any HTML or PHP code placed in the Loop will be repeated on each post.
If you open your index.php file in your WP theme you will find this line of code:
|
1 |
<?php if (have_posts()) : while (have_posts()) : the_post(); ?> |
and, later, this one:
|
1 |
<?php endwhile; endif; ?> |
This is the so-called Loop. All code and HTML between these two lines will be executed at every post.
This way, every post will look the same, since it’s generated by the same loop.
What if you want to embed a Google between the first and the second post?
If you browse the web, you will find a lot of examples with multiple loops. I discourage using multiple loops because the more you write, the easier you can make mistakes.
So my suggestion is to replace
|
1 |
<?php if (have_posts()) : while (have_posts()) : the_post(); ?> |
with
|
1 2 3 |
<?php $postcount = 0; ?> <?php if (have_posts()) : while (have_posts()) : the_post(); ?> <?php $postcount++; ?> |
To store in the $postcount variable the number of post displayed.
Then, just before
|
1 |
<?php endwhile; endif; ?> |
This code:
|
1 2 3 |
<?php if($postcount==1){ ?> your google ad code here <? } ?> |
And you’ll have this result:

This is only one example of various things you can do once you master The Loop, hope you will find it useful.
You will be pleasantly surprised by WordPress Themes provided by Template Monster. All of them are of professional design and high quality.














This post has 7 comments
Mr Sun
Cool, this might come in handy when I redesign my blog.
Will
This looks pretty straight forward. My have to have a go at getting that working!
Kesh
who cares about word press.
FayeC Web Studio :: Web Design and Development » Best Wordpress Tutorial sites
[...] Understanding the loop [...]
Annie
How would you show more than 1 result on the search results?
How would you show just one full post and the rest on the same blog page, headlines?
Thanks.
WordPress Loop | Theme Heven
[...] Read More … [...]
Marc Falk
Thanks so far..
How will the code look like if I want to add a specific class to every second post?
Don’t wanna write my suggestions, this form doesn’t support it?