按需要生成图片缩略图(更新)

上回说,为了优化以WordPress为基础的外贸网站,特别是针对原系统针对每张图片都要生成缩略的,重新改写了image_downsize代码。但在实际需要中仍然需要修改两个点:

  • 外贸站,自然有产品目录,而post-thumbnail原图生成的缩略图,并不能达到产品目录显示效果。通常来说,post-thumbnail会针对此格式特别修图,故而产品目录thumbnail图片效果自然达不到预期效果。
  • 如果不能用post-thumbnail的系列缩略图,而是直接调用文章中的图片,或指定第一张图片作为产品目录封面,然后再针对其优化,那么做出来的产品目录效果自然会更好。

第一:指定文章内容中第一张图片为目录封面图

找出文章内容中的第一张图片,当然它也可以是缩略图的原图

//echo first image url
function cq_get_first_image() {
	global $post;
	$output = preg_match_all('/<img.+src=[\'"]([^\'"]+)[\'"].*>/i', $post->post_content, $matches);
	if(!empty($matches[1][0])){
	   return $matches[1][0];
    }	
}

上述代码,在寻找文章内容中的第一张图片还是不太准确,待更新。

第二:利用第一张图片按指定要求生成缩略图

为了方便,就直接使用系统默认的图片尺寸,和add_image_size增加的图片尺寸。

	if ( in_array( $size, array( 'thumbnail', 'medium', 'medium_large', 'large' ) ) ) {
		$width  = get_option( $size . '_size_w' );
		$height = get_option( $size . '_size_h' );
		$crop   = (bool) get_option( $size . '_crop' );

	} elseif ( isset( $_wp_additional_image_sizes ) && isset( $_wp_additional_image_sizes[ $size ] ) ) {
		$width = (int)$_wp_additional_image_sizes[ $size ]['width'];
		$height = (int)$_wp_additional_image_sizes[ $size ]['height'];
		$crop = isset( $_wp_additional_image_sizes[ $size ]['crop'] ) ? $_wp_additional_image_sizes[ $size ]['crop'] : false;

	} else { 
		return false;
	}	

获得尺寸后,就可以按指定尺寸来将第一张图片制成缩略图了。

$suffix = sprintf( "%dx%d", absint( $width ), absint( $height ) );	
	$first_img_url = cq_get_first_image();
	
	if ( $first_img_url ) {	
		$attach_id   = attachment_url_to_postid( $first_img_url );	
		$first_img_path = get_attached_file( $attach_id );
		
		$full_img_info = pathinfo( $first_img_url );
		$full_img_ext = '.'. $full_img_info['extension'];
		$full_img_path = $full_img_info['dirname'] .'/'. $full_img_info['filename'];		
		$size_img_url = $full_img_path .'-'. $suffix . $full_img_ext;
		
		$size_img_array = parse_url ( $size_img_url );
		$size_img_path = rtrim( ABSPATH, '/' ). $size_img_array['path'];		
	
		if ( file_exists($size_img_path) ){	
			$size_image_editor = wp_get_image_editor( $size_img_path );
			$size_img = $size_image_editor->get_size();
			$size_width = $size_img['width'];
			$size_height = $size_img['height'];
			
			$cq_image = array (
				'url' => $size_img_url,
				'width' => absint( $size_width ),
				'height' => absint( $size_height ),
				'mime-type' => get_post_mime_type( $attach_id ),
			);	
			return $cq_image;			
			
		} else {
			$image_editor = wp_get_image_editor( $first_img_path );
			if ( ! is_wp_error( $image_editor ) ) {
				$image_editor->resize( $width, $height, $crop );
				$new_img = $image_editor->get_size();
				$new_width = $new_img['width'];
				$new_height = $new_img['height'];

				$filename = $image_editor->generate_filename( $suffix );
				
				$image_editor->save( $filename );
				$new_filename = wp_basename( $filename );
				
				$img_url = wp_get_attachment_url( $attach_id );
				$img_url_basename = wp_basename( $img_url );
				$size_img_url = str_replace( $img_url_basename, $new_filename, $img_url );

				$cq_image = array (
					'url' => $size_img_url,
					'width' => $new_img['width'],
					'height' => $new_img['height'],
					'mime-type' => get_post_mime_type( $attach_id ),
				);	
				return $cq_image;
				
			} else {
				return false;
			}	
		}
		
	} 

