Step 1: Define Image Sizes
`add_action( 'after_setup_theme', function(){
$image_sizes = [
[
'size' => 'thumbnail',
'width' => 150,
'height' => 150
],
[
'size' => 'medium',
'width' => 300,
'height' => 300
],
[
'size' => 'medium_large',
'width' => 768,
'height' => 0
],
[
'size' => 'large',
'width' => 1024,
'height' => 1024
]
];
foreach( $image_sizes as $sizes ) {
add_image_size( sprintf('%s', $sizes['size']), $sizes['width'], $sizes['height'] );
add_image_size( sprintf('%s@%dx', $sizes['size'], 2), $sizes['width']*2, $sizes['height']*2 );
add_image_size( sprintf('%s@%dx', $sizes['size'], 3), $sizes['width']*3, $sizes['height']*3 );
}
} );`
Step 2: Insert Retina Sizes in SRCSET
`add_filter( 'wp_get_attachment_image_attributes', function( $attr, $attachment, $size ) {
$img_id = $attachment->ID;
$requested_image = wp_get_attachment_image_src( $img_id, $size );
$res = ['2x', '3x'];
$srcset = [];
$size_args = [
'width' => $requested_image[1],
'height' => $requested_image[2]
];
$srcset[] = $requested_image[0] .' 1x';
foreach($res as $r) {
$r_img = $size .'@'. $r;
$r_src = wp_get_attachment_image_src($img_id, $r_img);
if($r_src[3] == true) {
$srcset[] = esc_url($r_src[0]) .' '. $r;
}
}
$attr['src'] = $requested_image[0];
$attr['srcset'] = implode( ', ', $srcset );
unset($attr['sizes']);
return $attr;
}, 10, 3 );`
Have fun coding!
Top comments (0)