Background Image on Site Header

Let’s say you wanted to do a page-specific background image on the site header. You’ve created a backend metabox for users to upload and manage the page-specific background image, and this stores it using the ‘be_page_header’ post meta key. But how do you display it on the website?

The snippet below shows how to filter the <header class="site-header"> element, updating it to have a style parameter defining the background image and adding a ‘has-image’ class so you can style these headers differently.

<?php
/**
* Site Header Background
*
* @author Bill Erickson
* @link http://www.billerickson.net/code/background-image-site-header/
*/
function be_site_header_background( $attributes ) {
$image = false;
if( is_page() )
$image = get_post_meta( get_the_ID(), 'be_page_header', true );
if( ! $image )
return $output;
$image = wp_get_attachment_image_src( $image, 'full' );
$attributes['class'] .= ' has-image';
$attributes['style'] = 'background-image: url(' . $image[0] . ');';
return $attributes;
}
add_filter( 'genesis_attr_site-header', 'be_site_header_background' );
view raw functions.php hosted with ❤ by GitHub

Bill Erickson

Bill Erickson is the co-founder and lead developer at CultivateWP, a WordPress agency focusing on high performance sites for web publishers.

About Me
Ready to upgrade your website?

I build custom WordPress websites that look great and are easy to manage.

Let's Talk