第三:如果文章中没有图片,但又设置了post-thumbnail,那就调用已经有的缩略图或生成新缩略图

		$attach_id = get_post_thumbnail_id( get_the_ID() );
		$meta = wp_get_attachment_metadata( $attach_id );		
		
		if ( is_array( $meta ) && isset( $meta['sizes'][$size] ) ) {		
			$intermediate = image_get_intermediate_size( $attach_id, $size );
			$img_url = wp_get_attachment_url( $attach_id );
			$img_url_basename = wp_basename( $img_url );

			$img_url = str_replace( $img_url_basename, $intermediate['file'], $img_url );
			$result_width = $intermediate['width'];
			$result_height = $intermediate['height'];

			$cq_image = array (
				'url' => $img_url,
				'width' => $result_width,
				'height' => $result_height,
				'mime-type' => get_post_mime_type( $attach_id ),
			);
			return $cq_image;
		
		} else {			
			$attachment_path = get_attached_file( $attach_id );
			$image_editor = wp_get_image_editor( $attachment_path );

			if ( ! is_wp_error( $image_editor ) ) {
				$image_editor->resize( $width, $height, $crop );
				
				$new_img = $image_editor->get_size();
				$new_width = $new_img['width'];
				$new_height = $new_img['height'];

				$filename = $image_editor->generate_filename( $suffix );
				
				$image_editor->save( $filename );
				$new_filename = wp_basename( $filename );			
				
				$meta['sizes'][ $size ] = array(
					'file'      => $new_filename,
					'width'     => $new_width,
					'height'    => $new_height,
					'mime-type' => get_post_mime_type( $attach_id ),
				);
				wp_update_attachment_metadata( $attach_id, $meta );
				
				$img_url = wp_get_attachment_url( $attach_id );
				$img_url_basename = wp_basename( $img_url );
				$img_url = str_replace( $img_url_basename, $new_filename, $img_url );

				$cq_image = array (
					'url' => $img_url,
					'width' => $new_img['width'],
					'height' => $new_img['height'],
					'mime-type' => get_post_mime_type( $attach_id ),
				);			
				return $cq_image;
			
			} else {
				return false;
			}		
		}

第四:全部代码如下:

//echo first image url
function cq_get_first_image() {
	global $post;
	$output = preg_match_all('/<img.+src=[\'"]([^\'"]+)[\'"].*>/i', $post->post_content, $matches);
	if(!empty($matches[1][0])){
	   return $matches[1][0];
    }	
}

/*
 * Resize images dynamically using wp built in functions.
 * Update: Use WP_Image_Editor class instead of deprecated image_resize.
 * Updated by Colin
 * 
 * php 5.2+
 *
 * @param int $attach_id
 * @param string $img_url
 * @param array $size
 * @param bool $crop
 * @return array
 */
