For many people who are creating their own blog or using a CMS like WordPress would like to customize how their blog articles are presented. This tutorial will go over how to insert elements within a PHP loop. A common use of this example is running a blog post loop and every nth iteration of the post, an Ad is placed to create revenue for the site. Let’s go over how to setup and put together the code.

Our Goal

Before we begin, let’s create a case where we can use this code. We want to have a blog that list all of the post articles that we create on for our website. We also want to insert an ad after every third blog article that is posted on the page. If you know a little about looping in PHP, you will know first off that we need to use the for loop to search through our list of and print each one. To prevent have to post 100,000 blog post (which could happen), we only want to list the 100 most recent articles. This will serve as our limit and will start from the first post and add a new one until it reaches 100. Let’s start writing our code.

PHP Code

The code below is a short and outputs a standard looping function. The main point of this exercise is to display our Ad post every third blog posted.

We start be creating a variable called post, which will in theory represent one blog post that we have created. PHP will count through all the blogs up to the 100th blog post and place the blog post. In this case we will just replace each blog with a phrase “Blog Post #_” to visually represent what PHP is doing. To help even further, we have placed an incrementing variable that will dynamically count blog for us (this is represented as $i++).

Now the most important part. We will disrupt the for loop by adding a conditional statement. This conditional statement will perform a simple math that states “if the blog posted is divisible by 3, echo our ad placement”. This simple operator is the key to placing our ad in every other blog post.

Wrapping It Up

PHP is a great tool for dynamically adding content into your website. It is most powerful when used with a database to get and post data instantly. Use this example withing your WordPress blog and other PHP websites to add more functionality into your site.