Making your WordPress header image responsive

A lot of web sites have a large header image, also known as a hero image. WordPress provides out-of-the box functionality to use these type of images in the design of your web site. Unfortunately most themes put out the full-sized image on every screen size. This wastes bandwidth, because in a lot of cases a smaller image could be served. This also makes your web site slower. And most people like fast loading web pages. WordPress does offer support for responsive images to help with this problem, but this feature seems to go unused with header images.

To use header images in WordPress you have to activate it in your theme by adding it to the functions.php:

function my_theme_setup() {
    add_theme_support( 'custom-header', array(
        'width'  => 2000,
        'height' => 500,
    ) );
add_action( 'after_theme_setup', 'my_theme_setup' );

In your header.php you then can add the following code to get a responsive header image:

if ( has_header_image() ) {
    $header_image_data = get_theme_mod( 'header_image_data' );
    echo wp_get_attachment_image( $header_image_data->attachment_id, 'full' );

Notice that the header_image() function is not used, but rather the meta data. The header image ID can then be used to output the responsive image with core WordPress image functions, because every uploaded image is available in multiple resolutions.

So go ahead and use the power of responsive images.

Back to top