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.


Comments

comments powered by Disqus