如何在4个帖子后自动插入新的标记元素?

时间:2018-01-31 作者:Sebestyén Nagy

如何在4列ms-4之后自动插入新行查询?

<section class="container" id="szolgaltatasok">
       <div class="row" id="szolgaltatasok">
        <?php
                $custom_query = new WP_Query(\'cat=-1\'); // Kizárt kategória
                while($custom_query->have_posts()) : $custom_query->the_post(); ?>
                <div class="col-md-4 portfolio-item" <?php post_class(); ?> id="post-<?php the_ID(); ?>">
                            <div class="szolgaltas-bg">
                                <?php if ( has_post_thumbnail() ) {
                                    the_post_thumbnail( \'la-dolce-vallata-blog\' );} ?> 
                                <div class="szolgaltas-padding">
                                    <h3 id="h3-padding"><a id="szolgaltatasok" href="<?php the_permalink(); ?>"><?php the_title(); ?></a></h3>  
                                    <?php
                                    echo "<p>";
                                    $content = get_the_content();
                                    echo substr(strip_tags($content), 0, 123);
                                    echo "...</p>";
                                    ?>
                                </div>
                            </div>    
                        </div>        
                <?php endwhile; ?>
                <?php wp_reset_postdata(); // reset the query
        ?>    
       </div>    
</section>

1 个回复
SO网友:Nicolai Grossherr

这可以通过访问WP_Queryproperties, 在循环中可用,如$current_post (当前职位索引),$post_count (显示的帖子数量),$found_posts (与查询匹配的帖子总数)。

通过使用$current_post, $post_count 和PHPmodulo, 如下图所示:

<?php if ( $custom_query->have_posts() ) : while ( $custom_query->have_posts() ) : $custom_query->the_post();  
  $i = $custom_query->current_post;  
  $c = $custom_query->post_count;
  if ( $i % 4 == 0 ) {
    // happening for $i being 0, 4, 8 and so on
    echo \'<div class="row">\';
  } ?>

// single post markup

<?php if ( $i % 4 == 3 || $i == ( $c - 1 ) ) {
  // happening for $i being 3, 7, 11 and so on
  // OR condition in case the last one is not a multiple of 4
  echo \'</div>\';
}
endwhile; endif; ?>

结束