I could not use @nvartolomei solution the way it was. It was not functional but still a good starting point.
Here is my final solution:
I add 3 new image sizes
by doubling the original 3 sizes.
- large_retina
- medium_retina
- thumbnail_retina
Then I put filter when you call them in PHP in order to replace with
and height
by their non retina equivalent (since it's not always about dividing by 2).
function.php:
add_action( 'init', 'cjg_register_sizes' );
add_filter( 'image_downsize', 'cjg_retina_scale', 10, 3 );
function cjg_register_sizes(){
add_image_size( 'large_retina', get_option( 'large_size_w' ) * 2 , get_option( 'large_size_h' ) * 2 );
add_image_size( 'medium_retina', get_option( 'medium_size_w' ) * 2 , get_option( 'medium_size_h' ) * 2 );
add_image_size( 'thumbnail_retina', get_option( 'thumbnail_size_w' ) * 2 , get_option( 'thumbnail_size_h' ) * 2 );
}
function cjg_retina_scale( $value, $id, $size ) {
if ( $size == 'large_retina' OR $size == 'medium_retina' OR $size == 'thumbnail_retina' ) {
if ( !is_array( $imagedata = wp_get_attachment_metadata( $id ) ) )
return false;
if ( $size == 'large_retina') $regular_size = 'large';
elseif ( $size == 'medium_retina') $regular_size = 'medium';
else $regular_size = 'thumbnail';
$img_url = wp_get_attachment_url( $id );
$img_url_basename = wp_basename( $img_url );
if ( isset( $imagedata['sizes'][$regular_size] ) ) {
$width = $imagedata['sizes'][$regular_size]['width'];
$height = $imagedata['sizes'][$regular_size]['height'];
if ( isset( $imagedata['sizes'][$size] ) )
$url = str_replace($img_url_basename, $imagedata['sizes'][$size]['file'], $img_url);
else
$url = $img_url;
}else{
$url = $img_url;
$width = $imagedata['width'];
$height = $imagedata['height'];
}
return array( $url, $width, $height );
}
return $value;
}
Now you can just call your images this way
wp_get_attachment_image( $attachment->ID, 'thumbnail_retina' );
wp_get_attachment_image( $attachment->ID, 'medium_retina' );
wp_get_attachment_image( $attachment->ID, 'large_retina' );
Important: after adding the 3 new sizes, I regenerated all thumbnails with the regenerate-thumbnails plugin