Wrapping every 3 elements in a loop leaves an empt

2020-04-29 00:20发布

I am wrapping every 3 elements in my loop in a wrapper div like this:

$query = array(
    'post_type' => 'post',
);

$i = 1;

$posts = new WP_Query( $query );
$out = '<div class="wrapper">';
if ($posts->have_posts()){
    while ($posts->have_posts()){
        $posts->the_post();

        $out.= '<div class="content">
            //content here
        </div>';

        if($i % 3 == 0) {
            $out .= '</div><div class="wrapper">';
        }

        $i++;

    }
}
$out .= '</div>';
wp_reset_postdata();


return '<section>'.$out.'</section>';

Which creates a good wrapping html minus one little thing that's bothering me:

<section>
    <div class="wrapper">
        <div class="content"></div>
    </div>
    <div class="wrapper">
        <div class="content"></div>
    </div>
    <div class="wrapper"></div>
</section>

If I have exactly 6 posts (or any multiple of 3, and modulo is doing this like it should) I'll get an extra empty wrapper. Which is really not needed.

So what conditional should I include in my query to ensure that I don't get empty wrappers?

标签: php wordpress
1条回答
forever°为你锁心
2楼-- · 2020-04-29 00:55

Add the wrapper inside:

$query = array(
    'post_type' => 'post',
);

$i = 1;

$posts = new WP_Query( $query );
$out = '';
$endingNeeded = false;
if ($posts->have_posts()){
    while ($posts->have_posts()){

        if($i % 3 == 1) {
            $out .= '<div class="wrapper">';
            $endingNeeded = true;
        }

        $posts->the_post();

        $out.= '<div class="content">
            //content here
        </div>';

        if($i % 3 == 0) {
            $out .= '</div>';
            $endingNeeded = false;
        }

        $i++;
    }
}

if($endingNeeded) {
    $out .= '</div>';
}

wp_reset_postdata();


return '<section>'.$out.'</section>';
查看更多
登录 后发表回答