Detect each 4 using modulus php

给你一囗甜甜゛ 提交于 2019-12-02 05:59:51

问题


I am trying to detect each 4th post to insert extra code in my layout in wordpress using modulus method but I just cant get it.

Here is a short example of mine:

<?php if (have_posts()) : ?>
<?php $count=0;?>   
<?php while (have_posts()) : the_post(); ?>

<div class="column">

<!--content-->

</div> 

    <?php
            if ($count % 4 == 0){     
                echo '<div class="clear"></div>';
            }      
            $count++;       
            ?>

<?php endwhile; ?>
<?php endif; ?>

all that is inside the while loop. What am I doing wrong? Thank you.


回答1:


You need to start your counter at 1, as you are increasing it at the end of the loop:

<?php $count=1;?>

Either that, or you increase it at the start of the loop / before the check:

<?php
        $count++; 
        if ($count % 4 == 0){     
            echo '<div class="clear"></div>';
        }            
?>



回答2:


When it comes to things like this, I always increment one on the if statement before calling modulo like so:

if(($count+1)%4 == 0)

This way it's easy for me to make a mental note that the statement naturally reads "if the current count is the 4th one then do:"



来源:https://stackoverflow.com/questions/9780012/detect-each-4-using-modulus-php

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!