function cq_the_post_thumbnail( $size ) {
	
	// Declaration
	global $_wp_additional_image_sizes;		
	$width = $height = 0;
	$crop = false;
		
	if ( in_array( $size, array( 'thumbnail', 'medium', 'medium_large', 'large' ) ) ) {
		$width  = get_option( $size . '_size_w' );
		$height = get_option( $size . '_size_h' );
		$crop   = (bool) get_option( $size . '_crop' );

	} elseif ( isset( $_wp_additional_image_sizes ) && isset( $_wp_additional_image_sizes[ $size ] ) ) {
		$width = (int)$_wp_additional_image_sizes[ $size ]['width'];
		$height = (int)$_wp_additional_image_sizes[ $size ]['height'];
		$crop = isset( $_wp_additional_image_sizes[ $size ]['crop'] ) ? $_wp_additional_image_sizes[ $size ]['crop'] : false;

	} else { 
		return false;
	}	

	if ( 0 === absint( $width ) && 0 === absint( $height ) ) {
		return false;
	}
	
	$suffix = sprintf( "%dx%d", absint( $width ), absint( $height ) );	
	$first_img_url = cq_get_first_image();
	
	if ( $first_img_url ) {	
		$attach_id   = attachment_url_to_postid( $first_img_url );	
		$first_img_path = get_attached_file( $attach_id );
		
		$full_img_info = pathinfo( $first_img_url );
		$full_img_ext = '.'. $full_img_info['extension'];
		$full_img_path = $full_img_info['dirname'] .'/'. $full_img_info['filename'];		
		$size_img_url = $full_img_path .'-'. $suffix . $full_img_ext;
		
		$size_img_array = parse_url ( $size_img_url );
		$size_img_path = rtrim( ABSPATH, '/' ). $size_img_array['path'];		
	
		if ( file_exists($size_img_path) ){	
			$size_image_editor = wp_get_image_editor( $size_img_path );
			$size_img = $size_image_editor->get_size();
			$size_width = $size_img['width'];
			$size_height = $size_img['height'];
			
			$cq_image = array (
				'url' => $size_img_url,
				'width' => absint( $size_width ),
				'height' => absint( $size_height ),
				'mime-type' => get_post_mime_type( $attach_id ),
			);	
			return $cq_image;			
			
		} else {
			$image_editor = wp_get_image_editor( $first_img_path );
			if ( ! is_wp_error( $image_editor ) ) {
				$image_editor->resize( $width, $height, $crop );
				$new_img = $image_editor->get_size();
				$new_width = $new_img['width'];
				$new_height = $new_img['height'];

				$filename = $image_editor->generate_filename( $suffix );
				
				$image_editor->save( $filename );
				$new_filename = wp_basename( $filename );
				
				$img_url = wp_get_attachment_url( $attach_id );
				$img_url_basename = wp_basename( $img_url );
				$size_img_url = str_replace( $img_url_basename, $new_filename, $img_url );

				$cq_image = array (
					'url' => $size_img_url,
					'width' => $new_img['width'],
					'height' => $new_img['height'],
					'mime-type' => get_post_mime_type( $attach_id ),
				);	
				return $cq_image;
				
			} else {
				return false;
			}	
		}
		
	} elseif ( get_the_ID() ) {		
		$attach_id = get_post_thumbnail_id( get_the_ID() );
		$meta = wp_get_attachment_metadata( $attach_id );		
		
		if ( is_array( $meta ) && isset( $meta['sizes'][$size] ) ) {		
			$intermediate = image_get_intermediate_size( $attach_id, $size );
			$img_url = wp_get_attachment_url( $attach_id );
			$img_url_basename = wp_basename( $img_url );

			$img_url = str_replace( $img_url_basename, $intermediate['file'], $img_url );
			$result_width = $intermediate['width'];
			$result_height = $intermediate['height'];

			$cq_image = array (
				'url' => $img_url,
				'width' => $result_width,
				'height' => $result_height,
				'mime-type' => get_post_mime_type( $attach_id ),
			);
			return $cq_image;
		
		} else {			
			$attachment_path = get_attached_file( $attach_id );
			$image_editor = wp_get_image_editor( $attachment_path );

			if ( ! is_wp_error( $image_editor ) ) {
				$image_editor->resize( $width, $height, $crop );
				
				$new_img = $image_editor->get_size();
				$new_width = $new_img['width'];
				$new_height = $new_img['height'];

				$filename = $image_editor->generate_filename( $suffix );
				
				$image_editor->save( $filename );
				$new_filename = wp_basename( $filename );			
				
				$meta['sizes'][ $size ] = array(
					'file'      => $new_filename,
					'width'     => $new_width,
					'height'    => $new_height,
					'mime-type' => get_post_mime_type( $attach_id ),
				);
				wp_update_attachment_metadata( $attach_id, $meta );
				
				$img_url = wp_get_attachment_url( $attach_id );
				$img_url_basename = wp_basename( $img_url );
				$img_url = str_replace( $img_url_basename, $new_filename, $img_url );

				$cq_image = array (
					'url' => $img_url,
					'width' => $new_img['width'],
					'height' => $new_img['height'],
					'mime-type' => get_post_mime_type( $attach_id ),
				);			
				return $cq_image;
			
			} else {
				return false;
			}		
		}
	} 
}

第五:使用方法

因为上述代码生成的一个数组,所以要将数组值抽出来使用,此代码需要更新以增加效率。

<?php if ( $image = cq_the_post_thumbnail( 'medium' ) ) { ?>
<figure>
<a href="https://colinqi.com/goto/Jmx0Oz9waHAgdGhlX3Blcm1hbGluaygpOyA/Jmd0Ow==" rel="nofollow" target="_blank" title="<?php the_title_attribute(); ?>">
	<img src="<?php echo $image['url']; ?>" width="<?php echo $image['width']; ?>" height="<?php echo $image['height']; ?>" alt="<?php the_title_attribute(); ?>" />
</a>
</figure>
<?php } ?>

 

Previous/Next

Say Something!

Leave a Reply