The WordPress loop is what controls the posts on the page. And like it’s name – it ‘loops’ the content and anything placed within the loop will be repeated until the loop ends.
Sometimes we’ll need to add content to a page that shouldn’t be repeated with every single post displayed (i.e. ads) and in order to do that, we need to know where the WordPress loop begins and where it ends.
For this example, I’ll be using the default WordPress template (Kubrick) index.php file located in the ‘[WP-INSTALL]/wp-content/themes/default/‘ folder.
You’ll see the loop starts around line 7* with:
<?php while (have_posts()) : the_post(); ?>
The give-away? The word ‘while’ – that is the element that tells you the WordPress loop is starting. You can add your information or content above this line and it will not be repeated with each post, instead, it will show before your posts start.
The loop ends around line 20 with:
<?php endwhile; ?>
The give-away? The word ‘endwhile’ – that is the element that tells you the WordPress loop is ending. You can add your information under this line and it will not be repeated with each post, instead, it will show after all of your posts.
Technically the loop starts at line 5 with:
<?php if (have_posts()) : ?>
However, this is simply a statement saying “if posts are available, go ahead and start ‘looping’ them” – anything you add before this will not be included in the loop, however, if you add something below it and no posts exist, whatever you added won’t be displayed either.
And technically the loop ends at line 33 with:
<?php endif; ?>
This is saying, end the ‘if posts are available…” statement from above and anything added above this line will only be displayed if there are posts, however, anything below it will be displayed regardless.