dphphvs496524 2014-09-24 17:57
浏览 19

每2个帖子插入div而没有空div

I'm pulling my hair out with this! The following code correctly inserts a div with row as the class every 2 posts. HOwever, when there's an even number of posts, it displays an extra empty div below. Can anyone help please?

Thanks!

    <div class="row">
    <?php
    $connected = new WP_Query( array(
    'connected_type' => '2-col-module_to_pages',
    'connected_items' => get_queried_object(),
    'nopaging' => true,
     ) );


 if ($connected->have_posts() ) : while ($connected->have_posts()) : $connected->the_post(); ?>
<div class="tile">
  <div class="wrapper">
    <div class="content">
        <h2><?php the_title();?></h2>
    </div>
 </div>
 </div>
   <?php $counter++;
  if ($counter % 2 == 0 ) {
        echo '</div><div class="row">';
        }
        endwhile; wp_reset_postdata(); endif; ?>
 </div>
  • 写回答

1条回答 默认 最新

  • dongyiba8082 2014-09-24 18:13
    关注

    By the time you fetched the last post you won't have any more; so you could ask again right before echoing the empty div:

    $counter++;
    if ($counter % 2 == 0 ) 
    {
        if ( more_posts() )
        {
            echo '<div class="row"></div>'; // It was </div><div class="row"> which always left an open div
        }
    }
    

    You can add the more_posts() function to WordPress' functions.php file.

    function more_posts() 
    {
        global $wp_query;
        return $wp_query->current_post + 1 < $wp_query->post_count;
    }
    

    Note: This solution was takeng from WordPress' Codex at: http://codex.wordpress.org/Function_Reference/have_posts

    评论

报告相同问题?

悬赏问题

  • ¥15 微信小程序协议怎么写
  • ¥15 c语言怎么用printf(“\b \b”)与getch()实现黑框里写入与删除?
  • ¥20 怎么用dlib库的算法识别小麦病虫害
  • ¥15 华为ensp模拟器中S5700交换机在配置过程中老是反复重启
  • ¥15 java写代码遇到问题,求帮助
  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看