Responsive Images with WordPress

December 5, 2013 1:28pm

We’ve all seen the statistics: more people are browsing the web on their mobile devices these days than there were humans alive in the year 36,000 BC. Wow, that’s a big number. And, as inhabitants of the greatest damn planet in this entire solar system, we know that once numbers get large, it’s time to start a Wikipedia page. And of course, Wikipedia pages are responsive these days. Because responsive design is not just a buzzword, it’s a buzz-worthy word.

And so on.

Now that I’ve finally sold you on the history of the world of responding to various screen sizes, let’s take a quick gander at how we can use WordPress to deliver appropriately sized images depending on where our visitors are coming from, saving them bandwidth and valuable milliseconds of lifegiving breath.

We’ll really only need two of them for today’s purposes though: is_mobile_device() and is_tablet(). Though note that they’re dependent on one another, so you’ll need to install (or modify) all of the functions to get these two to work.

Now let’s dive into our theme templates.

Modifying Theme Templates

Open up your single.php file template. Theme’s vary widely, but if you’ve got a wonderfully well built theme, you should be able to easily spot something like the following:

<?php if (has_post_thumbnail()) { the_post_thumbnail() } ?>

That’s the call to your “Featured Image”, as it’s referred to in the WP Admin, though in the web developing world we refer to it as the Post Thumbnail. Go figure, a secret language!

Thank you, you’re too kind. But hold the Nobel Prize for Simple If/Else/Then Statements until we take a moment to dissect and finalize.

Essentially, that code says, “If this post has a Featured Image, let’s show it, but let’s show different sizes to different devices. Show the thumbnail to phones, a medium-sized image to tablets, and a large image to all other devices.”

You’ll want to go into Settings > Media and determine which sizes are actually appropriate to use in your code. For example, if you’ve got your thumbnails set to 50px x 50px, that may be a little too small for devices. Use your best judgement. You can even go and create custom image sizes if you don’t want to change the settings for these three built-in WordPress image sizes. Open your functions.php file and paste in the following:

That will add three additional images sizes for all new uploaded files. It won’t resize old files, though there are plugins for that.

You can create any sizes you want. In this scenario, we’ve created a desktop version which will be at most 1400px wide and 1000px high. You can set 1000 to 9999 if you want to basically set no maximum height. In our mobile setting, we’ve added a fourth parameter, true, which tells WordPress to crop the image to these exact dimensions every time.

If you decided to use these exact sizes, your new code for your template would be: