Wordpress Loop: how to wrap each 3 posts into a di

2019-04-30 01:39发布

I'm trying this:

<?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; ?>

But it's not working! :/ Thank you!

3条回答
爷的心禁止访问
2楼-- · 2019-04-30 02:25
<?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; ?>
查看更多
Root(大扎)
3楼-- · 2019-04-30 02:37

I haven't tested it with wordpress so i'm not 100% sure it'll work. The idea is to use the modulus operator (see an example that matches your needs here 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; ?>
查看更多
趁早两清
4楼-- · 2019-04-30 02:45

Thanks for your support guys! :) I tried both solutions but didn't work, I ended up with this and works perfectly!

<?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>
查看更多
登录 后发表回答