DEV Community

Muhammad Ahmad
Muhammad Ahmad

Posted on

How to Make Images Retina-Ready for your WordPress Theme without any plugin?

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 );
}
Enter fullscreen mode Exit fullscreen mode

} );`

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;
Enter fullscreen mode Exit fullscreen mode

}, 10, 3 );`

How to Make Images Retina-Ready for your WordPress Theme without any plugin?

Let's first understand why its important for your website to retina-ready nowadays. With the rise of very high density "super retina" displays in the newest

favicon ahmadthedev.com

Have fun coding!

Top comments (0)