钩子文档

fallback_intermediate_image_sizes

💡 云策文档标注

概述

fallback_intermediate_image_sizes 是一个 WordPress 过滤器,用于控制为非图像 MIME 类型(如 PDF)生成图像尺寸的行为。它允许开发者自定义这些文件类型应生成的图像尺寸列表,以匹配主题需求。

关键要点

  • 过滤器应用于非图像 MIME 类型(如 PDF)上传时,默认仅生成 'thumbnail'、'medium' 和 'large' 尺寸,可能不包含主题自定义尺寸。
  • 参数包括 $fallback_sizes(图像尺寸名称数组)和 $metadata(当前附件元数据),可通过 add_filter 修改返回的尺寸数组。
  • WordPress 4.7.0 引入此过滤器,用于扩展 wp_generate_attachment_metadata() 函数中的图像子尺寸生成逻辑。
  • 存在一个已知问题:在 wp-admin/includes/image.php 中,'thumbnail' 尺寸的 'crop' 参数被硬编码覆盖为 false,可能影响主题依赖的裁剪行为,目前无官方解决方案。

代码示例

add_filter(
  'fallback_intermediate_image_sizes',
  function ( array $fallback_sizes, array $metadata ) : array {
    return array_merge( $fallback_sizes, array_keys( wp_get_registered_image_subsizes() ) );
  }, 
10, 2 );

注意事项

使用此过滤器时,需注意 PHP 版本兼容性(示例代码适用于 PHP 7+),并了解 'thumbnail' 尺寸的裁剪行为可能被 WordPress 核心代码覆盖,这可能导致主题图像显示不一致。


📄 原文内容

Filters the image sizes generated for non-image mime types.

Parameters

$fallback_sizesstring[]
An array of image size names.
$metadataarray
Current attachment metadata.

Source

$fallback_sizes = apply_filters( 'fallback_intermediate_image_sizes', $fallback_sizes, $metadata );

Changelog

Version Description
4.7.0 Introduced.

User Contributed Notes

  1. Skip to note 2 content

    By default, when you upload an image such as a png or jpeg to the media library, WordPress generates all the standard image sizes that may be used by a theme, such as ‘thumbnail’ and ‘post-thumbnail’. Including any custom sizes you may have added to your theme using add_theme_support( 'post-thumbnails' ), set_post_thumbnail_size( 250, 250, true );, add_image_size( 'small', 500, 500 );, etc.

    But when you upload an image in pdf format, by default WordPress only generates the ‘thumbnail’, ‘medium’ and ‘large’ sizes — not all the other sizes your theme may use. Here’s a quick fix for that you can put into your theme’s functions.php:

    // Note for PHP 7 or higher, uses return type declaration
    add_filter(
      'fallback_intermediate_image_sizes',
      function ( array $fallback_sizes, array $metadata ) : array {
        return array_merge( $fallback_sizes, array_keys( wp_get_registered_image_subsizes() ) );
      }, 
    10, 2 );

    WordPress also has hardcoded behavior in wp-admin/includes/image.php to override whatever you have set the ‘crop’ parameter to for ‘thumbnail’ to false. This is a bug in my opinion because if your theme depends on images being cropped to specific dimensions or aspect ratio, this overrides it for no good reason I can think of. I don’t know of any workaround for this.