记录一个 WordPress 获取文章中的图片作为缩略图,并缓存的函数,方便以后应用。
- <?php
- if( !defined( 'THEME_THUMBNAIL_PATH' ) ) define( 'THEME_THUMBNAIL_PATH', '/cache/theme-thumbnail' ); //存储目录
- function biji_build_empty_index( $path ){ //生成空白首页
- $index = $path . '/index.php';
- if( is_file( $index ) ) return;
- wp_mkdir_p( $path );
- file_put_contents( $index, "<?php\n// Silence is golden.\n" );
- }
- function biji_crop_thumbnail( $url, $width, $height = null ){ //裁剪图片
- $width = (int) $width;
- $height = empty( $height ) ? $width : (int) $height;
- $hash = md5( $url );
- $file_path = constant( 'WP_CONTENT_DIR' ) . constant( 'THEME_THUMBNAIL_PATH' ) . "/$hash-$width-$height.jpg";
- $file_url = content_url( constant( 'THEME_THUMBNAIL_PATH' ) . "/$hash-$width-$height.jpg" );
- if( is_file( $file_path ) ) return $file_url;
- $editor = wp_get_image_editor( $url );
- if( is_wp_error( $editor ) ) return $url;
- $size = $editor->get_size();
- $dims = image_resize_dimensions( $size['width'], $size['height'], $width, $height, true );
- //if( !$dims ) return $url;
- $cmp = min( $size['width'] / $width, $size['height'] / $height );
- if( is_wp_error( $editor->crop( $dims[2], $dims[3], $width * $cmp, $height * $cmp, $width, $height ) ) ) return $url;
- biji_build_empty_index( constant( 'WP_CONTENT_DIR' ) . constant( 'THEME_THUMBNAIL_PATH' ) );
- return is_wp_error( $editor->save( $file_path, 'image/jpg' ) ) ? $url : $file_url;
- }
- //缩略图获取post_thumbnail
- function post_thumbnail($width = 275,$height = 170 )
- {
- global $post;
- //如果有特色图片则取特色图片
- if( has_post_thumbnail( $post->ID ) ){
- $thumbnail_ID = get_post_thumbnail_id( $post->ID );
- $thumbnailsrc = wp_get_attachment_image_src( $thumbnail_ID, 'full' );
- return biji_crop_thumbnail($thumbnailsrc[0],$width,$height);
- } else {
- $content = $post->post_content;
- preg_match_all('/<img.*?(?: |\\t|\\r|\\n)?src=[\'"]?(.+?)[\'"]?(?:(?: |\\t|\\r|\\n)+.*?)? >/sim', $content, $strResult, PREG_PATTERN_ORDER);
- if(count($strResult[1]) > 0) return biji_crop_thumbnail($strResult[1][0],$width,$height);
- else{
- return false;
- }
- }
- }
- ?>
在调用时,可以这样调用:
- <?php if (post_thumbnail(110, 110)){ ?>
- <img src="<?php echo post_thumbnail(110, 110); ?>" srcset="<?php echo post_thumbnail(220, 220); ?> 2x"/>
- <?php }else{
- echo '<i class="icon-file-text2"></i>';
- }?>