Last active
February 8, 2017 04:28
-
-
Save gnowland/5d6c4cdd6ef9024de325b87ab10ea0ff to your computer and use it in GitHub Desktop.
Function (+ accompanying css) for creating "cover"-like background images with "responsive" srcset via wp_get_attachment_image
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 | |
function bg_img_cover($id, $size, $focus = null, $classes = null, $atts = []) { | |
if ( !empty($focus) ) { | |
$atts['style'] = "top: {$focus}; -webkit-transform: translate( -50%, -{$focus}); transform: translate( -50%, -{$focus});"; | |
} | |
$img_src = wp_get_attachment_image($id, $size, false, $atts); | |
if( !empty($classes) ) { | |
$img_src = str_replace( 'class="', "class=\"{$classes} ", $img_src ); | |
} | |
return $img_src; | |
} | |
?> | |
<style> | |
.bg-img-cover { | |
position: absolute; | |
top: 0; | |
right: 0; | |
bottom: 0; | |
left: 0; | |
overflow: hidden; | |
} | |
.bg-img-cover img { | |
position: absolute; | |
top: 50%; | |
left: 50%; | |
width: auto; | |
max-height: none; | |
max-width: none; | |
min-height: 100%; | |
min-width: 100%; | |
transform: translate(-50%,-50%); | |
height: auto; | |
} | |
</style> | |
<div class="bg-img-cover"> | |
<?php | |
$img_id = (int)get_field( 'img_id' ); | |
$focal_pt = (int)get_field( 'img_focal_pt' ) . '%'; | |
$classes = 'classname'; | |
$other_atts = ['alt'=>'Some alt text perhaps?']; | |
echo bg_img_cover($img_id, 'size', $focal_pt, $classes, $other_atts); | |
?> | |
</div> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment