2013-12-18 50 views
0

我需要为我的wordpress循环中的每个第二项添加一个div。目前我正在使用下面的代码(哪些工作),但我认为有一个更好或更干净的方式来做到这一点。我将如何更改下面的代码?任何关于去哪里看的建议都会很棒,因为这对我来说似乎很混乱。提前致谢。每隔一个循环显示div

<?php while (have_posts()) : the_post(); ?> 
<?php    
    $col_select = $data['example_select']; 
    if ($col_select == '2 Col') { 
    get_template_part('/templates/article/content', 'standard'); ?> 
<?php if($wp_query->current_post == '1') { ?> 
    </div><div class="row"> 
<?php } if($wp_query->current_post == '3') { ?> 
    </div><div class="row"> 
<?php } if($wp_query->current_post == '5') { ?> 
    </div><div class="row"> 
<?php } if($wp_query->current_post == '7') { ?> 
    </div><div class="row"> 
<?php } if($wp_query->current_post == '9') { ?> 
    </div><div class="row"> 
<?php } ?> 

回答

4

if($wp_query->current_post % 2 != 0)应该这样做。

参见:http://php.net/manual/en/language.operators.arithmetic.php

编辑:当然,如果你删除帖子会破,但是这是基于关闭您当前的代码。该位在哪里的循环在哪里?你可以用柜台来做到这一点。

+1

哈哈我只是写你写的! –

+1

Brillant。这么简单....我会接受,当它让我杰西卡 – user2966586

0
<?php while (have_posts()) : the_post(); ?> 
    <?php    
     $col_select = $data['example_select']; 
    if ($col_select == '2 Col') 
    { 
     get_template_part('/templates/article/content', 'standard'); ?> 
     <?php if(($wp_query->current_post % 2) == 1) { ?> 
      </div><div class="row"> 
     <?php } ?> 

current_post % 2如果它是奇数,将返回1。

+0

它会返回0而不是1 – ollieread

+1

@ollieread不,它会返回0为偶数。他是正确的,它将是1的奇数。 – Jessica

+0

不,它不会。奇数除以2的余数为1.如果它是偶数,它将返回0,就像下面的杰西卡的替代答案一样。 – egl

0

您应该尽可能避免打开和关闭<?php ... ?>标签。这妨碍了能够读取你的代码。其次,如果你想结束你的div每隔一行,然后用一个模测试,像这样:

<?php 
    while (have_posts()) : the_post(); 
    $col_select = $data['example_select']; 
    if ($col_select == '2 Col') { 
     get_template_part('/templates/article/content', 'standard'); 
     if ($wp_query->current_post % 2 == 1) { 
     echo "</div><div class=\"row\">"; 
     } 
    } 
    endwhile; 
?> 

然而,真正的干净的方式做,这是推迟显示器你呈现这里的模板。不知道你用什么get_template_part,这一点很难说你会如何在适当的数据传递(这是您的查询的“接下来的两个”部分。

1

即使

if($wp_query->current_post % 2) 

那么做了2%,因为1 =真,0 =假

+0

虽然如果我们决定向列中扔三样东西,这会中断 –

0

模量的做法是正确的,但由于不破,如果$wp_query->current_post选项没有返回增量数字。

办最好的事,会创造另一个变量来存储您循环的次数,如下所示。上述

<?php 
$x = 1; 
while (have_posts()) : the_post(); 
    $col_select = $data['example_select']; 
    if ($col_select == '2 Col') 
    { 
     get_template_part('/templates/article/content', 'standard'); 
     if(($x % 2) == 1) { ?> 
      </div><div class="row"> 
     <?php } 
     $x++; 
    } 
endwhile; 

意味着为2 Col比赛每一秒的结果你就必须</div><div class="row">输出。