Created
April 21, 2018 14:07
-
-
Save janzikmund/87bd1c394ba46836ef54f13391e69e0d to your computer and use it in GitHub Desktop.
WordPress responsive images with SRCSET
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 | |
/** | |
* Responsive images | |
*/ | |
// allow featured images | |
add_theme_support( 'post-thumbnails' ); | |
// register image sizes - hard cropped | |
add_image_size( 'team-profile', 560, 560, true ); | |
add_image_size( 'blog-large', 1000, 1000, true ); | |
add_image_size( 'blog-small', 300, 300, true ); | |
// flexible | |
add_image_size( 'logo', 170, 170, false ); | |
// output image by ID with SRC set and sizes if defined | |
function ps_responsive_image($image, $size, $sizes = false) { | |
echo ps_get_responsive_image($image, $size, $sizes); | |
} | |
function ps_get_responsive_image($image, $size, $sizes = false) { | |
if(is_array($image)) $image = $image['id']; | |
if(!$sizes) { | |
$args = []; | |
} else { | |
$args = ['sizes' => $sizes]; | |
} | |
return wp_get_attachment_image( $image, $size, false, $args ); | |
} | |
/** | |
* add empty image to srcset in case image is hidden on certain sizes - make it look like 4px so it is not too small for retina screens | |
*/ | |
add_filter('wp_calculate_image_srcset', function($size_array, $image_src, $image_meta, $attachment_id) { | |
$size_array['4'] = [ | |
'url' => 'data:image/gif;base64,R0lGODlhAQABAAD/ACwAAAAAAQABAAACADs=', | |
'descriptor' => 'w', | |
'value' => 4, | |
]; | |
return $size_array; | |
}, 10, 4); |
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 | |
// from ACF | |
if($image = get_field('photo')): ?> | |
<?php ps_responsive_image($image, 'large', '(min-width: 1160px) 173px, (min-width: 1024px) calc(25vw - 117px), (min-width: 768px) calc(25vw - 72px), 150px'); ?> | |
<?php endif | |
// featured image as variable | |
if (has_post_thumbnail( get_the_id() ) ) { | |
$profile_image_html = ps_get_responsive_image(get_post_thumbnail_id( get_the_id() ), 'team-profile', '(min-width: 768px) 90px, 140px'); | |
} | |
// featured image directly within loop | |
the_post_thumbnail('blog-large', ['sizes' => '(min-width: 1160px) 296px, (min-width: 768px) calc(40vw - 126px), 81vw']); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment