1

I am trying to achieve a loop that has an odd / even pattern within Wordpress. That doesn't work. It loops each post 10 times. How do I integrate the counting loop within the original foreach loop?

<?php  
$i=0;
$posts = get_posts(array('posts_per_page'=>9,'offset'=> 6));
foreach( $posts as $post ) : setup_postdata($post);

for ($i = 0; $i < 10; $i++)
{
  if ($i % 2 == 0)
  { ?>

MY ODD CONTENT

<?php  }
    else
    {
 ?>

MY EVEN CONTENT

<?php  }
    }
?>



<?php
$i++;
endforeach;
wp_reset_postdata();
?>
1
  • Do you need to split our loop in two for two post columns? Commented Apr 9, 2014 at 18:06

1 Answer 1

1
for($i = 0; $i < 10; $i++){
    if($i % 2 == 0){
        //echo even
        echo "Even: " . $i . "<br/>";
    } else {
        //echo odd
        echo "Odd: " . $i . "<br/>";
    }
}

simple for loop

for your content:

foreach( $posts as $post ) : setup_postdata($post);
   if($i % 2 == 0){
            //echo even
            echo "Even: " . $i . "<br/>";
        } else {
            //echo odd
            echo "Odd: " . $i . "<br/>";
        }
$i++
endforeach;

Complete code:

<?php  
$i=0;
$posts = get_posts(array('posts_per_page'=>9,'offset'=> 6));
foreach( $posts as $post ) : setup_postdata($post);
  if($i % 2 == 0){
        //echo even
        echo "Even: " . $i . "<br/>";
    } else {
        //echo odd
        echo "Odd: " . $i . "<br/>";
    }
$i++;
endforeach;
wp_reset_postdata();
?>
Sign up to request clarification or add additional context in comments.

3 Comments

Thanks for the ultra fast reply. Where do I have to integrate that?
remove that loop and and add my odd and even logic and you are good to go
@ScubaBen select my comment as answer if it resolves your problem.

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.