Wrapping every 3 elements in a loop leaves an empty wrapper

前端 未结 1 653
执念已碎
执念已碎 2021-01-25 02:15

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( $quer         


        
相关标签:
1条回答
  • 2021-01-25 02:47

    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>';
    
    0 讨论(0)
提交回复
热议问题