WordPress.org

Support

Support » Plugins and Hacks » Hacks » Content in loop

Content in loop

  • pelw

    @pierrewiberg

    Hi,

    I’d like to add banners within the loop of blog posts.

    The problem is that I cant quite understand how to add it after every third post. Any ideas? I would be real glad NOT to use any lame plugins.

    Thanks!!

Viewing 4 replies - 1 through 4 (of 4 total)
  • Just before the loop, set a PHP variable (eg, $my_count) and set it equal to 1: $my_count=1;. Then, at the end of the loop, just before endwhile;, add $mycount+=1; to increase the variable by 1.

    Finally, wherever you want your banners to appear, put:

    if(($my_count%3)==0):
    Your banner code
    endif;

    That $my_count%3 says “If the number $my_count is evenly divisible by 3 (ie, no remainder), put my banner code here.”

    pelw

    @pierrewiberg

    Thanks for a quick reply!

    Can you give me a little more details on your code, I’m pretty new on PHP :-/
    But I’m pretty familiar with the loop so just the basics of your code would be highly appreciated, and I can play around with it 🙂

    Thanks!

    All it’s doing is creating a variable called $my_count before the loop, and then setting that variable equal to the number 1. Then, once the loop starts, the variable increases by 1 after each post is displayed (the $my_count+=1 line).

    So…if you’re using the default setup, the WordPress loop will pull ten posts and your $my_count variable would look like this:

    $my_count=1
    BEGIN WORDPRESS LOOP
    POST #1
    $my_count=2
    POST #2
    $my_count=3
    POST #3
    $my_count=4
    POST #4
    $my_count=5
    POST #6
    $my_count=7
    POST #7
    $my_count=8
    POST #8
    $my_count=9
    POST #9
    $my_count=10
    POST #10
    $my_count=11
    END WORDPRESS LOOP

    The “if” function says that your code inside the “if” function should appear if $my_count=3,6,9,12 — basically, any time $my_count is evenly divisible by 3. In the above example, your code would appear after POST #3, POST #6, and POST #9.

    So a sample code would look like this:

    <?php
    $my_count=1;
    if(have_posts()) : while(have_posts()) : the_post();
    ?>
    <div class="entry">
    <h1><?php the_title();?></h1>
    <?php the_content();?>
    </div>
    <?php if(($my_count%3)==0):?>
    <div class="banner">
    Content of banner (Google AdSense code or whatever)
    </div>
    <?php endif;?>
    <?php
    $my_count+=1;
    endwhile;
    endif;
    ?>

    pelw

    @pierrewiberg

    You are fantastic human being!
    Thanks!

Viewing 4 replies - 1 through 4 (of 4 total)
  • The topic ‘Content in loop’ is closed to new replies.
Skip to toolbar