1

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?

2

Here'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.org/reference/hooks/wp_calculate_image_srcset/

| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.