Last active
October 22, 2015 08:31
-
-
Save wiesson/71239af49233fb74c0a8 to your computer and use it in GitHub Desktop.
Responsive Wordpress Background Images
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
add_image_size('img-l', 1024, 702); | |
add_image_size('img-m', 768, 372); | |
add_image_size('img-s', 480, 320); | |
add_image_size('img-xs', 320, 200); | |
/** | |
* Get WP Attachment as responsive background image | |
* @param int $id | |
* @return string | |
*/ | |
function getResponsiveBackgroundImage(int $id) | |
{ | |
$class = ".img-bg-"; | |
$mediaQuery = array('481px' => "img-s", '768px' => 'img-m', '1030px' => 'img-l', '1240px' => 'full'); | |
$alt = get_post_meta($id, '_wp_attachment_image_alt', true); | |
$style = "<style>" . $class . $id . " { background: url(" . wp_get_attachment_image_src($id, 'img-xs')[0] . ") no-repeat center center; background-size: cover; }"; | |
foreach ($mediaQuery as $media => $image) { | |
$style .= "@media only screen and (min-width: " . $media . ") { " . $class . $id . " { background: url(" . wp_get_attachment_image_src($id, $image)[0] . ") no-repeat center center; background-size: cover; } }"; | |
} | |
$style .= "</style>"; | |
return $style; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment