I can style the first three posts differently with no problem.

What I can't figure out, is how to do it and include the first three posts in a single container div (e.g. not a new div for each post).

The output would be something like this: (but obviously this will loop the container, and I don't want that...)

<?php
$wp_query = new WP_Query();
$wp_query->query(array(
'post_type'=>'post',
));

$i = 1; // counter to style first 3 different

if ($wp_query->have_posts()) : ?>
<?php while ($wp_query->have_posts()) : ?>
<?php $wp_query->the_post(); ?> 

<?php 
    if($i < 4) { // first 3 posts ?>

    <div class="container">
        <div class="post">
            <?php the_title(); ?>
        </div>
    </div>

    <?php } else { // not the first 3 posts  ?>

        <div class="differnt-post-style">
            <?php the_title(); ?>
        </div>

    <?php } ?>

    <?php endwhile; endif; ?>

closed as off-topic by Michael, Mark Kaplun, cybmeta, Mayeenul Islam, Robert hue Feb 13 '15 at 8:13

This question appears to be off-topic. The users who voted to close gave this specific reason:

If this question can be reworded to fit the rules in the help center, please edit the question.

  • Do you want one container to wrap the first three posts or 1 container around each of the first three posts? It sounds like you want your first three posts in a shared container, but I cannot quite tell. – Privateer Feb 10 '15 at 21:08
  • @Privateer - correct in the first thing you said. I want one container around the first 3 posts, not one around each. Thanks – acrane Feb 10 '15 at 21:12
  • 2
    you're almost there- open the container before the loop and close the container when $i equals 3. – Milo Feb 10 '15 at 21:23
up vote 3 down vote accepted

As Milo noted, the final result might look something like the following

if ($wp_query->have_posts()) {
    while ($wp_query->have_posts()) {
        $wp_query->the_post();
        $post_title = get_the_title();

        # On the first pass, write the start of your single container
        if ( 0 == $wp_query->current_post ) {
            echo '<div class="container">';
        }
        echo <<<HTML
<div class="different-post-style">
    {$the_title}
</div>
HTML;

        # On the 3rd pass, close your single container
        if ( 2 == $wp_query->current_post ) {
            echo "\r\n</div>";
        }

    }
    # Close the div if there were 2 or fewer posts
    if ( $wp_query->current_post < 2 ) {
        echo "\r\n</div>";
    }
}

Modified as per Milo's comment. I hadn't thought of that.

  • 1
    you can also use $wp_query->current_post property in place of your own counter. – Milo Feb 10 '15 at 21:29
  • Ahhh, that's it. Thanks a lot to both! @Milo and Privateer – acrane Feb 10 '15 at 21:37

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