Recently while working on a new blog layout for Code With Design I found myself finding that the code blocks look far to dull. My way of fixing this was to add an image but it didn’t end up helping anything, the image just looked repetitive and thus it is time to find some change and include a random image setup for each block.
WordPress uses a while loop to display the post information. I plan on taking advantage of this by adding a style to each of the div blocks. This will force the function to load for each div block and thus making the background images random for each individual block.
If the image was entered into the css then each block would look the same:
Function loads -> CSS is put into the style sheet -> style sheet loads into each element.
If the image was loaded on each div individually then the process will look something like this:
Function loads inside of div tag -> CSS is put into the looping div -> On each run the Function runs its random -> The random is placed out on each div.
The function loads a list of URL paths separated by comas. Then you are given the option of using placement properties and two of them so bottom right or top left is aloud. The final variable that this function uses is the repeat. This allows you to repeat the image by x, y, repeat or no-repeat.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | <?php //'/images/br_corner_cloud.png,/images/tr_corner_cloud.png','bottom','right','no-repeat' //creating a function function cj_random_image($image_array, $prop1, $prop2, $repeat) { //image arrays $image_array = explode(",",$image_array); $image_max = count($image_array); //random image count based on user input $image_rando = mt_rand(1, $image_max) - 1; //image echo 'url('.$image_array[$image_rando].')'.$prop1.' '.$prop2.' '.$repeat; } //created by calebj ?> |
The first thing the function does is takes what the user has placed into it then outputs it. The main inputs are the URL paths. These paths are counted and the count is used as the maximum on the random. This forces the mt_rand function to return the proper value which means that you can enter any amount of image URLs and the function will still work out.
In order to use this effectively you will need to place the function like so:
1 2 3 | <div style="background: #f2f2f2<?php cj_random_image('images/br_corner_cloud.png,images/cloud1.png','bottom','right','no-repeat'); ?> "> </div> |
If you would like to see this code working in action please click here. Keep in mind that you need to refresh the page to see the random clouds show up.

