【问题标题】:Wrapping every 3 elements in a loop leaves an empty wrapper将每 3 个元素包装在一个循环中会留下一个空包装器
【发布时间】:2015-08-03 12:35:39
【问题描述】:

我将循环中的每 3 个元素包装在一个包装器 div 中,如下所示:

$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>';

这创建了一个很好的包装 html 减去一件让我烦恼的小事:

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

如果我正好有 6 个帖子(或 3 的任何倍数,并且模数正在这样做),我会得到一个额外的空包装器。这真的不需要。

那么我应该在查询中包含什么条件以确保不会得到空包装器?

【问题讨论】:

    标签: php wordpress


    【解决方案1】:

    在里面添加包装器:

    $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>';
    

    【讨论】:

    • 这行得通!谢谢 :) 我会在 2 分钟内接受它。我记得我本可以使用.wrapper:empty{display:none;},但这要好得多,因为我不会留下没有用途的空 div :)
    猜你喜欢
    • 2020-06-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-24
    • 2014-09-07
    • 2011-03-22
    • 2018-02-11
    • 1970-01-01
    相关资源
    最近更新 更多