I want to put add a different layout for the first post. This is 100% width, and below the rest of the post 50% (two columns).
I am using Bootstrap, this is the HTML:
<div class="col-sm-9">
<article></article>
<div class="row">
<div class="col-sm-6">
<article></article>
</div>
<div class="col-sm-6">
<article></article>
</div>
<div class="col-sm-6">
<article></article>
</div>
<div class="col-sm-6">
<article></article>
</div>
</div>
</div>
I know two ways to achieve this: Make two loops. In the first call the first post, and in the second loop call the rest. Or make only one loop, and use a counter like in this question.
But what will be a best practice? Is there a reason for doing one or another?
The more loops you make, more is your complexity. Loop inside loop makes your code less optimized. Use counter, it does not count in the complexity. It is just a variable. Secondly yes for every condition check e.g if
statement it has to do some work but if you use loop as you know there are multiple condition checks in loop as well.
here's the code
<?php
if( have_posts() ) :
$counter = 0;
while( have_posts() ) : the_post();
$counter++;
?>
<?php if( $counter == 1) { ?>
<div class="col-sm-9">
<article></article>
<?php } ?>
<?php if( $counter ==2 ) { ?>
<div class="row">
<div class="col-sm-6">
<article></article>
</div>
<?php } else { ?>
<div class="col-sm-6">
<article></article>
</div>
<?php } ?>
<?php endwhile; ?>
</div>
</div>
<?php endif; ?>
you can also do it with rewind_posts() though , if you want a cleaner code http://codex.wordpress.org/Function_Reference/rewind_posts