Insert Elements Within a Php Loop

Estimated read time 3 min read

Introduction

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 set up 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 lists all of the post articles that we create 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 and print each one. To prevent having to post 100,000 blog posts (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 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 by creating a variable called a 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 the 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 loop by adding a conditional statement. This conditional statement will perform 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 to your website. It is most powerful when used with a database to get and post data instantly. Use this example within your WordPress blog and other PHP websites to add more functionality to your site.

You May Also Like

More From Author