php WP仅在需要时才创建图像大小

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了php WP仅在需要时才创建图像大小相关的知识,希望对你有一定的参考价值。

add_filter( 'image_downsize', 'ml_media_downsize', 10, 3 );
function ml_media_downsize( $out, $id, $size ) {

	$dims = null;
	$crop = false;
	 
	if( is_array( $size ) ) {
		// don't handle these for now. but if you want on-the-fly sizes, comment out
		// the return statement
		return false;
		$dims = $size;
		// create custom image size name consisting of widthXheight
		$size = sprintf( "%dx%d", $size[0], $size[1] );
	}
	 
	// If image size exists let WP serve it like normally
	$imagedata = wp_get_attachment_metadata( $id );
	if ( is_array( $imagedata ) && isset( $imagedata['sizes'][$size] ) )
	return false;
	 
	// Check that the requested size exists, or abort
	if ( $dims === null ){
		global $_wp_additional_image_sizes;
		if ( !isset( $_wp_additional_image_sizes[$size] ) )
		return false;
	}
	 
	// Make the new thumb
	if( $dims ){
	 
		// we got passed custom width/height as array...
		if ( !$resized = image_make_intermediate_size(
			get_attached_file( $id ),
			$dims[0],
			$dims[1],
			$crop ) ) {
			return false;
		}
	 
	} else {
	 
		if ( !$resized = image_make_intermediate_size(
			get_attached_file( $id ),
			$_wp_additional_image_sizes[$size]['width'],
			$_wp_additional_image_sizes[$size]['height'],
			$_wp_additional_image_sizes[$size]['crop'] ) ) {
			return false;
		}
	 
	}
	 
	// Save image meta, or WP can't see that the thumb exists now
	$imagedata['sizes'][$size] = $resized;
	wp_update_attachment_metadata( $id, $imagedata );
	 
	// Return the array for displaying the resized image
	$att_url = wp_get_attachment_url( $id );
	return array( dirname( $att_url ) . '/' . $resized['file'], $resized['width'], $resized['height'], true );

}

add_filter('intermediate_image_sizes_advanced', 'ml_media_prevent_resize_on_upload');
function ml_media_prevent_resize_on_upload( $sizes ) {
	// Removing these defaults might cause problems, so we don't, though you could
	// probably set them to all be the same dimensions and rely on custom image sizes
	// for everything else
	return array(
		'thumbnail' => $sizes['thumbnail'],
		'medium' => $sizes['medium'],
		'large' => $sizes['large']
	);
}

以上是关于php WP仅在需要时才创建图像大小的主要内容,如果未能解决你的问题,请参考以下文章

php 将自定义WP图像大小添加到“媒体库设置”

UIView 转换仅在 UIView 是通过 Interface Builder 创建时才有效

是否仅在禁用 Javascript 时才下载 noscript 标记中的图像?

使用页面宽度调整大小更改图像

WooCommerce 插件模板覆盖

PHP 仅在描述可用时才拉出类别描述。