This currently only works when using post thumbnails, so it won’t work for inline images in posts, but maybe I’ll get to that later. For now, here’s the small filter I created to convert post thumbnails into <picture> elements:

What’s happening here is rather simple: the ‘thumbnail’ size I’ve configured in WordPress is served as the default (no media query), thus the smallest image. Any screen 480px wide and above is served whatever the requested thumbnail size was, followed by loading the WordPress configured ‘large’ image for retina displays. You can read more about how the picturefill.js script works on the Github page, but the noscript tag will serve as a fallback and thus I’m just sending whatever image was going to be printed in the first place.

This could be extended with better support by adding some more specific image sizes in WordPress that could added here for various breakpoints. I kept it simple here by just providing three options: A small version (the thumbnail), the intended size (whatever the requested thumbnail size was), and a large version (for retina displays).

4 Responses to Integrating Picturefill.js with WordPress

I haven’t, unfortunately, but it wouldn’t be too much work. It would require adding a filter to the post_content so you could parse out each src, get the base image name, then perform a query for an attachment with that file name, and finish it off with the same the workflow. Could be useful if you’re using something like W3TC so those lookups aren’t happening on every pageview, especially if there are a fair amount of images on the page..

Yeah – the ability to avoid multiple lookups all the time is a key issue. You want the pages and images cached as quick as possbile. I’ve read the adaptive images PHP technique, but fear that the server would be running this load all the time, its not the best solution. Has to happen faster than that, which Is why some client side JS can reference a cache, not the host server itself. Im gunna give it a go… let you know how I go! I really just want it to be as smooth as possible, to just fluidly throw anything you want at the editor, and have the site crunch some hard responsive numbers in the background. One day! There’s no plugins for this you know of? Cheers

Awesome—yes, let me know how it works out! I haven’t done much searching for plugins that do this, specifically for the picturefill.js technique, but a quick search came up with this: https://github.com/kylereicks/picturefill.js.wp . Looks like it’s doing all the hard work of replacing the images in the post_content. Using an interesting technique of converting it into a PHP DOMDocument to traverse through images. Haven’t tested it out, but looks like it’s in the right direction.