Menu Search
Jump to the content X X
Smashing Conf Barcelona 2016

We use ad-blockers as well, you know. We gotta keep those servers running though. Did you know that we publish useful books and run friendly conferences — crafted for pros like yourself? E.g. upcoming SmashingConf Barcelona, dedicated to smart front-end techniques and design patterns.

RICG Responsive Images For WordPress

I recently teamed up with Mat Marquis of the Responsive Images Community Group to help integrate responsive images into the WordPress platform. We decided to refactor a plugin that I had built several months ago, hoping that it would lead to a more useable and performant solution.

After months of pull requests, conversations on Slack and help from WordPress’ core team, we’re finally ready to share what we’ve been working on. You can download and install RICG Responsive Images1 from WordPress’ plugin directory, while keeping track of our development progress on GitHub2.

What Does The Plugin Do? Link

WordPress hasn’t changed the way it outputs the img tag in quite some time. And although there are plenty of ways to hook into WordPress’ native functions and alter the img snippet, doing so can be overwhelming for beginners and non-theme developers alike. Compound that with the complexity of Picturefill and of the srcset specification, and WordPress users have had few options for implementing a clean and properly functioning responsive images solution.

To solve this problem, we set out to build a plugin that gives users responsive images as soon as the plugin is installed, with no extra effort needed. No admin setting, media uploading configuration or coding is required. The plugin comes with one dependency3, a polyfill for browsers that don’t yet support native responsive images. Removing this file is completely optional and will not affect the functionality of the plugin, as long as the user has a modern browser.

As soon as an image is uploaded through the media interface, WordPress automatically creates three variations of the image at different sizes. When the plugin is activated, adding “Featured” and content images to a post will return WordPress’ standard image markup, with an added srcset attribute4. We’re using the srcset attribute because it’s the easiest attribute for both developers and users to add. While the picture element provides the user with a richer set of options5, we felt that the srcset attribute makes the most sense as an out-of-the-box solution. It’s also best to use when you’re focusing on resolution-switching more than art direction6 (more on that later in the article).

<a href=""><img class="alignnone size-full wp-image-6" src="" srcset=" 150w, 300w, 1024w, 1800w" alt="a cool responsive image" width="1800" height="1800"></a>

The plugin is designed to be backwards-compatible, meaning that images added before the plugin was installed will be responsive when added to a post or “Featured Image” section. This is because it uses the image sizes previously defined by WordPress and the active theme’s functions.php file. The image ratio will be maintained throughout the srcset array, meaning that images differing from the aspect ratio of the initial uploaded image will be left out.

Theme developers can use the plugin to place responsive images wherever they’d like by using the tevkori_get_srcset_string() function, which takes an image’s ID and size as parameters.

<img src="myimg.png" <?php echo tevkori_get_srcset_string( 11, 'medium' ); ?> />

There’s also a tevkori_get_srcset_array() function that takes the same parameters and returns an array of srcset values for the specified image.

How Does The Plugin Work? Link

Most of the functionality happens when an image is dropped into WordPress’ WYSIWYG editor. Because all of the resized images will have been created during the uploading process, the only thing left to do is create an array containing the URLs of the available images in various sizes, as well as their dimensions. This array is then filtered to remove the image sizes with aspect ratios that don’t match the ratio of the full-sized image.

The array is created by calling the wp_get_attachment_image_src() function and storing the results. At the same time, we use wp_get_attachment_metadata() to retrieve the same results but for every possible variation of the image. Next, the ratio is calculated by multiplying each image’s width by the result of the initial image’s height divided by the initial image’s width. If that result matches the initial image’s height, then the image will be pushed into the final array, to be returned by the tevkori_get_srcset_array() function.

The tevkori_get_srcset_string() function calls tevkori_get_srcset_array() and places the result inside of the srcset attribute. A filter is applied to the image_send_to_editor function, where a regular expression is used to place the result of the tevkori_get_srcset_string() function directly after the src attribute in the image. The same process occurs for featured images, with a filter being applied to the post_thumbnail_html function.

