钩子文档

max_srcset_image_width

💡 云策文档标注

概述

max_srcset_image_width 是一个 WordPress 过滤器,用于控制 srcset 属性中包含的最大图像宽度。它允许开发者自定义或移除默认的宽度限制,以优化响应式图像的加载。

关键要点

  • 过滤器名称:max_srcset_image_width,用于修改 srcset 中的最大图像宽度。
  • 默认值:2048 像素,但可通过过滤器覆盖。
  • 参数:$max_width(最大宽度,整数)和 $size_array(请求的宽度和高度数组)。
  • 相关函数:与 wp_calculate_image_srcset() 配合使用,计算 srcset 属性中的图像源。
  • 注意事项:如果主题设置了 $content_width 变量,它会优先于 max_srcset_image_width 的值。

代码示例

// 移除 srcset 中的最大宽度限制
function remove_max_srcset_image_width( $max_width ) {
    return false;
}
add_filter( 'max_srcset_image_width', 'remove_max_srcset_image_width' );

// 根据原始图像宽度动态调整最大宽度
function custom_max_srcset_image_width( $max_width, $size_array ) {
    $width = $size_array[0];
    if ( $width > 800 ) {
        $max_width = 2048;
    }
    return $max_width;
}
add_filter( 'max_srcset_image_width', 'custom_max_srcset_image_width', 10, 2 );

注意事项

  • 使用此过滤器时,需注意 $content_width 主题变量的影响,它可能覆盖过滤器的设置。
  • 过滤器返回 false 可以完全移除宽度限制,但需确保图像尺寸合理以避免性能问题。
  • 在自定义逻辑中,可以利用 $size_array 参数基于原始图像尺寸进行条件判断。

📄 原文内容

Filters the maximum image width to be included in a ‘srcset’ attribute.

Parameters

$max_widthint
The maximum image width to be included in the 'srcset'. Default '2048'.
$size_arrayint[]
An array of requested width and height values.

  • 0 int
    The width in pixels.
  • 1 int
    The height in pixels.

Source

$max_srcset_image_width = apply_filters( 'max_srcset_image_width', 2048, $size_array );

Changelog

Version Description
4.4.0 Introduced.

User Contributed Notes

  1. Skip to note 7 content

    Increase the limit based on the size of the original.

    In this example, we’re going to change the maximum allowed image width to 2048px if the original image is wider than 800px.

    function custom_max_srcset_image_width( $max_width, $size_array ) {
        $width = $size_array[0];
    
        if ( $width > 800 ) {
            $max_width = 2048;
        }
    
        return $max_width;
    }
    add_filter( 'max_srcset_image_width', 'custom_max_srcset_image_width', 10, 2 );

  2. Skip to note 8 content

    Hey Joe, your notes were a big help! Just for clarification though, what is the $max_width variable? When using this it appears to be looking at screen size, similar to a media query. For example: if screen is wider than 800px, load in the largest registered image size that’s not wider than 2048px. I’m a little confused about the “if the original image is wider than 800px” part. How does the original image size factor into what image is chosen?