我们的博客网站中的每一篇文章或多或少都会有一些图片,而近期发现占用空间严重,不用问,大多数是图片占用内存的问题,仔细查看,果然如此,查看到uploads文件内图片文件被切成多种尺寸的缩微图,一张图就有几个尺寸的文件,占用很大内存,所以这里详细打说下我优化的方法。

上图为文章页面源码,想给图片添加alt 和 title 属性,在 functions.php 添加如下代码:
/**
*自动添加图片 alt 和 title 属性|boke112 导航
*https://boke112.com/2912.html
*/
function image_alttitle( $imgalttitle ){
global $post;
$category = get_the_category();
$flname=$category[0]->cat_name;
$btitle = get_bloginfo();
$imgtitle = $post->post_title;
$imgUrl = "<img\s[^>]*src=(\"??)([^\" >]*?)\\1[^>]*>";
if(preg_match_all("/$imgUrl/siU",$imgalttitle,$matches,PREG_SET_ORDER)){
if( !empty($matches) ){
for ($i=0; $i < count($matches); $i++){
$tag = $url = $matches[$i][0];
$j=$i+1;
$judge = '/title=/';
preg_match($judge,$tag,$match,PREG_OFFSET_CAPTURE);
if( count($match) < 1 )
$altURL = ' alt="'.$imgtitle.' '.$flname.' 第'.$j.'张" title="'.$imgtitle.' '.$flname.' 第'.$j.'张-'.$btitle.'" ';
$url = rtrim($url,'>');
$url .= $altURL.'>';
$imgalttitle = str_replace($tag,$url,$imgalttitle);
}
}
}
return $imgalttitle;
}
add_filter( 'the_content','image_alttitle');
禁止srcset、sizes属性,禁止 thumbnail 功能, 本人使用的是 TWENTY TWELVE 主题,在主题
functions.php 文件中查找:
// This theme uses a custom image size for featured images, displayed on "standard" posts.
//add_theme_support( 'post-thumbnails' );
//set_post_thumbnail_size( 624, 9999 ); // Unlimited height, soft crop
注释掉,去掉 thumbnail 繁琐的剪切功能
这样发布文章只显示唯一图片路径,而且均有 alt 和 title 属性 代码。
安装图片压缩插件:Compress JPEG & PNG images