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

It turns out that different browsers handle how they load images with srcset slightly differently and network speed is o

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/

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744726399a4590206.html

相关推荐

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

    It turns out that different browsers handle how they load images with srcset slightly differently and network speed is o

    1天前
    50

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信