If the image size is changed in the post’s editor, then the plugin will detect the change and update the srcset value accordingly. This ensures that the correct image ratio is always maintained. To enable this functionality, we’re using JavaScript to hook into the object7 and recalculating the srcset attribute by running the same image-ratio calculations defined in tevkori_get_srcset_array(). Before starting on this project, I was unaware of the object and its useful functionality. Because not much documentation for it exists, explaining in detail how we’re using it might be helpful. As it turns out, you can listen for an image-update event in the post’s editor by adding an event listener to the object. 'editor:image-update', function( args ) {
  var image = args.image;
  //more function logic

With this function, a theme developer can access every image as soon as it has been updated in the post’s editor. You can also take advantage of Underscore8, which is used as a dependency by the media uploader to edit image data on the fly. In the case of our plugin, we’re using a helpful Underscore utility to get our image-size ratios once the editor:image-update event has been fired.

// Grab all of the sizes that match our target ratio and add them to our srcset array.
_.each(sizes, function(size){
  var softHeight = Math.round( size.width * metadata.height / metadata.width );

  // If the height is within 1 integer of the expected height, let it pass.
  if ( size.height >= softHeight - 1 && size.height <= softHeight + 1  ) {
    srcsetGroup.push(size.url + ' ' + size.width + 'w');

To learn more about how we hook into the object, be sure to look at the code in wp-tevko-responsive-images.js.

The sizes Attribute Link

Currently, this plugin doesn’t add a sizes attribute9 to complement the srcset attribute. The reason is that we initially recognized that we could never predict what those sizes would need to be, because they depend on how the user’s theme is styled. While we are working on a solution to this issue, we’re encouraging all users to include a sizes attribute on their own, either manually or via another WordPress plugin, such as wp-lazysizes10. One thing to note is that the responsive images specification has recently changed, and use of the w descriptor must now be followed by a sizes attribute. Omitting the sizes attribute will render the markup technically invalid, while still falling back to a default size of 100vh.

What About Features X, Y And Z? Link

While much more can be done with responsive images, you’ve probably noticed a few use cases that this plugin doesn’t cover. The first thing that we’re usually asked about is a feature for art direction. Art direction refers to loading differently styled images at different breakpoints — whether that means entirely new images or the same image cropped or focused differently. This feature would require use of the picture element, which in turn would mean a lot more markup to generate the final image.

Adding this feature to WordPress would be impossible without the addition of a fairly complicated interface in WordPress’ media uploader, because the user would need to be able to define all breakpoints and then select images to be loaded in when those breakpoints are reached. Our goal for this plugin is to allow for a basic implementation of responsive images, with absolutely no configuration needed by the user. So, we’ve decided to omit this feature. We will, however, do our best to allow art direction to work side by side with our plugin as we expand the API for theme developers.

Lazy-loading and image compression are two other features that we have no plans to implement, simply because they fall beyond the scope of a more or less “default” solution for responsive images. Again, we aim to make the addition of these features possible for theme developers who use our plugin via a feature-rich API.

What’s Next? Link

While the plugin is available for everyone to download and install, we’re actively working to make it better. So, users can expect frequent updates, resolved issues and an all-around better functioning plugin as time goes on. We’re planning to add more features, such as the sizes attribute and hooks that allow theme developers to further customize the plugin.

Another feature we have yet to consider is ratio descriptors like 2x and 3x for “Retina” use cases. Better documentation and support are coming soon as well. Eventually, we’d like to see this plugin become a part of WordPress’ core, which means that it will stay minimalist, admin-less and easy to use.

(il, al, ml)

Footnotes Link

  1. 1
  2. 2
  3. 3
  4. 4
  5. 5
  6. 6
  7. 7
  8. 8
  9. 9
  10. 10
SmashingConf Barcelona 2016

Hold on, Tiger! Thank you for reading the article. Did you know that we also publish printed books and run friendly conferences – crafted for pros like you? Like SmashingConf Barcelona, on October 25–26, with smart design patterns and front-end techniques.

↑ Back to top Tweet itShare on Facebook


Tim Evko is a Front-End Engineer working on responsive e-commerce for BaubleBar in Manhattan, NY. An experienced WordPress theme developer and plugin author, Tim helps lead and manage the team responsible for developing the RICG-responsive-images WordPress plugin. Tim has had the pleasure of writing for CSS-Tricks,, Web Design Weekly, and SitePoint, where he focuses on responsive web development, performance, and general industry related issues.

  1. 1

    Tim, you’re the man. (And you too, Mat). WP has been running behind on responsive images, and it’ll be nice to have a new go-to. I’m going to install this and give it a shot today!

    • 2

      Thanks Dan!

      • 3

        Great idea – but why not just define responsive images via CSS like this?

        img {
        height: auto;

        This seamless scaling works perfect on my site. I usually upload all my images with a fixed maximum size and an optimized compression that’s more efficient like the internal WordPress JPG compression. Most images are just 50-100 kb in size and that’s even OK for mobile access.

        • 4

          Morten Rand-Hendriksen

          February 24, 2015 8:02 pm

          Responsive images have to do with serving the browser with the best fitting image. In a large browser window you’d serve up a large image, in a small browser window a small one. You can also serve up different images based on screen resolution, and in the future there may be options to serve up different images depending on bandwidth. The CSS method only deals with a singular image. Responsive images deals with various images at various sizes and resolutions.

          • 5

            Matt Mizwicki

            March 22, 2015 10:57 pm

            Morten thank you for explaining this in such a simple way. Extremely helpful for me.

  2. 6

    Morten Rand-Hendriksen

    February 24, 2015 7:21 pm

    On a longer time scale this is somewhat related to what we are doing in the ImageFlow project for core. We are working on redesigning and rethinking the process of adding images to posts and pages and part of that discussion revolves around how to provide placement and size selection. Early on in the project I brought up the point that in the not-so-distant future we need to look at responsive images within the framework of posts and pages, and that means the current modality of selecting an image size for display makes little sense. Rather than selecting the specific image that is of a certain size (thumbnail, small, medium, large, or original) in the future the user will select the size of the space allotted to the image and responsive image code will determine which actual image file is loaded. This looks to be the premise you are working under.

    I’m curious to see how this works for things like image galleries and themes and posts that display the thumbnail as these both typically show square-cropped images whereas the larger images in the array are typically not square.

    • 7

      Filip Michalski

      February 25, 2015 10:18 am

      I am working as solo developer for a creative agency and was vocalising a need for such solution either paid/free that would work with WordPress.

      My idea was: rather than making images ‘content aware’ designer/developer would define few image types that would have own [ viewportsize / image size ] ratio relations.

      Template uses 4 types of images: [Banner Image], [Blog Content Image], [Blog Summary Image],[Isotope Grid Image].
      The [Banner Image] needs always to be full-width without maintaining the aspect ratio between each breakpoint. So for Banner IMG we want: [fullsize=>1920×420, desktop=>1300×360, tablet=>768×300 ….. ]
      So on.

      This plugin uses similar approach, but it is more of a workaround than fully scaled solution

  3. 8

    Tim, your work on this could not have come at a better time for me!

    My question is this: if my predefined WP image sizes are not in the same aspect ratio (say 1:1) as the original image (say 16:9), will these 1:1 image sizes still be available for a mobile browser to choose from?

    Thanks and keep up the good work. This really helps keep my page load times low and UX more frictionless.

    • 9

      So right now the rounding calculations happen with the full sized as the main reference. I’m not sure if this will cause unintended consequences in your case, but you can change the default size in WordPress. Feel free to raise an issue in Github if you’re still struggling with this

  4. 10

    Thank you very much!!

  5. 11


    Thank you for your plugin. I just want to use the plugin for modern browsers and don’t want to use the javascript polyfill. Do I really have to delete that or is there an option somewhere?

  6. 13

    This is a great plugin to build websites into responsive form.Otherwise it will take time to build all images manually for every gadget.This plugin will reduce time and effort to build responsive websites especially for web designers who had taken time to resize images and fit into website.But now problem has been fixed.

    We will be expecting more and more new stuff from you.

    Thanks Tim.

  7. 14

    This is an area I’ve been watching with interest because I’m a total amateur but am really keen to be as mobile friendly as possible due to the nature of my site. So far I’ve been unable to implement any solution due to my own confusion around page caching (which I don’t think is an issue?) but also the use of existing ‘adaptive’ images solutions and CDNs which don’t work together. Will this solution work in partnership with a CDN (the phrase dumb cache gets mentioned)? You mention backward compatibility re existing images but I assume that doesn’t include adding markup to existing posts – just existing images added to new posts?

    • 15

      You’re correct, it won’t add code to old posts. It depends on how you’re using the cdn to deliver images, so I can’t say for sure. But I’d love to see what issues you’re coming up against, so please feel free to participate on Github!

  8. 16

    Are we going about this the wrong way? It seems to be getting more and more complex.

    A few years ago, we served a single image.

    Now, on a site that is using three breakpoints, and providing for devices at 1X, 1.5X, 2X and 3X we could end up having to generate 16 images!! (Three breakpoints means four defs).

    Are we trying to be too perfect for our own good?

    Ironically, one of the arguments is about saving bandwidth and thus making pages load faster, especially on mobile. But 2X and 3X images that are targeted at those devices are larger, thus we end up delivering larger pages to mobile.

    So if we are sending larger images to mobiles, why do we make such a fuss about page load times? Why do we care about compressing CSS and JS to save 50KB, when a single image at 2X can be sucking up way more than those 50KB over an above the 1X version?

    I really appreciate what Tim and Mat have done, but it does highlight the complexity that seems to be getting worse every year.

    The simplest solution is often the best. Yet no one seems to be looking for that solution. Everyone seems resigned to the complex solution.

    For example, your computer or phone has heaps of power. Why couldn’t browsers create 2X and 3X images on the fly? Use the power. Until they do, why not a JS script to do it? Even if it lags a little the first time (browser cached thereafter), so does downloading the 2X image the first time.

    (Sorry if this came thru twice – internet cut out while posting the first time)

    • 17

      Marvin Hagemeister

      February 26, 2015 11:55 am

      I completely agree. The long term solution seems to be either better mobile networks or smarter image compression algorithms. While the approach in the article is really nice and well thought out, it seems to be more of a workaround, because we just don’t have a better alternative yet available. It’s amazing if you need it now, but I hope there will be a more elegant solution in the future.

    • 18

      Primoz Cigler

      March 22, 2015 10:23 pm

      Using new srcset specification with a w descriptor you don’t need to take care anymore for 2x, 3x, … Nx screen densities. The browser is smart enough to pick the right source.

      Moreover, there will be settings available in the future in the mobile browsers (probably eventually in desktop as well) that you will opt-out for hi-quality pictures and browser will again download lo-res picture for you, even if the 2x version is available. Which is great, isn’t it?

  9. 19

    I remember the days with you would insert an image with one line of code :)

    I understand why such a simple thing is now so ridiculously complicated, but it still makes me chuckle.

  10. 20

    Cathie Dunklee-Donnell

    February 26, 2015 5:19 am

    It is about time we had a plugin like this. Thank you!

  11. 21

    This is a great plugin to build websites into responsive form.Otherwise it will take time to build all images manually for every gadget But now problem has been fixed.

  12. 22

    Kristi guerrero

    February 26, 2015 9:18 am

    Responsive design and layout is the final solution to hold a grip of mobile users. After the big bang of M-Commerce it is the direct and easiest solution of increasing the viewers.

  13. 23

    Your solution looks awesome! I hope there will be enough interest around it to develop it further. BUT!
    Unfortunately, I don’t see a general solution for responsive/adaptive images, not now, not in the near future, not ever. There is not a voice out there to regulate imgs usage on all devices.
    Going over and over after software solutions, everytime things are changing hardware-wise, is not the way. Although this could feed a lot of us, developers, the approach is totally wrong. How would be like operating systems to do this stuff for its users? Do you really believe it can’t be achieved by any of the major OS on the market in a week or so? In a simple patch?
    See, I have read tons of info about respimgs all over the web. More or less developed towards the future.
    Why don’t we ask companies to implement this in their next versions? Even as updates for the actual ones. Isn’t this the more convenient way for users?

  14. 24

    This is awesome! I used WP to create a website for a class I had, and I really am not experienced with coding. Even though I am not currently using WP, I can definitely appreciate what you’re doing here! In my opinion every little bit helps for a guy like me. Even though some people are seeming to dislike the approach I feel it has been a long time coming. Many of the others who have commented seem to think that there is an easier, or better way to do this, which is probably true. Mention of better mobile networks or compression algorithms are way over my head. But I’m extremely curious to see where this goes from here. Maybe I’ll get my website going again, working towards something bigger and better. Thanks!

  15. 25

    Patrick Danhof

    March 3, 2015 10:32 am

    I am a little bit confused, are you actually loading two images each time on mobile? The one at src attribute and one from the responsive set? You want to prevent extra download right?

    • 26

      Only 1 image is downloaded.

      Browsers that understand `srcset` chooses the optimum size from that set. Those that don’t, ignores the srcset & downloads the image at ` src`.

  16. 27

    The plugin is only in effect in posts then, correct? It would have no effect on pages using images outside of the WYSIWYG editor? I’m thinking of themes that have gallery features.

  17. 28

    This plugin rocks ! But I’m totally disappointed that some browsers always download big image defined in the “src” attribute. So in mobile context, when I analyze the loading process of a page, these browsers always download 2 images : the biggest first and the adapted in a second time !! I wish the problem will be resolved asap…
    My tests : Chrome works fine but Firefox downloads 2 images…

  18. 29

    Please correct me if I’m going about this the wrong way, or not understanding the plugins intention. I’m expecting that when I upload a large image,

    a) the uploads directory will get several versions of the same file at different sizes,
    b) the html will contain an img tag with srcset,
    c) that the appropriately sized image will be downloaded dependent on the viewport width
    [ and, d) that Picturefill will provide back-compatibility.]

    Are these assumptions correct? In Chrome, Safari, Firefox I’m seeing the same full size image served at all screen widths and simple resized with css.

  19. 30


    This is the one which i’m searching from a long while.

    Expecting more articles regards wordpress

  20. 31

    Daniel Keith

    May 9, 2015 8:58 am

    Hi Tim,
    Very nice article. I am running a wallpaper’s website. I want to know will this plugin helpful to decrease the load time of my website?


↑ Back to top