分解循环的结果

时间:2013-12-28 作者:NW Tech

在我的查询中,我收集了6篇帖子,并将它们显示在无序列表中。下面是我使用的代码:

$args = array(
    \'post_parent\' => $page_id->ID,
    \'showposts\' => 6,
    \'post_type\' => \'page\',
    \'orderby\' => \'menu_order\',
    \'order\' => \'ASC\'
);
$subpages = new WP_query($args);

if ($subpages->have_posts()) :
    while ($subpages->have_posts()) : $subpages->the_post();
        $output .= \'<li><a href="\'.get_permalink().\'" class="\'.$page_id->post_name.\'-link"><div class="\'.$page_id->post_name.\'-info"><div class="\'.$page_id->post_name.\'-img">\'.get_the_post_thumbnail($page->ID,\'icons\').\'</div><h2>\'.get_the_title().\'</h2>
                    <p class="\'.$page_id->post_name.\'-excerpt">\'.get_the_excerpt().\'</p>
                    </div></a></li>\';
    endwhile;
endif;
我想分解并显示三篇文章,然后插入另一个div,然后继续循环。html结果类似于:

<ul>
    <li>Post1</li>
    <li>Post2</li>
    <li>Post3</li>
</ul>
<div class="notice">Some text goes here</div>
<ul>
    <li>Post4</li>
    <li>Post5</li>
    <li>Post6</li>
</ul>
EDIT 我是根据@Rarst的建议来做这件事的。以下是我的更新代码:

    $args = array(
        \'post_parent\' => $page_id->ID,
        \'showposts\' => 6,
        \'post_type\' => \'page\',
        \'orderby\' => \'menu_order\',
        \'order\' => \'ASC\'
    );
    $subpages = new WP_query($args);

    if ($subpages->have_posts()) :
        while ($subpages->have_posts()) : $subpages->the_post();
            $output .= \'<li><a href="\'.get_permalink().\'" class="\'.$page_id->post_name.\'-link"><div class="\'.$page_id->post_name.\'-info"><div class="\'.$page_id->post_name.\'-img">\'.get_the_post_thumbnail($page->ID,\'icons\').\'</div><h2>\'.get_the_title().\'</h2>
                        <p class="\'.$page_id->post_name.\'-excerpt">\'.get_the_excerpt().\'</p>
                        </div></a></li>\';
            if (2 == $subpages->current_post):
                    $output .= \'</ul>\';
                    $output .= \'test\';
                    $output .= \'<ul class="\'.$page_id->post_name.\'">\';
            endif;
        endwhile;
    endif;

1 个回复
最合适的回答,由SO网友:Rarst 整理而成

的实例WP_Query 跟踪当前帖子的数量current_post 属性,从零开始。

所以在你的循环中,你可以检查if ( 2 == $subpages->current_post ) 并输出附加内容。

结束

相关推荐

Get 1 more post in loop

例如,在简单循环中:$loop = new wp_query(array(\'posts_per_page\' => 3)); while($loop->have_posts()) : $loop->the_post(); if(get_post_meta($post->ID, \'skip_me\', true) == true){ // do something to ask for one more post, &#x