WordPress固定宽高比缩略图加载适配方案问询
解决WordPress同比例缩略图自动 fallback 问题
1. 注册全系列同比例缩略图尺寸
先确保你已注册所有需要的3:1比例缩略图,注册时必须开启强制裁剪以锁定比例:
add_action( 'after_setup_theme', 'register_proportional_header_sizes' ); function register_proportional_header_sizes() { // 3:1宽高比,强制裁剪保证比例一致 add_image_size( '2048x684-header', 2048, 684, true ); add_image_size( '1600x534-header', 1600, 534, true ); add_image_size( '1100x367-header', 1100, 367, true ); }
2. 自定义函数实现自动 fallback 逻辑
WordPress默认的wp_get_attachment_image不会优先匹配同比例尺寸,需要自定义函数来检查原图尺寸,选择最合适的同比例缩略图:
function get_header_image_with_fallback( $attachment_id ) { // 按尺寸从大到小排序,优先使用大尺寸 $proportional_sizes = [ '2048x684-header', '1600x534-header', '1100x367-header' ]; // 获取原图宽度信息 $original_meta = wp_get_attachment_metadata( $attachment_id ); if ( !$original_meta ) return ''; $original_width = $original_meta['width']; // 遍历尺寸列表,找到第一个原图足够生成的尺寸 foreach ( $proportional_sizes as $size ) { $size_info = wp_get_image_size( $size ); $target_width = $size_info['width']; // 原图宽度达标,或该尺寸已存在(兼容已生成的缩略图) if ( $original_width >= $target_width || wp_get_attachment_image_src( $attachment_id, $size ) ) { return wp_get_attachment_image( $attachment_id, $size ); } } // 所有同比例尺寸不满足时,返回默认中等尺寸(可按需调整) return wp_get_attachment_image( $attachment_id, 'medium' ); }
3. 替换原有调用代码
把原来的wp_get_attachment_image( $image, '2048x684-header' );替换为:
echo get_header_image_with_fallback( $image );
4. 补全旧图片的缩略图
如果之前上传的图片未生成新注册的尺寸,需使用Regenerate Thumbnails插件批量重新生成所有缩略图,确保新尺寸生效。
内容的提问来源于stack exchange,提问作者Rob
相关产品推荐
相关产品推荐

