This question already has an answer here:

I've got the following code, which gets the first 3 posts. However, I am hoping to style each differently with if statements. But when I add if statements (to determine whether it is the first or second post), they are added, which on top of the first 3 posts: accidently creating 5 posts.

Is there a proper way to style the posts depending on whether they are first, second and third, but keep within the showposts => 3 attribute?

    <?php

    $lifestyle_cat = array(
        'category_name' => 'lifestyle',
        'showposts' => 3,
        'post_type' => 'post',
        'post_status' => 'publish',
        'orderby' => 'date',
        'order' => 'DESC'
    );

    $lifestyle_query = new WP_Query( $lifestyle_cat );
    if ( $lifestyle_query->have_posts()) {
        $i = 0; 
        while ( $lifestyle_query->have_posts()) {
             $i++;
            $lifestyle_query->the_post();
                if ($i==1) { // these are added and not within the 3 show posts
                   ?> <p> <?php  the_title();?>  i = 1</p> <?php
                } elseif ($i==2) { // these are added and not within the 3 show posts
                     ?> <p> <?php  the_title();?>  i = 2</p> <?php
                } ?>

            <p><?php the_title(); ?></p>

<?php } } else {
        // no posts found
    }

    wp_reset_postdata(); ?>

marked as duplicate by Michael, kaiser Feb 25 '14 at 12:45

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.

up vote 1 down vote accepted

You just need one more else statement, that's it.

<?php

    $lifestyle_cat = array(
        'category_name' => 'lifestyle',
        'showposts' => 3,
        'post_type' => 'post',
        'post_status' => 'publish',
        'orderby' => 'date',
        'order' => 'DESC'
    );

    $lifestyle_query = new WP_Query( $lifestyle_cat );
    if ( $lifestyle_query->have_posts()) {
        $i = 0; 
        while ( $lifestyle_query->have_posts()) {
             $i++;
            $lifestyle_query->the_post();
                if ($i==1) { // these are added and not within the 3 show posts
                   ?> <p> <?php  the_title();?>  i = 1</p> <?php
                } elseif ($i==2) { // these are added and not within the 3 show posts
                     ?> <p> <?php  the_title();?>  i = 2</p> <?php
                } else { ?>

            <p><?php the_title(); ?></p>
<?php } ?>

<?php } } else {
        // no posts found
    }

    wp_reset_postdata(); ?>
  • Thanks! I'm a little new to this. Does this get all posts, but only show 3, or only get 3 posts? Just curious about the loading time of the site. – tmyie Feb 25 '14 at 11:32
  • @tmyie if you are using showposts=>3 it will get 3 post only. You can accept the answer if correct. – Rajeev Vyas Feb 25 '14 at 11:39

Not the answer you're looking for? Browse other questions tagged or ask your own question.