WordPress教程

WordPress 可用的缩略图函数

阿里云

记录一个 wordpress 获取文章中的图片作为缩略图,并缓存的函数,方便以后应用。

  1. <?php
  2. if( !defined( 'THEME_THUMBNAIL_PATH' ) ) define( 'THEME_THUMBNAIL_PATH', '/cache/theme-thumbnail' ); //存储目录
  3. function biji_build_empty_index( $path ){ //生成空白首页
  4.     $index = $path . '/index.php';
  5.     if( is_file( $index ) ) return;
  6.     wp_mkdir_p( $path );
  7.     file_put_contents( $index, "<?php\n// Silence is golden.\n" );
  8. }
  9. function biji_crop_thumbnail( $url, $width, $height = null ){ //裁剪图片
  10.     $width = (int) $width;
  11.     $height = empty( $height ) ? $width : (int) $height;
  12.     $hash = md5( $url );
  13.     $file_path = constant( 'WP_CONTENT_DIR' ) . constant( 'THEME_THUMBNAIL_PATH' ) . "/$hash-$width-$height.jpg";
  14.     $file_url = content_url( constant( 'THEME_THUMBNAIL_PATH' ) . "/$hash-$width-$height.jpg" );
  15.     if( is_file( $file_path ) ) return $file_url;
  16.     $editor = wp_get_image_editor( $url );
  17.     if( is_wp_error( $editor ) ) return $url;
  18.     $size = $editor->get_size();
  19.     $dims = image_resize_dimensions( $size['width'], $size['height'], $width, $height, true );
  20.     //if( !$dims ) return $url;
  21.     $cmp = min( $size['width'] / $width, $size['height'] / $height );
  22.     if( is_wp_error( $editor->crop( $dims[2], $dims[3], $width * $cmp, $height * $cmp, $width, $height ) ) ) return $url;
  23.     biji_build_empty_index( constant( 'WP_CONTENT_DIR' ) . constant( 'THEME_THUMBNAIL_PATH' ) );
  24.     return is_wp_error( $editor->save( $file_path, 'image/jpg' ) ) ? $url : $file_url;
  25. }
  26. //缩略图获取post_thumbnail
  27. function post_thumbnail($width = 275,$height = 170 )
  28. {
  29.     global $post;
  30.     //如果有特色图片则取特色图片
  31.     if( has_post_thumbnail( $post->ID ) ){
  32.         $thumbnail_ID = get_post_thumbnail_id( $post->ID );
  33.         $thumbnailsrc = wp_get_attachment_image_src( $thumbnail_ID, 'full' );
  34.         return biji_crop_thumbnail($thumbnailsrc[0],$width,$height);
  35.     } else {
  36.         $content = $post->post_content;
  37.         preg_match_all('/<img.*?(?: |\\t|\\r|\\n)?src=[\'"]?(.+?)[\'"]?(?:(?: |\\t|\\r|\\n)+.*?)? >/sim', $content, $strResult, PREG_PATTERN_ORDER);
  38.         if(count($strResult[1]) > 0) return biji_crop_thumbnail($strResult[1][0],$width,$height);
  39.         else{
  40.             return false;
  41.         }
  42.     }
  43. }
  44. ?>
也想出现在这里?联系我们
创客主机

在调用时,可以这样调用:

  1. <?php if (post_thumbnail(110, 110)){ ?>
  2.   <img src="<?php echo post_thumbnail(110, 110); ?>" srcset="<?php echo post_thumbnail(220, 220); ?> 2x"/>
  3. <?php }else{
  4.    echo '<i class="icon-file-text2"></i>';
  5.   }?>

WordPress 可用的缩略图函数

已有 174 人购买
查看演示升级 VIP立刻购买

收藏
(0)

发表回复

热销模板

Ashade - 作品展示摄影相册WordPress汉化主题
LensNews

本站承接 WordPress / PbootCMS / DedeCMS 等
系统建站、仿站、开发、定制等业务!