简体   繁体   English

将DIV中的每1-4个Wordpress帖子换行

[英]Wrap Every 1 - 4 Wordpress Posts within a DIV

I am trying to wrap every row of wordpress posts with a div with a class of row. 我正在尝试用每行一格的div包装wordpress帖子的每一行。

Have been trying to follow the answers from another question linked below But seem to be having trouble as my loop is a little different. 一直在尝试遵循下面链接的另一个问题的答案,但是似乎遇到了麻烦,因为我的循环有点不同。 Also I would like any rows with 1 or more posts to be wrapped in a row also... 我也想将具有1个或多个帖子的任何行也包装成一行...

I need to wrap every 4 wordpress posts in a div 我需要在div中包装每4个wordpress帖子

<?php

    query_posts('cat=2'); 
    $i = 0;
    $wrap_div = "<div class='row'>";

    if ( have_posts() ) : 
        $total_posts = $wp_query->post_count;
        echo $wrap_div;

        while ( have_posts() ) : the_post();
?>

<div class="four columns gameListing" id="" data-count="">       
    <img class="gameLogo" src="" > 
    <div class="gameInfo">
        <h2 class="gameTitle"></h2>
        <div class="gameRating"></div>
    </div>
    <a class="gameCta" rel="" data-post-id="" >
         <span class="title" data-id="">Click to Play</span
    </a>
</div>

<?php 

        if ( $i % 4 == 0 && $i != 0 && ( $i + 1 ) != $total_posts ) {
            echo '</div>' . $wrap_div;
        }

        $i ++;

?>
<?php endwhile; endif; ?>
<?php wp_reset_query(); ?>

Can be a situation when post_count not multiple of 4 可能是post_count不是4的倍数的情况

<?php
$my_query = new WP_Query( array( 'category__in' => 2 ) );
$wrap_avery = 4;
$index = 0;

$need_end_div = $my_query->post_count % $wrap_avery > 0;

while( $my_query->have_posts() ) {
    $my_query->the_post();
    $index++;

    // open row if index = 1, 5, 9...
    if( ($index - 1) % $wrap_avery == 0 ) {
        echo "<div class='row'>";
    }

    //todo: block HTML here

    // close row if index = 4, 8, 12...
    if( $index % $wrap_avery == 0 ) {
        echo '</div>';
    }

}

// close div if posts count not multiple of 4
if($need_end_div) {
    echo '</div>';
}

BTW you should no use query_posts 顺便说一句你不应该使用query_posts

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM