It turns out that different browsers handle how they load images with srcset slightly differently and network speed is of vital importance for me.
I don't want to globally limit srcset, but I want to make sure that there are no srcsets over a certain width only on posts.
Is this possible with code?
It turns out that different browsers handle how they load images with srcset slightly differently and network speed is of vital importance for me.
I don't want to globally limit srcset, but I want to make sure that there are no srcsets over a certain width only on posts.
Is this possible with code?
Share Improve this question asked Feb 20, 2020 at 0:24 notthehoffnotthehoff 1114 bronze badges1 Answer
Reset to default 2Here's an example for filtering out sizes above set limit from the srcset
attribute on certain post type. This works for featured image and images added to the post content with Gutenberg. (Tested on Twenty Twenty theme).
function filter_wp_calculate_image_srcset( $sources, $size_array, $image_src, $image_meta, $attachment_id ) {
global $post;
if ( $post && 'post' === $post->post_type ) {
$max_size = 600; // change as needed
// var_dump($sources);
foreach ($sources as $size => $image) {
if ( $size > $max_size ) {
unset($sources[$size]);
}
}
// var_dump($sources);
}
return $sources;
}
add_filter( 'wp_calculate_image_srcset', 'filter_wp_calculate_image_srcset', 11, 5 );
Filter docs: https://developer.wordpress/reference/hooks/wp_calculate_image_srcset/
发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744726399a4590206.html
评论列表(0条)