Created
September 3, 2015 23:17
-
-
Save oknoway/e833d81c894cfa740390 to your computer and use it in GitHub Desktop.
brute force a bunch of inline css to change a background-image at specific breakpoints
This file contains 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
<?php if ( ! function_exists( 'get_attachment_sizes' ) ) : | |
/** | |
* Get attachments at a variety of sizes. | |
* | |
* @uses wp_get_attachment_image_src | |
* | |
* @param id - attachment id | |
* @param sizes - (optional) an array of registered image sizes as strings | |
* | |
* @return array of urls, dimensions, and size names | |
* | |
* @since 0.1.0 | |
*/ | |
function get_attachment_sizes( $id, $sizes ) { | |
$images = array(); | |
foreach( $sizes as $size ) { | |
$images[ $size ] = wp_get_attachment_image_src( $id, $size ); | |
} | |
return $images; | |
} | |
endif; //get_attachment_sizes | |
if ( ! function_exists( 'bg_img_styles' ) ) : | |
/** | |
* Get a block of responsive background image styles, scoped to the post id. | |
* | |
* @param $id - post id | |
* | |
* @param $sizes - array of registered image sizes as strings, passed directly to get_attachment_sizes | |
* | |
* @return string | |
* | |
* @since 0.1.0 | |
*/ | |
function bg_img_styles( $id, $sizes ) { | |
// get images | |
$images = get_attachment_sizes( get_post_thumbnail_id( $id ), $sizes ); | |
// determine largest size available | |
$widths = wp_list_pluck( $images, '1' ); | |
$biggest = array_search( max( $widths ), $widths ); | |
$style = '<style>' . "\n"; | |
foreach ( $images as $size=>$image ) : | |
$media_feature = ( $size == $biggest ) ? 'min-width' : 'max-width'; | |
$style .= '@media screen and (' . $media_feature . ':' . $images[ $size ][1] . 'px) {' . "\n"; | |
$style .= '#post-' . $id . ' { background-image:url(' . $images[ $size ][0] . '); }' . "\n"; | |
$style .= '}' . "\n"; | |
endforeach; | |
$style .= '</style>' . "\n"; | |
return $style; | |
} | |
endif; // bg_img_styles |
This file contains 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
<?php $style = bg_img_styles( get_the_ID(), array( 'hero', 'hero-md', 'hero-sm' ) ); | |
//I'd like to find a way to batch all these throughout the page and then output them all in wp_footer() | |
if ( $style ) echo $style; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment