admin管理员组

文章数量:1134247

I'm having a lot of trouble finding the solution. I would like to loop my last 3 posts with wp-query. I would like the 1st post to be in one div and the last 2 posts in another different div. So when I publish a new post the last post goes to div 1 and the previous one goes down to the 2nd div etc...

here is an example

$args = array(
    'post_type' => 'post',
    'post_per_page' => 3,
);

<?php $loop = new WP_Query($args);

$count = 0;
 while ($loop->have_posts()) : $loop->the_post();
if ($count == 0):
?>

    <!-- last post -->
    <div class="post-one">
        <h1><?php the_title();?></h1>
    </div>
<?php else:?>

    <!-- second et third post -->
    <div class="post-two">
    <h2><?php the_title();?></h2>
        <?php the_excerpt();?>
    </div>

<?php
$count ++;
endif;
endwhile;
wp_reset_postdata();?>

I'm having a lot of trouble finding the solution. I would like to loop my last 3 posts with wp-query. I would like the 1st post to be in one div and the last 2 posts in another different div. So when I publish a new post the last post goes to div 1 and the previous one goes down to the 2nd div etc...

here is an example

$args = array(
    'post_type' => 'post',
    'post_per_page' => 3,
);

<?php $loop = new WP_Query($args);

$count = 0;
 while ($loop->have_posts()) : $loop->the_post();
if ($count == 0):
?>

    <!-- last post -->
    <div class="post-one">
        <h1><?php the_title();?></h1>
    </div>
<?php else:?>

    <!-- second et third post -->
    <div class="post-two">
    <h2><?php the_title();?></h2>
        <?php the_excerpt();?>
    </div>

<?php
$count ++;
endif;
endwhile;
wp_reset_postdata();?>
Share Improve this question edited Sep 25, 2023 at 17:02 asked Sep 25, 2023 at 15:50 user188850user188850
Add a comment  | 

2 Answers 2

Reset to default 2

Your $count++ needs to be after your endif statement. It's not counting up because your counter is always at 0 which means you're always in your "if" portion of your statement not your "else". Like this:

$args = array(
        'post_type' => 'post',
        'post_per_page' => 3,
    );

<?php $loop = new WP_Query($args);

$count = 0;
while ($loop->have_posts()) : $loop->the_post();
    if ($count == 0):
    ?>
        <!-- last post -->
        <div class="post-one">
            <h1><?php the_title();?></h1>
        </div>
    <?php else:?>
    
        <!-- second et third post -->
        <div class="post-two">
        <h2><?php the_title();?></h2>
            <?php the_excerpt();?>
        </div>
        <?php
    endif;
    $count ++;
endwhile;
wp_reset_postdata();?>

You have error in code

if ($count == ):

it should be

if ($count == 0):

本文标签: wp querypost loop with different design depending on post