Skip to content

Instantly share code, notes, and snippets.

@brycejacobson
Created August 28, 2018 20:08
Show Gist options
  • Save brycejacobson/c1e952233bd280e746879f0ca565c7a5 to your computer and use it in GitHub Desktop.
Save brycejacobson/c1e952233bd280e746879f0ca565c7a5 to your computer and use it in GitHub Desktop.
Set sizes attribute for responsive images and better performance in WordPress
<?php
/**
* Set sizes attribute for responsive images and better performance
*
* @param array $attr markup attributes.
* @param object $attachment WP_Post image attachment post.
* @param string|array $size named image size or array.
* @return array markup attributes
*/
function meta13_resp_img_sizes( $attr, $attachment, $size ) {
if ( is_array( $size ) ) {
$attr['sizes'] = $size[0] . 'px';
} elseif ( $size == 'small-square' ) {
$attr['sizes'] = '(min-width: 640px) 270px, 640px';
} elseif ( $size == 'medium-square' ) {
$attr['sizes'] = '(min-width: 640px) 512px, 1024px';
} elseif ( $size == 'large-square' ) {
$attr['sizes'] = '1200px';
} elseif ( $size == 'xlarge-square' ) {
$attr['sizes'] = '1440px';
} elseif ( $size == 'small-crop' ) {
$attr['sizes'] = '640px';
} elseif ( $size == 'medium-crop' ) {
$attr['sizes'] = '1024px';
} elseif ( $size == 'large-crop' ) {
$attr['sizes'] = '1200px';
}
return $attr;
}
add_filter( 'wp_get_attachment_image_attributes', 'meta13_resp_img_sizes', 25, 3 );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment