钩子文档

wp_calculate_image_srcset

💡 云策文档标注

概述

wp_calculate_image_srcset 是一个 WordPress 过滤器,用于修改图像 'srcset' 属性的源数据。它允许开发者自定义或添加图像源,以支持响应式图像显示。

关键要点

  • 过滤器名称:wp_calculate_image_srcset,用于过滤图像 'srcset' 源。
  • 参数:$sources(源数组)、$size_array(请求尺寸数组)、$image_src(图像 src)、$image_meta(图像元数据)、$attachment_id(附件 ID)。
  • 用途:通过 apply_filters 调用,开发者可以修改 $sources 数组来添加、移除或调整图像源。
  • 相关函数:wp_calculate_image_srcset() 是计算 'srcset' 源的辅助函数。
  • 版本:从 WordPress 4.4.0 引入。

代码示例

function abc_custom_image_srcset( $sources, $size_array, $image_src, $image_meta, $attachment_id ){
   $w = get_custom_header()->width;
   $sources[$w] = array(
         'url'        => 'myfolder/myimage.jpg',
         'descriptor' => 'w',
         'value'      => $w,
   );
   return $sources;
}
add_filter( 'wp_calculate_image_srcset', 'abc_custom_image_srcset', 10, 5 );

📄 原文内容

Filters an image’s ‘srcset’ sources.

Parameters

$sourcesarray
One or more arrays of source data to include in the ‘srcset’.

  • width array
    • url string
      The URL of an image source.
    • descriptor string
      The descriptor type used in the image candidate string, either 'w' or 'x'.
    • value int
      The source width if paired with a 'w' descriptor, or a pixel density value if paired with an 'x' descriptor.

$size_arrayarray
An array of requested width and height values.

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

$image_srcstring
The 'src' of the image.
$image_metaarray
The image meta data as returned by ‘wp_get_attachment_metadata() ‘.
$attachment_idint
Image attachment ID or 0.

Source

$sources = apply_filters( 'wp_calculate_image_srcset', $sources, $size_array, $image_src, $image_meta, $attachment_id );

Changelog

Version Description
4.4.0 Introduced.

User Contributed Notes

  1. Skip to note 2 content

    function abc_custom_image_srcset( $sources, $size_array, $image_src, $image_meta, $attachment_id ){
    
       $w = get_custom_header()->width;
    
    // srcset val
          $sources[$w] = array(
                 'url'        => 'myfolder/myimage.jpg',
                 'descriptor' => 'w',
                 'value'      => $w,
          );
             return $sources;
          
       }
       add_filter( 'wp_calculate_image_srcset', 'abc_custom_image_srcset', 10, 5 );

You must log in before being able to contribute a note or feedback.