Im trying to generate responsive background images for my page header, using a modified version of this gist, but I cant get it to work correctly, and Im not sure if the issue is with wp_get_attachment_image_srcset
, wp_calculate_image_sizes
or the loop itself.
Here's my code:
Responsive Image Size Attributes
function adjust_image_sizes_attr( $sizes, $size ) {
$width = $size[0];
if($width >= 1260){
$sizes = '(max-width:575px) 575px, (max-width:767px) 767px, (max-width:991px) 991px, (max-width:1199px) 1199px, 1260px)';
}
elseif($width >= 900){
$sizes = '(max-width:767px) 100vw, (max-width:991px) 631px, (max- width:1199px) 839px, 900px)';
}
elseif($width >= 600){
$sizes = '(max-width:767px) 100vw, 600px';
}
else{
$sizes= '(max-width: ' . $width . 'px) 100vw, ' . $width . 'px';
}
return $sizes;
}
add_filter( 'wp_calculate_image_sizes', __NAMESPACE__ . '\\adjust_image_sizes_attr', 10 , 2 );
Generate Responsive Background Image CSS
function gsc_responsive_bg_images($attachment_id, $img_size, $selector)
{
$img_srcset = wp_get_attachment_image_srcset( $attachment_id, $img_size );
$sizes = explode( ", ", $img_srcset );
$css = '';
$prev_size = '';
foreach( $sizes as $size ) {
// Split up the size string, into an array with [0]=>img_url, [1]=>size
$split = explode( " ", $size );
if( !isset( $split[0], $split[1] ) )
continue;
$background_css = '.gsc-page-title-bar {
background-image: url(' . esc_url( $split[0] ) . ')
}';
// Grab the previous image size as the min-width and/or add the background css to the main css string
if( !empty( $prev_size ) ) {
$css .= '@media only screen and (min-width: ' . $prev_size . ') {';
$css .= $background_css;
$css .= "}\n";
} else {
$css .= $background_css;
}
// Set the current image size as the "previous image" size, for use with media queries
$prev_size = str_replace( "w", "px", $split[1] );
}
return $css;
}
**My Output: (in shorthand) ** default.jpg (original dimensions: 1170w)
@min-width: 1170px -> 768w.jpg
@min-width: 768px -> 120w.jpg
@min-width: 120px -> 500w.jpg
@min-width: 500px -> 700w.jpg
@min-width: 700px -> 200w.jpg
@min-width: 400px -> 600w.jpg
@min-width: 600px -> 800w.jpg
I was expecting
Seeing this, Im left with a bunch of questions:
- Why is this the CSS code thats being returned? Shouldnt it be the smallest size being returned at the default breakpoint and the largest size at
@min-width:1170px
? Why does@min-width: 768px -> 120w.jpg
, and@min-width: 700px -> 200w.jpg
? - Why are these the srcset images that are being generated? Shouldn't they be 900px, 767px, 839px, 631px?
Any and all help appreciated!