0

Let's say I have a regular main page listing posts, like in any regular WP blog. Now, I'd like to achieve this: if it's the first post in the list, use some layout, if second, another layout, if third, then another layout and so on. Even better: if it's post 1, 5, 9, 15, 22 -> use layout 1 . If it's 2,3,8, 12,14 -> use layout 2 (basically, adding re-usable code)

For reference:

post 1 -> <div class="layout1">....</div>
post 2 -> <div class="layout2">....</div>
post 3 -> <div class="layout3">....</div>
post 4 -> <div class="layout1">....</div>
post 5 -> <div class="layout1">....</div>

(so there's no "every given number of posts, use layout x", but "if in spot X, use layout X")

I know I can do this with CSS, it's a snap, but it's not smart at all, since I want to use different post-thumbnail sizes, so loading big images for small sizes is ridiculous.

I tried looking for WP conditionals, if_post and what not, but couldn't find anything, so really no clue on how to achieve this (without using masonry, which will have the same post_thumbnail problem)

Any ideas on how to do this?

Thanx in advance and Happy New Year for everybody! :)

1

WP_Query will track which post is current. For example:

$p = new WP_Query(array('post_type'=>'post','posts_per_page'=> 10));
if ($p->have_posts()) {
  while ($p->have_posts()) {
    $p->the_post();
    echo $p->current_post.'<br>';
  }
}

You could use that to selectively format your posts. For example

$p = new WP_Query(array('post_type'=>'post','posts_per_page'=> -1));
if ($p->have_posts()) {
  while ($p->have_posts()) {
    $p->the_post();
    switch ($p->current_post) {
      case 0:
      case 3:
      case 4:
        echo '<div class="layout1">....</div>';
      break;
      case 1:
        echo '<div class="layout2">....</div>';
      break;
      case 2:
        echo '<div class="layout3">....</div>';
      break;
    }
  }
}

I can't tell if you have a pattern that you might be able to map mathematically or if you are going to have to manually construct the whole switch.

3
  • thank you s_ha_dum, will play around a bit and let you know :) – Devin Dec 29 '13 at 23:36
  • The code I posted duplicates your sample output so it should work. – s_ha_dum Dec 30 '13 at 0:18
  • yes, with some customization I made it work, many thanx s_ha_dum! :) – Devin Dec 30 '13 at 2:17

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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