WordPress Picture / Picturefill Shortcode

An important component of responsive design is handling images. Forcing mobile visitors download of full sized images isn’t optimal, neither is serving up blurry low-res images. On top of that if visitors are viewing on higher density displays then it’s all blurry.

A promising solution

The <picture> element is working its way into the spec for HTML5, but in the meantime there is a polyfill. Version 2.0 of the picturefill script builds around the proposed <picture> element, meaning the sytnax you use for the polyfill will be the same syntax used for native browser support.

The advantages of using the <picture> element include:

  • Specifying images for various breakpoints
  • Specifying images to use for high density displays
  • Using new image types (such as svg and webp) with fallbacks if not supported

How to Use It

In combination with custom image sizes in WordPress it’s a powerful tool to create responsive images.

add_image_size( 'thumb-800', 800, 800, false );
add_image_size( 'thumb-400', 400, 400, false );

add_filter( 'image_size_names_choose', 'custom_image_sizes' );

function custom_image_sizes( $sizes ) {
    return array_merge( $sizes, array(
        'thumb-800' => __('Desktop / Tablet Image'),
        'thumb-400' => __('Mobile Image'),
    ) );

Add that in your functions.php file and your new thumbnail sizes will be activated.

Your thumbnail sizes will vary depending on the needs of your site, but for this example we’ll be doing the following:

  • Upload a 1600px image that will be used as the high density image
  • Have the 800px image used for the desktop and tablet views, as well as the high density mobile view
  • Have the 400px image used for the mobile view

Now to use these images we’ll just need to add these shortcodes to the content:

[picture img="/path/to/image-400x400.png, /path/to/image-800x800.png 2x"]
[source srcset="https://cdn.ractoon.com/path/to/image-800x800.png, https://cdn.ractoon.com/path/to/image-full.png 2x" media="(min-width: 400px)"]

The img attribute in the picture shortcode defines the default image to use, in this case it’s the mobile image. The source shortcode defines the image to use for the tablet and desktop view which is currently set at anything greater than 400px wide. You can have as many source shortcodes as you’d like.

The Plugin

The full documentation is included along with the plugin on the Github repo:

Get the plugin on Github