Created
August 28, 2018 20:08
-
-
Save brycejacobson/c1e952233bd280e746879f0ca565c7a5 to your computer and use it in GitHub Desktop.
Set sizes attribute for responsive images and better performance in WordPress
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 | |
/** | |
* 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