Created
December 18, 2016 01:54
-
-
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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