函数文档

_wp_add_additional_image_sizes()

💡 云策文档标注

概述

_wp_add_additional_image_sizes() 是 WordPress 核心函数,用于添加额外的默认图像子尺寸,以优化前端在高分辨率设备上的图像显示。它通过生成更合适的 srcset 和 sizes 属性来提升用户体验。

关键要点

  • 函数添加两个默认图像尺寸:1536x1536(2倍 medium_large 尺寸)和 2048x2048(2倍 large 尺寸)。
  • 这些尺寸旨在增强大尺寸、高密度设备上的图像显示,支持响应式图像。
  • 主题和插件可以更改或移除这些尺寸,但不推荐,因为尺寸名称基于维度,更改可能导致误导。
  • 函数在 WordPress 5.3.0 版本中引入。

代码示例

function _wp_add_additional_image_sizes() {
    // 2x medium_large size.
    add_image_size( '1536x1536', 1536, 1536 );
    // 2x large size.
    add_image_size( '2048x2048', 2048, 2048 );
}

注意事项

用户贡献笔记提供了移除这些默认尺寸的示例代码,使用 remove_image_size() 函数,但需谨慎操作以避免影响图像显示效果。


📄 原文内容

Adds additional default image sub-sizes.

Description

These sizes are meant to enhance the way WordPress displays images on the front-end on larger, high-density devices. They make it possible to generate more suitable srcset and sizes attributes when the users upload large images.

The sizes can be changed or removed by themes and plugins but that is not recommended.
The size “names” reflect the image dimensions, so changing the sizes would be quite misleading.

Source

function _wp_add_additional_image_sizes() {
	// 2x medium_large size.
	add_image_size( '1536x1536', 1536, 1536 );
	// 2x large size.
	add_image_size( '2048x2048', 2048, 2048 );
}

Changelog

Version Description
5.3.0 Introduced.

User Contributed Notes

  1. Skip to note 2 content

    To remove those two image sizes you can use the code below:

    add_action( 'init', 'wpdocs_remove_default_additional_image_sizes' );
    function wpdocs_remove_default_additional_image_sizes() {
        remove_image_size( '1536x1536' );
        remove_image_size( '2048x2048' );
    }

    Code can be added to functions.php file of the theme.