Skip to content

Instantly share code, notes, and snippets.

@morgyface
Last active November 30, 2025 11:56
Show Gist options
  • Select an option

  • Save morgyface/259702f75d76b517cafe174eb6064b85 to your computer and use it in GitHub Desktop.

Select an option

Save morgyface/259702f75d76b517cafe174eb6064b85 to your computer and use it in GitHub Desktop.
PHP | WordPress | A generic responsive srcset image helper function
<?php
// A generic responsive image helper
function responsive_image( $acf_image_array, $alt, $sizes, $srcset, $class = null ) {
$default_image_url = get_bloginfo( 'template_directory' ) . '/assets/img/thumb_blank.svg';
$filetype_ext = 'svg';
if( !empty( $acf_image_array ) ) {
$image_url = $acf_image_array['url'];
$filetype = wp_check_filetype($image_url);
$filetype_ext = $filetype['ext'];
if( $filetype_ext == 'svg' ) {
$default_image_url = $acf_image_array['url'];
} else {
$default_image_size = current( $srcset ); // Grabs the first element of the array
$default_image_url = $acf_image_array['sizes'][$default_image_size]; // Uses first element for the default size
}
}
// Start the image assembly
$image = '<img ';
if ( $class ) {
$image .= 'class="' . $class . '" ';
}
$image .= 'src="' . $default_image_url . '" ';
$image .= 'alt="' . $alt . '" ';
if( $filetype_ext != 'svg' ) {
// Sizes
$image .= 'sizes="';
$sizes_index = 1;
$sizes_count = count($sizes);
foreach( $sizes as $screen => $image_width ) {
if( $screen != 0 ) {
$image .= '(min-width: ' . $screen . 'px) ';
}
$image .= $image_width;
if( $sizes_index < $sizes_count ) {
$image .= ', ';
}
++$sizes_index;
}
$image .= '" ';
// Srcset
$image .= 'srcset="';
$srcset_index = 1;
$srcset_count = count($srcset);
foreach( $srcset as $image_size ) {
$width = $image_size . '-width';
$image .= $acf_image_array['sizes'][$image_size] . ' ';
$image .= $acf_image_array['sizes'][$width] . 'w';
if( $srcset_index < $srcset_count ) {
$image .= ', ';
}
++$srcset_index;
}
$image .= '" ';
}
$image .= '/>';
return $image;
}
@morgyface
Copy link
Author

Tested and updated November 2025. Adding a class for the image is now optional.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment