最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

functions - How can you limit srcset on a single type of page?

programmeradmin1浏览0评论

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 badges
Add a comment  | 

1 Answer 1

Reset to default 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/reference/hooks/wp_calculate_image_srcset/

发布评论

评论列表(0)

  1. 暂无评论