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' ); |