0

I've been thinking about how I would use responsive images in Wordpress. My site has a fixed height, full width thumbnail at the top of each post. The built in Wordpress implementation of responsive images assumes a constant aspect ratio, which this use-case doesn't have.

I've created 6 image size, covering 3 widths and 2x pixels:

add_action( 'after_setup_theme', 'setup_image_sizes' );
function setup_image_sizes() {
  $height = 150;
  $width  = 250;
  $gutter = 50;

  add_image_size( 'single-width', $width, $height, true ); //Single width Thumbnail
  add_image_size( 'single-width-2x', $width * 2, $height * 2, true ); //Single width Thumbnail
  add_image_size( 'double-width', 2 * $width + $gutter, $height, true ); //Double width Thumbnail
  add_image_size( 'double-width-2x', ( 2 * $width + $gutter ) * 2, $height * 2, true ); //Double width Thumbnail
  add_image_size( 'triple-width', 3 * $width + 2 * $gutter, $height, true ); //Triple width Thumbnail
  add_image_size( 'triple-width-2x', ( 3 * $width + 2 * $gutter ) * 2, $height * 2, true ); //Triple width Thumbnail
}

Having done this, I have no idea how I would build a <picture> element. Any help and guidance would be appreciated.

0

The 'picture' element supports min-width and max-width.

If the image is a featured image then wp_get_attachment_image_src is what you would use:

// open the picture element
<picture>

// use this image if the width of a screen does not go over 599px
<source srcset="<?php echo wp_get_attachment_image_src( get_post_thumbnail_id(), 'whatever add_image_size you want to use', false )[0] ?>" media="(max-width: 599px)">

// call an image
<source srcset="<?php echo wp_get_attachment_image_src( get_post_thumbnail_id(), 'whatever add_image_size you want to use', false )[0] ?>">

// fall back for older browsers
<img srcset="<?php echo wp_get_attachment_image_src( get_post_thumbnail_id(), 'whatever add_image_size you want to use', false )[0] ?>">

// close the picture element
</picture>

You can have as many as you want

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.