Skip to content

Instantly share code, notes, and snippets.

@noltedesign
Created May 17, 2018 18:52
Show Gist options
  • Save noltedesign/71028b79a2100aea3ff3de9f8f1314a8 to your computer and use it in GitHub Desktop.
Save noltedesign/71028b79a2100aea3ff3de9f8f1314a8 to your computer and use it in GitHub Desktop.
// Add responsive background image code
function responsive_bg_styles($attachment_id, $selector) {
$srcset = wp_get_attachment_image_srcset($attachment_id);
$sets = explode(', ', $srcset);
if (is_array($sets)) {
$set_build = array();
foreach ($sets as $set) {
list($url, $width) = explode(' ', $set);
$width = str_replace('w', '', $width);
$set_build[$url] = $width;
}
asort( $set_build );
$min_width = 0;
echo '<style>';
foreach ($set_build as $key => &$val) { ?>
@media (min-width: <?php echo $min_width ?>px) {
<?php echo $selector; ?> {
background-image: url(<?php echo $key; ?>);
}
}
<?php $min_width = $val+1;
}
echo '</style>';
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment