Assigning random CSS pseudo classes using PHP arrays

admin

Administrator
Staff member
The goal: to randomly assign different color CSS backgrounds to a Wordpress-generated tag cloud on a mouseover by the user.

My method (so far unsuccessful):

Code:
        <?php 
            $colors = array( 0 => "#645676", "#427048", "#654335", "#ab2805", "#a59d57", "#302f2f", "#81510d" );
            $tags = wp_tag_cloud('smallest=10&largest=10&unit=px&number=40&format=array&echo=0'); 
            shuffle($tags); 
            foreach ($tags as $tag) { 
                    shuffle($colors);
                echo "<li style=\"a:hover=background:".$colors[0].";\"> $tag \n </li>"; 
            } 
        ?>

I figured a foreach PHP loop would be the easiest way to do this. I created two arrays ($colors and $tags). I manually filled $colors with the hex tags of the colors I want to use. $tags is populated by the wordpress tag cloud array (more info here if interested: <a href="http://codex.wordpress.org/Function_Reference/wp_tag_cloud" rel="nofollow">http://codex.wordpress.org/Function_Reference/wp_tag_cloud</a>) which I have set to grab the 40 most popular tags on this blog.

I then use the PHP shuffle function on $tags to mix up the top 40 tags, run those 40 tags through a foreach loop which then randomly assigns one of the shuffled $colors to a CSS pseudo class which gets echoed out.

The code works, here is a sample of the output:

Code:
&lt;li style="a:hover=background:#302f2f;"&gt; &lt;a href='http://localhost:8888/nutritionwonderland_2/tag/truvia/' class='tag-link-49' title='3 topics' style='font-size: 10px;'&gt;truvia&lt;/a&gt; 
 &lt;/li&gt;&lt;li style="a:hover=background:#81510d;"&gt; &lt;a href='http://localhost:8888/nutritionwonderland_2/tag/cancer/' class='tag-link-8' title='11 topics' style='font-size: 10px;'&gt;cancer&lt;/a&gt; 
 &lt;/li&gt;&lt;li style="a:hover=background:#427048;"&gt; &lt;a href='http://localhost:8888/nutritionwonderland_2/tag/antioxidants/' class='tag-link-93' title='4 topics' style='font-size: 10px;'&gt;antioxidants&lt;/a&gt; 
 &lt;/li&gt;

The problem: when I mouseover any of the tags, the background never shows up. This makes me think the CSS may be bad.

A couple of questions for the peanut gallery:<br>
1) How do you apply CSS pseudo classes randomly via PHP?<br>
2) Even if this worked, would the CSS output here by standards compliant?<br>
3) Should I even worry about standards here?

Interested to hear any responses - thanks in advance for your time.