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();
?>
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();
?>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.