WordPress: How to get the Header Image ID

Short story:
I’m trying to get the ID of the Header Image in WordPress.

All I found was this guide, which dosn’t seem to work anymore:http://nickohrn.com/2013/09/get-attachment-id-wordpress-header-image/

Read More

Long Story
I’m trying to make the WP Header responsive with an srcset. so I don’t want to use this code

<img id="masthead-bg" src="<?php header_image() ?>" alt=""> 

…but instead want to use the wp_get_attachment_image_srcset function to get the srcset of my header image. Only problem: I need an Image ID for this function -> The ID of my Header image.

<img id="masthead-bg" 
src="<?php header_image() ?>" 
srcset="<?php echo wp_get_attachment_image_srcset( image_id(), 'thumbnail' ); ?>" 
sizes="100vw" alt="">

Any suggestions?

Related posts

Leave a Reply

3 comments

  1. Try this…

        // Get the header image data    
        $data = get_object_vars(get_theme_mod('header_image_data'));
    
        // Now check to see if there is an id    
        $attachment_id = is_array($data) && isset($data['attachment_id']) ? $data['attachment_id'] : false;
    
        if($attachment_id) {
           // Put your image code here, user whatever function to get image by id you need
        }
    

    Note: if you use a proper WordPress function to get the image it should add in all the srcset etc stuff for you, to allow for responsive images.

  2. To answer the original question, I’ve found the simplest way to get the ID while I was filtering the markup that gets outputted by <?php the_header_image_tag(); ?> (introduced in v4.4).

    function header_img_markup( $html, $header, $attr) {
    
        // we can get the image ID by passing its src url to this method
        $header_img_id = attachment_url_to_postid($attr['src']);
    
        // now we can get its metadata from the db
        $header_img_data = wp_get_attachment_metadata($header_img_id);
    
        // now we can use the data
        $customSizeWidth = $header_img_data['sizes']['my-custom-size']['width'];
    
        // ...your custom output here...
        return $html;
    }
    add_filter('get_header_image_tag', 'header_img_markup', 20, 3);
    
  3. Responsive WordPress Header Image with fallback:

    if (get_header_image() !== '') {
        $attachment_id = attachment_url_to_postid(get_header_image());
        echo wp_get_attachment_image($attachment_id, 'large');
    } 
    if (get_header_image() == '') {
        echo '<h1>'.get_bloginfo( "name" ).'</h1>';
        echo '<h2>'.get_bloginfo( "description" ).'</h2>';
    }