将代码转换为函数

时间:2012-02-23 15:00:52

标签: function arrays

如何转换此代码:

    <?php
                    if(have_posts()):

                    $end = array(3,6,9,12,15,18,21,24,27,30,33,36,39,42,45);
                    $a = 0;
                    while (have_posts()) : the_post();
                    $a++;
                    global $post;
                ?>
                <li class="item_list<?php if (in_array($a, $end)) { echo " right"; } ?>">

进入一个像这样开始的函数

$display = 

提前非常感谢你!)

2 个答案:

答案 0 :(得分:2)

您无法将代码转换为函数,因为它是if / while / endwhile / endif结构的一部分;

要达到你想要的效果,可以尝试使用模数运算符:

<?php           
  if(have_posts()):             
     $a = 0;               
     while (have_posts()) : the_post(); 
        $a++;          
        global $post; ?> 

        <li class="item_list<?php if ($a%3 == 0) { echo " right"; } ?>"> 

答案 1 :(得分:0)

以正确的方式使用WordPress对象我会指向使用“$ wp_query-&gt; current_post”,而不是进行这种计数。

以下示例:

if( have_posts() ) {
    // Before the loop

    while( have_posts() ){
        the_post();
        // The loop
        echo "<li class='" . ( $wp_query->current_post % 3 == 0 ? "right" : "" ) . "'></li>";

    }
    // After the loop

} else {
    // If don't have any posts
}