Last active
November 1, 2017 08:32
-
-
Save apkoponen/69613decf11e13454ae4 to your computer and use it in GitHub Desktop.
Output a style tag with responsive background image sizes (for WordPress 4.4 and up).
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| /** | |
| * Output a style tag with responsive background image sizes. | |
| * | |
| * Example: | |
| * | |
| * the_attachment_image_responsive_bg_style(132, "#section-top", 40) | |
| * | |
| * For attachment ID 132, for an element with id="section-top" and a page | |
| * with 20px padding on both sides of the element. | |
| * | |
| * @param int $attachment_id Attachment ID | |
| * @param string $selector CSS-selector | |
| * @param int $page_padding Horizontal padding around the element for calculating min-width | |
| */ | |
| function the_attachment_image_responsive_bg_style($attachment_id, $selector, $page_padding = 0) | |
| { | |
| $srcset = wp_get_attachment_image_srcset($attachment_id); | |
| $sets = explode(', ', $srcset); | |
| if (is_array($sets)) { | |
| echo '<style>'; | |
| $smallest_image_url = ''; | |
| $smallest_width = 9999; | |
| foreach ($sets as $set) { | |
| list($url, $width) = explode(' ', $set); | |
| if ($smallest_width > $width) { | |
| $smallest_image_url = $url; | |
| } | |
| $width = str_replace('w', '', $width) + $page_padding; | |
| ?> | |
| @media (min-width: <?php echo $width; ?>px) { | |
| <?php echo $selector; ?> { | |
| background-image: url(<?php echo $url; ?>); | |
| } | |
| } | |
| <?php | |
| } | |
| echo $selector; ?> { | |
| background-image: url(<?php echo $smallest_image_url; ?>); | |
| } | |
| <?php | |
| echo '</style>'; | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Good job