WordPress: responsive images for mobile devices with the wp_is_mobile() function

WordPress: responsive images for mobile devices with the wp_is_mobile() function

The main problem with mobile devices is related to the bandwidth they can use.

When you upload an image to the WordPress Media Library, WordPress automatically creates several copies of the original image using different resolutions. This comes handy if you want to target mobile devices with a resized version of the original image.

Either you’re using the default image dimensions provided by WordPress under its Media settings panel or your custom image dimensions specified in your theme, you can target mobile devices by using the wp_is_mobile() function.

This function returns a boolean value that evaluates to true when your site is accessed through a mobile device.

The main problem with mobile devices is not only related to their screen resolution (CSS Media Queries can actually fix this problem very well) but also to the bandwidth they can use.

In an ideal scenario, mobile devices are connected to the Internet through a Wi-Fi connection. In this case there’s no limit to the bandwidth they need to download our images.

But when mobile devices use their cellular data, there might be a limit (usually a monthly limit) imposed by the contract with their carriers. If you’ve subscribed to a monthly plan of, say, 2 Gb per month, you can’t download several megabytes of images every time you visit a website. Sooner or later you’ll reach your limit and you’ll be forced to pay an extra fee. Otherwise, there will be no Internet until the next month.

You can use wp_is_mobile() to deliver images based on the device in use with different sizes:


if( wp_is_mobile() ) {
    the_post_thumbnail( 'medium' );
} else {
    the_post_thumbnail( 'full' );
}

In this case, the post’s featured image is delivered in its resized version to mobile devices and in its full version to desktop computers.

It’s a simple but effective technique to help mobile device’s users to spare their bandwidth and reduce loading times.