random header images for homepage

PHP isn’t so bad once you get the hang of it! The use of the glob() function allowed me to query all images in a given folder, and stick them in an array. So now I can dynamically update my header images without having to mess with the PHP code itself. The important segment is found in header.php, or header-xxxx.php depending on what you’re calling:
<?php
$imgarray = glob("./wp-content/headers/homepage/\*.\*",1);
$cnt = count($imgarray);
$rn = rand(0,$cnt-1);
$img = $imgarray[$rn];
?>
FYI glob() requires an absolute path…so you can’t simply use the content_path() function as I was before. However, now I can drop all the images I want into wp-content/headers/homepage and they will automatically be added to the list of possible images. I just have to remember to crop them properly to 1040x250 or they’ll show up as their original size.

PHP is annoying

I wanted to randomize the header image for the gaming subcategory…talk about a pain in the neck! PHP seems to be pretty robust, but the syntax is quite different than either Python or C which I am used to. I had to change a few things, first up - category.php; I went from
get_header();
to
<?php
if ( is_category( 'Gaming' ) ) :
  get_header( 'gaming' );
elseif ( is_404() ) :
  get_header( '404' );
else :
  get_header();
endif;
?>
Apparently there are different methods of doing this with curly brackets, but this was the cleanest example I could find and it resembles python. It basically says to use header-gaming.php if the category matches “Gaming”. Next up was that file, which I just made a copy of header.php. I added this relavant code:
<?php
$url = content_url();
$img0 = $url . "/uploads/2013/06/cropped-ORIGINAL.jpg";
$img1 = $url . "/uploads/2013/06/cropped-KUNARK.jpg";
$img2 = $url . "/uploads/2013/06/cropped-VELIOUS.jpg";
$img3 = $url .
"/uploads/2013/06/cropped-arma3_e32013_screenshot_06-100041641-orig1.png";
$imgarray = array($img0,$img1,$img2,$img3);

$cnt = count($imgarray);
$rn = rand(1,$cnt-1);
$img = $imgarray[$rn];
//echo "selecting image " . $rn . " out of " . $cnt;
?>
This was a pain. The first line assigns the variable $url to the wordpress content directory as this is where the header images are currently stored. The next 4 lines combine that directory with the remaining image path. Next I add all of these images to an array called imgarray. I can then count how large that array is, generate a random number, then assign $img using the random number as an index for the $imgarray. Next is the HTML part that actually places the image:
<img src="<?php echo $img; ?>"...
which is pretty straight forward.

Next up: scanning a directory for a list of images and automatically adding them to an array as to make this process automatic. This will allow me to randomize each page with pretty pictures. Start with these stack overflow suggestions.