Insert Content In WordPress Loop After First Post
August 21, 2020 • PHP, WordPress • Published By Josh • 3 minute read
Have you ever wanted to include something other than a post in the WordPress loop? Maybe you want to display an ad after the first post. Let’s learn how to do that!
Table of Contents
Create Your Content
Your content can be anything you want. It could be made up of text, an image, Google Adsense code, whatever you’d like to display!
<p>This will appear after the first post in the loop.</p>
A WordPress theme may have several files where the loop is used. You want your content to appear in each of these files. You could add the content directly into each of these files, but then making an edit later would be tedious. You’d have to edit the content in every file.
Instead, create a new file. Let’s call it ad.php and place it inside your theme folder. In a moment, you’ll learn how to include it in each file where you want your content to appear. Making edits in the future will be simple because you only have to edit one file!
Find The Loop
You need to find the WordPress loop code in each of the theme files you’d like your content to appear. Every theme is different, but you should be able to find something similar to the examples below:
<?php if ( have_posts() ) : while ( have_posts() ) : the_post(); ?>
<?php endwhile; else : ?>
<?php endif; ?>
<?php
if ( have_posts() ) {
while ( have_posts() ) {
the_post();
}
}
?>
Here are some common theme files where you’ll find the WordPress loop:
- author.php
- category.php
- index.php
- search.php
- tag.php
Update The Loop
Create a variable called $count and set it’s value to 0. This will keep track of what post we’re on in the loop.
$count = 0;
Create an if statement checking if the count is set to 1. If it is, let’s include the content we want to display. WordPress provides a helpful function called get_template_part. Pass in the name of the file, which was called ad in our example.
By the way, if you wanted to display your content after the second post for example, just change the value from 1 to 2.
if ($count === 1) {
get_template_part( 'ad' );
}
Finally, increment the value of count by 1 as the while loop continues to display posts.
$count++;
Below is an example of what it could look like. After updating and saving each theme file, your content should display after the first post!
<?php
$count = 0;
if ( have_posts() ) {
while ( have_posts() ) {
the_post();
if ($count === 1) {
get_template_part( 'ad' );
}
count++;
}
}
?>