WordPress 纯代码实现自动缩略图功能

2023-11-24 1 1,049

前言:

WordPress 默认的特征图像匹配系统设置有剪切功能,但每次传输还是有点困难。我们通常直接从网络上复制文章。默认情况下,WordPress 不会为我们剪切它们。如果此时使用第一张图片作为缩略图,将大大增加页面大小并降低打开速度,因此今天我推荐使用 timthumb 工具类来生成缩略图。你可以在文章末尾下载这个类文件。

WordPress 纯代码实现自动缩略图功能

1.复制下面代码到主题目录:functions.php

// https://www.huizhanii.com
//缩略图开始
function post_thumbnail( $width = 220,$height = 150 ){
    global $post;
    if( has_post_thumbnail() ){    //如果有缩略图,则显示缩略图
        $timthumb_src = wp_get_attachment_image_src(get_post_thumbnail_id($post->ID),'full');
        $post_timthumb = '<img src="'.get_bloginfo("template_url").'/timthumb.php?src='.$timthumb_src[0].'&amp;h='.$height.'&amp;w='.$width.'&amp;zc=1" alt="'.$post->post_title.'" class="thumb" style="display: inline;" />';
        echo $post_timthumb;
    } else {
        $post_timthumb = '';
        ob_start();
        ob_end_clean();
        $output = preg_match('/<img.+src=[\'"]([^\'"]+)[\'"].*>/i', $post->post_content, $index_matches);    //获取日志中第一张图片
        $first_img_src = get_bloginfo('wpurl').$index_matches [1];    //获取该图片 src
        if( !empty($first_img_src) ){    //如果日志中有图片
            $path_parts = pathinfo($first_img_src);    //获取图片 src 信息
            $first_img_name = $path_parts["basename"];    //获取图片名
            $first_img_pic = get_bloginfo('wpurl'). '/cache/'.$first_img_name;    //文件所在地址
            $first_img_file = ABSPATH. 'cache/'.$first_img_name;    //保存地址
            $expired = 604800;    //过期时间
            if ( !is_file($first_img_file) || (time() - filemtime($first_img_file)) > $expired ){
                copy($first_img_src, $first_img_file);    //远程获取图片保存于本地
                $post_timthumb = '<img src="'.$first_img_src.'" alt="'.$post->post_title.'" class="focus" style="display: inline;" />';    //保存时用原图显示
            }
            $post_timthumb = '<img src="'.get_bloginfo("template_url").'/timthumb.php?src='.$first_img_pic.'&amp;h='.$height.'&amp;w='.$width.'&amp;zc=1" alt="'.$post->post_title.'" class="focus" style="display: inline;" />';
        } else {    //如果日志中没有图片,则显示默认
            $post_timthumb = '<img src="'.get_bloginfo("template_url").'/images/default_thumb.gif" alt="'.$post->post_title.'"  class="focus" style="display: inline;" />';
        }
        echo $post_timthumb;
    }
}
//缩略图结束

然后在网站项目根目录下新创建一个 cache 文件夹,并且给予 777 权限。

最后在模板里面调用:

// https://www.huizhanii.com
<span class="pln">post_thumbnail</span><span class="pun">(</span><span class="lit">243</span><span class="pun">,</span><span class="lit">182</span><span class="pun">);</span>

转载请注明:汇站网 » WordPress 纯代码实现自动缩略图功能

收藏 (1)

微信支付 微信扫一扫

支付宝支付 支付宝扫一扫

点赞 (0)

站长资源下载中心-找源码上汇站

常见问题
  • 如果付款后没有弹出下载页面,多刷新几下,有问题联系客服!
查看详情
  • 本站所有资源版权均属于原作者所有,这里所提供资源均只能用于参考学习用,请勿直接商用。若由于商用引起版权纠纷,一切责任均由使用者承担。
查看详情

相关文章

联系官方客服

为您解决烦忧 - 24小时在线 专业服务