记录一些常用的函数和瞎折腾的过程……

wordpress函数之:缓存缩略图

提醒:本文最后更新于 2353 天前,文中所描述的信息可能已发生改变,请谨慎使用。

有时候在调用文章中的图片作为缩略图时,图片过大,影响加载速度,此时以将原图裁剪,缓存在本地,方便调用,结合前面讲到的自动缩略图的函数功能即可实现。

首先定义缓存函数:

<?php// 缩略图缓存
if( !defined( 'THEME_THUMBNAIL_PATH' ) ) define( 'THEME_THUMBNAIL_PATH', '/cache/theme-thumbnail' );
function Bing_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 Bing_crop_thumbnail( $url, $width, $height = null ){
    $width = (int) $width;
    $height = empty( $height ) ? $width : (int) $height;
    $hash = md5( $url );
    $file_path = WP_CONTENT_DIR . THEME_THUMBNAIL_PATH . "/$hash-$width-$height.jpg";
    $file_url = content_url( 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();
    if( !$dims = image_resize_dimensions( $size['width'], $size['height'], $width, $height, true ) )
        return $url;
    $cmp_x = $size['width'] / $width;
    $cmp_y = $size['height'] / $height;
    $cmp = min( $cmp_x, $cmp_y );
    $min_width = round( $width * $cmp );
    $min_height = round( $height * $cmp );
    $crop = $editor->crop( $dims[2], $dims[3], $min_width, $min_height, $width, $height );
    if( is_wp_error( $crop ) )
        return $url;
    Bing_build_empty_index( WP_CONTENT_DIR . THEME_THUMBNAIL_PATH );
    $save = $editor->save( $file_path, 'image/jpg' );
    return is_wp_error( $save ) ? $url : $file_url;
}
function Bing_add_support_post_thumbnails(){
    add_theme_support( 'post-thumbnails' );
}
add_action( 'after_setup_theme', 'Bing_add_support_post_thumbnails' );

然后获取文章中的缩略图:

// 获取文章第一张图片
function get_content_first_image($content){
    if ( $content === false ) $content = get_the_content();
    preg_match_all('|<img.*?src=[\'"](.*?)[\'"].*?>|i', $content, $images);
    if($images){
        return $images[1][0];
    }else{
        return false;
    }
}

最后将获取的缩略图缓存起来,可以在文章列表中调用了:

<img src="<?php echo esc_url( Bing_crop_thumbnail( get_content_first_image(get_the_content()),110,110) ) ; ?>"/>