What’s the best way to use the Featured Image for responsive web design?

I have a brilliant idea and since WordPress already takes care of some of the work, I just need to find a good method to make this work.

I am working on a project that needs to be responsive to all devices, whether a desktop PC or mobile gadget. Thus, I want the images to also be responsive, meaning that mobile devices shouldn’t load 50KB+ images.

For each page or post, I can add a Featured Image using Post Thumbnails which, at full-size, the image is about 950×250 at ~60KB. If I load the website on an iPhone/Android, I wouldn’t want the ~60KB image to load, but instead would like the small thumbnail to load in its place.

The default method for responsive images is to make the width of the image 100% of the parent container, thus it will resize automatically if the parent container is also resized. Not the best method for larger images.

I thought about trying out Filament Group’s responsive image script, but I tried it and it didn’t work right. One way this could be accomplished is through user-agent detection, but I’d rather not do this method either since user-agents can be spoofed.

Here’s another method for resizing images on the fly, but this seems to be duplicating what WordPress has already done.

If there is a way of doing this with the Media Gallery images that WordPress has be default, with all the resized thumbnails already created, that would be preferable.

4 s
4

Step 1:

Define two custom image sizes, e.g.:

<?php
add_image_size( 'normal-thumbnail', 400, 300, false ); // Default image size
add_image_size( 'mobile-device-thumbnail', 200, 150, false ); // Mobile-device image size
?>

Step 2:

Implement your chosen means to determine client. There are several ways, and which method you use is outside the scope of this question. But, assuming you have a method that works for you, output the result to some variable, such as $mobile_device = true;

Step 3:

In your template files, output the image conditionally, based on client.

<?php
if ( true = $mobile_device ) { // client is mobile; be responsive
    the_post_thumbnail( 'mobile-device-thumbnail' );
} else {
    the_post_thumbnail( 'normal-thumbnail' );
}
?>

Note: you could repeat the if/else (or do a switch) for multiple form factors (i.e. screen sizes). Just add multiple custom image sizes, and conditionally test for each screen size you want to support.

Leave a Comment