PHP如果foreach显示广告每5个循环


<?php 
$args = array('posts_per_page'=> 100,'orderby' => 'rand' );
$rand_posts = get_posts( $args );
foreach( $rand_posts as $post ) :
    if($i == 5){
        $i ==1; 
        xxxxx
    }else{
        $i++;
    }
    ?>       
    <div class="thumbBlock" id="post-<?php the_ID(); ?>">
        123
    </div>
<?php endforeach; ?>

xxx是我的广告。是重复的

但不能工作

您没有正确地重置计数器。将$i == 1修改为$i = 1。同时确保$i正确初始化。

<?php $args = array('posts_per_page'=> 100,'orderby' => 'rand' );
$rand_posts = get_posts( $args );
foreach( $rand_posts as $post ) :  
    if($i == 5){
        $i = 1;  // <--- reset, don't test for $i == 1 
        xxxxx
    }else{i++;}?>       
<div class="thumbBlock" id="post-<?php the_ID(); ?>">
123
</div>
<?php endforeach; ?>

检查$i是否能被5整除,如果可以,您可以显示您的广告

<?php 
$args = array('posts_per_page'=> 100,'orderby' => 'rand' );
$rand_posts = get_posts( $args );
$i = 0;
foreach( $rand_posts as $post ) :
    if ($i % 5 == 0) {
        # code to show your ads
    }else{
        #show something else
    }
    $i++;
    ?>       
    <div class="thumbBlock" id="post-<?php the_ID(); ?>">
        123
    </div>
<?php endforeach; ?>

最新更新