Drupal random banner with optional path based image

  • Published by steve on 6 August 2011.

We had one customer that required a randomized banner but also had specific drupal pages where they wanted a particular header image to appear. This featured seemed worth the work so I dug into a few of the options out there and came out with a modified solution and minimal code.
This is some php I discovered on adaptive themes as well as the rotate.php that comes with marinelli theme and I have found it in other places as
well.

Hopefully a video and/or more screenshots posted to explain this better but basically this code outputs a random page header unless there is a match between your clean url path and the file name of your image.

So a random banner will display unless you are on the "contact" page and there happens to be a "header-contact.png".

step 1. Comment out in the css file the call to rotate.php
step 2. change #header to have a background matching your sites colour scheme.
step 3. add this to the beginning of template.php...

function unique_section_header() {
$path = drupal_get_path_alias($_GET['q']);
list($sections, ) = explode('/', $path, 2);
$section = safe_string($sections);
$filepath = path_to_theme() . '/images/sections/header-' . $path .'.png';
if (file_exists($filepath)) {
$output = $filepath;
}
else {
$output = path_to_theme() . '/img/banners/rotate.php';
}
return $output;
}

//Make a string safe
function safe_string($string) {
$string = strtolower(preg_replace('/[^a-zA-Z0-9_-]+/', '-', $string));
return $string;
}

Step 4. In this case I had to add

" />

(this went underneath the existing div id header section).

If you are reading this page it is just a draft, i hope to clean it up and include screen shots and more detailed instructions.