You’ve probably been on a site where half way through the list of posts (the WordPress loop) there are a couple of advertisements. It can be quite confusing as to how this is done at first so let me show you.
The easiest way to do this is by using a counter. A counter is simply a variable that goes up by one every time the WordPress loop is run. Remember The Loop is just a PHP while statement. You’ve likely heard of a foreach statement. Well a while statement acts in some of the same way. Many developers debate over which to use in certain situations but we won’t go over that today.
Let’s start off with a basic WordPress loop. The following code is all you’ll need to start displaying the latest posts. You can also manipulate the “loop” to accept arguments, but that’s a little beyond the scope of this tutorial.
if(have_posts()) : while(have_posts()) : the_post();
the_content();
endwhile; endif;
Next we need a variable which will act as a counter. What happens is every time WordPress does a loop of our while
statement and displays another post, the variable of $counter++;
gets incremented by 1.
if(have_posts()) : while(have_posts()) : the_post();
$counter++;
the_content();
endwhile; endif;
Tip: The counter will start at 1, but you can set it start at 0 by initialising the $counter
variable before the loop, like so…
$counter = 0;
if(have_posts()) : while(have_posts()) : the_post();
$counter++;
the_content();
endwhile; endif;
To display the ads we simply stop the while loop at a set number, display the ads, then carry on with the loop.
if(have_posts()) : while(have_posts()) : the_post();
$counter++;
if($counter == 3) {
// Display Ads
}
the_content();
endwhile; endif;
Join the newsletter to get the best articles, tutorials and exclusive freebies every two weeks.
marquis
February 27, 2016 at 4:19 am
Works Well How Would i show content after the last post