WordPress: adding ‘srcset’ and ‘sizes’ attributes to image from customizer

WordPress automatically adds srcset and sizes attributes to all images coming from posts. That’s very neat.

But how to I get WordPress to add those attributes to images that come from a customizer input?

In my case: a default image for posts. That default image is displayed when no image was uploaded in a post. It’s uploaded by the user through the customizer and called using get_theme_mod.

image from post (works fine, all attributes are added):

get_the_post_thumbnail($post->ID, 'news', array('class' => 'img-responsive'));

if no image is provided: the default image is loaded (no ’scrset’ and ’sizes’)

'<img src="' . esc_url( get_theme_mod( 'default_image' ) ) . '" alt="default image" class="img-responsive" />'

wp_image_add_srcset_and_sizes() seems to be the way to go but it requires attributes I don’t know where to get.

Thank you for your help!

this function does the trick:

function create_responsive_image( $img ) {
  $img_id = attachment_url_to_postid( $img );
  $img_srcset = wp_get_attachment_image_srcset( $img_id );
  $img_sizes = wp_get_attachment_image_sizes( $img_id );
  return '<img src="' . $img . '" srcset="' . esc_attr( $img_srcset ) . '" sizes="' . esc_attr( $img_sizes ) . '">';