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:

[php]
$count = 0;
if ( have_posts() ) : while ( have_posts() ) : the_post();
//before
if ($count % 2 == 0){
//do something like displaying an ad
}
$count++;
//after
endwhile;
endif;
[/php]

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

26 thoughts on “How to insert ads every two posts in WordPress”

  1. cool, thanks Empress 🙂 You know, if you want to insert an ad only after the first post instead of checking ($count % 2 == 0) you could check ($count == 0) and you’re cool.

  2. You could also set it up to be more specific as to where you want the ads to appear using your same count code at the top then using this code within the loop…

    if($count == 1 || $count == 3 || $count == 8){
    //item to be shown here
    }
    $count++;

    Where 3 and 7 specify the post position to display the content after – you can add more OR statements to put it in more positions…

    1. Correct, Adam. Posibilities are endless. We could also use a switch instruction to display specific chunks of code.

  3. Hi Elio,

    Would it be possible to update the ads-wordpress-loop post with an example loop containing your code?

    That would really help a lot of people because it would be much clearer how to set this up.

    Thanks!

  4. hey friend i am using this code but it only display 1 post after 2 post

    i want to show ad after every 2nd post
    [?php if ($count==2) { ?]
    [div class=”clear postborder”> [/div]
    [?php } ?]
    [?php $count = $count + 0; ?]

  5. Opps code didnt post… sorry

    [?php $myCats = array(63,86); // Excluded Categories
    query_posts($query_string); // Requested variables
    if(have_posts()) :while (have_posts()) : the_post();
    if(in_category($myCats)) continue;
    ?]

    1. You can do it on index.php for example, or any archive template in general, like category.php, archive.php and so on. That is, of course, assuming your theme complies with WordPress code standards.

Leave a Reply to Very Useful 65 WordPress Hacks | Design your way Cancel reply