0

I would like to publish 7 posts from the same category but embedded in different DIV or UL.

How could I simplify this code?

<?php
$query01 = array( 'numberposts' => 1, 'offset'=> 0, 'post_type' => array('product') );
$query02 = array( 'numberposts' => 3, 'offset'=> 1, 'post_type' => array('product') );
$query03 = array( 'numberposts' => 3, 'offset'=> 4, 'post_type' => array('product') );
?>

<div class="class news">
<ul class="280">
get_posts( $query01 ) -> FOREACH WITH ONE POST
</ul>
</div>

<div class="class editorial">
<ul class="650">
get_posts( $query02 ) -> FOREACH WITH THREE POST
</ul>
</div>

<div class="class images">
<ul class="980">
get_posts( $query03 ) -> FOREACH WITH THREE POST
</ul>
</div>

1 Answer 1

0

query for all posts at once and set a counter variable to check where you are in the loop.

$products = get_posts(
    array( 
        'numberposts' => 7,
        'post_type' => array('product')
    )
);
$count = 1;
foreach( $products as $product ):
    if( $count == 1 ):
        // first post
    elseif( $count > 1 && $count < 5 ):
        // two - four
    else:
        // four +
    endif;
    $count++;
endforeach;

EDIT- using your markup:

$products = get_posts(
    array( 
        'numberposts' => 7,
        'post_type' => array('product')
    )
);

?>
<div class="class news">
<ul class="280">
<?php
$count = 1;
foreach( $products as $product ):
    if( $count == 2 ):
        ?>
        </ul>
        </div>

        <div class="class editorial">
        <ul class="650">
        <?php
    elseif( $count == 5 ):
        ?>
        </ul>
        </div>

        <div class="class images">
        <ul class="980">
        <?php
    endif;

    echo '<li>post</li>';
    $count++;
endforeach;
?>
</ul>
</div>
4
  • I know that. But as you look at the code you notice I have three different DIVs for the three groups of posts. If I use the code you suggest also DIVs will be iterated.
    – Francesco
    Oct 27, 2012 at 22:29
  • it just comes down to how you count it- if it's the second post, close the first container and open the second, if it's the fifth post, close the second container and open the third.
    – Milo
    Oct 27, 2012 at 22:31
  • 1
    @Francesco see edit above
    – Milo
    Oct 27, 2012 at 22:38
  • Thank You Milo. The code is clear now and it works. Waiting for a more straightforward solution (in long snippets of code identify the sections is very hard), I will otherwise accept your answer.
    – Francesco
    Oct 28, 2012 at 18:03

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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