I will start saying with I’m really a noob on PHP and I need to solve a problem, I know the logic, however in the syntaxis I’m dead.
Here is the case.
I need to create a wordpress loop, which will display images with a span class with 3 different colors, 1 per loop, so it goes, 0 = green, 1 = blue, 2 = pink.
Since I have 3 colors a X numbers of outputs, I think about creating an array from 0 to 2, an assign a value according the colors I described, then create a conditional that will go as, if i > 2, then i = 0.
With this I will just echo the array value on my span class, that should do the trick.
What I need help with is creating the syntaxys for this, so far, this is what I have:
<?php while ( have_posts() ) : the_post(); $i = 0 ?>
<?php
$array = array(
0 => 'green',
1 => 'blue',
2 => 'pink',
);
?>
<span class="<?php echo $array ?>;">Title</span>
<?php
$i++;
?>
<?if ($i > 2) { $i=0; } endif; ?>
<?php endwhile; ?>
I’m missing the part where I should compare the counter i with the array.
I would appreciated any help!
Thanks in advance.
There were a few problems with this code (as well as some suggestions).
$i = 0;inside the while loop meaning it was always== 0$arrayinstead of one itemHow to fix:
$i = 0;outside the while loop (so it’s defined before the loop)echo $array[$i]to echo the item id you’re looking for$i / 3and use that as your indexYou could also
$colors = array('green', 'blue', 'pink');which will behave the same – this works as PHP uses a default index starting at 0$colorsinstead of$arrayto make it clearer what’s going on<?phptags to keep things clearer$colors) outside of the loopSee the complete code below
And a further simplification