Show a Unique Header Image based on Path

Many sites want to show a unique header image for a particular section, node or view. There are many ways to achieve this including the the [Header Image]( and [Sections]( modules.

For a recent site build we wanted to avoid the overhead of a module for such a simple feature so I wrote a small function to show a different header image based on the path (the URL alias in this case). The function tests to see if an image exists for the path part (or "section") and if not displays a default image instead. To do this your site structure needs to have distinct sections, something you can create by writing alias's with the Path, and probably Pathauto, modules.

## Add the two functions to template.php

The first function looks for image names that match the "section" appended with the word "header-". **Sections are the first path part**. The format looks something like this: **header-[section].png**. For example if you have the path /blog, it will look for an image named header-blog.png.

Some other examples of sections:


It does not matter what comes after the first part of the path, the function will ignore it and return the same header image for the entire section. As you can see this relies heavily on using the Path module and most likely good planning with your [Pathauto]( patterns.

Note that all images are consider to be .png file type. All images need to be stored in `your_theme/images/sections` (of course you can adjust this by modifying the function).

The second function is just a helper to clean the string of any unwanted characters and to ensure it is lower case.

// Return a file based on the URL alias, else return a default file
function unique_section_header() {
$path = drupal_get_path_alias($\_GET['q']);
$sections, ) = explode('/', $path, 2);
$section = safe_string($sections);
$filepath = path_to_theme() . '/images/sections/header-' . $section .'.png';
  if (
file_exists($filepath)) {
$output = $filepath;
  else {
$output = path_to_theme() . '/images/sections/header-default.png';
//Make a string safe
function safe_string($string) {
$string = strtolower(preg_replace('/[^a-zA-Z0-9_-]+/', '-', $string));

## Call the image and print it in page.tpl.php

You will likely need to integrate with with your theme and style it with CSS.

<div class="header">
  <img src="<?php print $base_path . unique_section_header(); ?>" />

Alternatively if you would like the image set as a background-image using CSS you can place this in your page.tpl.php head.

<style type="text/css">
.header {
  background: url("<?php print $base_path . unique_section_header(); ?>") no-repeat 0 0;

[Here is the test theme we developed this on](, maybe it will be gone one day though...

Last updated 15th April, 2009 - 10:21pm

Authored by Jeff Burnz on