Skip to content

Instantly share code, notes, and snippets.

@megmorsie
Created December 18, 2016 01:54
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save megmorsie/a26852d088ca5e05bf93fb7837149c3c to your computer and use it in GitHub Desktop.
Save megmorsie/a26852d088ca5e05bf93fb7837149c3c to your computer and use it in GitHub Desktop.
This is an example of using WordPress Image Sizes and the picture element to implement responsive images. I prefer this method over using srcset on the img tag because that method doesn't account for window resizing or server-side caching.
<?php
// Put in functions.php
/**
* Image Sizes
*/
add_image_size( 'featured', 960, 250, array( 'center', 'center' ) );
add_image_size( 'cropped', 450, 180, array( 'center', 'center' ) );
// Put in Template File (For Example, single.php)
if ( has_post_thumbnail() ) {
$alt = get_post_meta( get_post_thumbnail_id(), '_wp_attachment_image_alt', true ); ?>
<picture>
<source media="(min-width: 450px)" srcset="<?php the_post_thumbnail_url( 'featured' ); ?>">
<img src="<?php the_post_thumbnail_url( 'cropped' ); ?>" alt="<?php echo $alt; ?>">
</picture>
<?php } // end if ?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment