Site icon StartFunction

How to insert ads every two posts in WordPress

It is said that ads inserted on the content perform better than those on sidebars or footers. Let’s see a quick and easy technique for WordPress to display ads every two posts.

In order to do this, we need to initialize a variable before entering The Loop and, during the iteration through the posts, test if its value is even. We will use the Modulus operator %, which in an operation

a % b

is the remainder of a when divided by b. For example:

4 % 2 = 0

3 % 2 = 1

So if the remainder of our variable divided by 2 is zero, we will be at an even post and hence we can insert the ad or anything else. The code is as follows:

$count = 0;
if ( have_posts() ) : while ( have_posts() ) : the_post();
if ($count % 2 == 0){
//do something like displaying an ad

Of course, if you want to insert something every three posts change the number to three. That’s it, have fun inserting!

Exit mobile version