【问题标题】:Wordpress Loop: how to wrap each 3 posts into a div?Wordpress Loop:如何将每 3 个帖子包装成一个 div?
【发布时间】:2011-12-19 22:05:08
【问题描述】:

我正在尝试这个:

<?php query_posts('cat=6'); ?>
<?php if (have_posts()) : ?>

    <?php while (have_posts()) : the_post(); ?>
        <div>
            <?php $counter=3; ?>
            <?php the_post_thumbnail(); ?>
            <?php $counter++; ?>
        </div>

    <?php endwhile; ?>
<?php endif; ?>

但它不起作用! :/ 谢谢!

【问题讨论】:

  • 我认为这是最简单的方法:stackoverflow.com/questions/28247770/loop-through-wordpress-posts-and-wrap-each-x-post-in-a- div

标签: php wordpress loops foreach


【解决方案1】:

感谢大家的支持! :) 我尝试了两种解决方案,但没有奏效, 我最终得到了这个并且完美地工作!

<?php query_posts('cat=6'); ?>

<?php $variable=0;?>

<div>
<?php while ( have_posts() ) : the_post(); ?>
<?php if(($variable+1)<4){ ?>
<a href="<?php echo get_post_meta($post->ID, 'colaborador-link', true); ?>" target="blank">
<?php the_post_thumbnail(); ?>
</a>
<?php $variable+=1; ?>
<?php }else{ ?>
<?php $variable=1; ?>
</div>

<div>
<a href="<?php echo get_post_meta($post->ID, 'colaborador-link', true); ?>" target="blank">
<?php the_post_thumbnail(); ?>
</a>
<?php }?>
<?php endwhile; ?>
</div>

【讨论】:

    【解决方案2】:

    我没有用 wordpress 测试过它,所以我不能 100% 确定它会起作用。 这个想法是使用modulus 运算符(在此处查看符合您需求的示例http://codepad.org/78d2aAKp

    <?php query_posts('cat=6'); ?>
    <?php if (have_posts()) : ?>
    <!-- Your div starts here -->
    <div>
    <?php 
        while (have_posts()) : 
            the_post();
            $counter = 0;
            if($counter%3 == 0 && $counter > 0):
    ?>
    <!--Close and then open the div-->
    </div><div>
    <?php 
            endif;
    ?>
    <?php the_post_thumbnail(); ?>
    <?php $counter++; ?>
    <?php endwhile; ?>
    </div><!--/Your div ends here -->
    <?php endif; ?>
    

    【讨论】:

      【解决方案3】:
      <?php query_posts('cat=6'); ?>
      <?php if (have_posts()) : ?>
      <?php $counter=0; ?>
      <?php while (have_posts()) : the_post(); ?>
      <?php if($counter%3==0) : ?>        
      <div>
              <?php $counter=3; ?>
              <?php the_post_thumbnail(); ?>
              <?php $counter++; ?>
      </div>
      <?php else: 
      //Some code for other posts..
      endif;
      ?>
      <?php $counter++; ?>
      <?php endwhile; ?>
      <?php endif; ?>
      

      【讨论】:

        猜你喜欢
        • 2014-07-20
        • 2013-03-03
        • 1970-01-01
        • 2016-11-30
        • 1970-01-01
        • 1970-01-01
        • 2014-07-15
        • 2017-06-06
        • 1970-01-01
        相关资源
        最近更新 更多