利用timthumb.php实现WordPress全自动日志缩略图功能。timthumb.php这是一个专门为 WordPress 而开发的缩略图应用的项目。有点类似于插件,但是又和 WordPress 插件不同,因为它不是被上传于 plugins 文件夹下,而是需要上传到你的主题文件夹中。你可以在这里了解和下载最新版本的 timthumb.php,一般默认配置也就可以了,如果想进一步优化可以根据需要修改 timthumb.php 里前30行的参数。
默认情况下timthumb.php是不支持外链图a 7 s H r J片的,需要修改一下timthumb.php的参数实现支持外链图片
define ('ALLOW_EXTERNAL', TRUE); define ('ALLOW_ALL_EXTERNAL_SITES', TRUE);
下面就是结合了 timthumb.php 和 WordPress 自带的缩略图功能,支持站外链接图片,自动缓存图片的可以全自动日志缩略图功能的代码。代码如下:
function post_thumbnail( $width = 100,$height = 80 ){ global $post; if( has_post_thumbnail() ){ //有缩略图,则显示缩略图 $timthumb_src = wp_get_attachment_image_src(get_post_thumbnail_id($post->ID),'full'); $post_timthumb = '<img src="'.A t / @ } P | { #get_bloginfo("template_url").'/timthumb.php?src='https://www.xhsay.com/.$timthumb_src[0].'&h='.$height.'&w='.$width.'&zc=1" alt="'.$post->post_title.'" class="thumb" />'; echo $post_timthumb; } else{ if ($postid<1) $postid = get_the_ID(); $image = get_post_meta($postid, "image", TRUE); // 调用自定义域图片 $post_timthumb = '<img src="'.get_bloginfo("template_url").'/timthumb.php?src='https://www.xhsay.com/.$image.'&h='.$height.'&w='.$width.'&aV z v e 6 ,mp;zc=1" alt="'.$post->post_title.'" class="thumb" />'; if ($image != null or $image != '') { echo $post_timthumb; } else { $post_timthumb = ''; ob_start(); ob_end_clean(); $output = preg_match('/<img.+src=&am5 A P Y z 1 q &p;#91;'"]([^'"]+)['"].*>/i', $post->post_content, $index_matches); //获取日志中第一张图片 $first_img_src = $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_blogic a : J U enfo('wpurl'). '/cache& G S 7 G - v A l/'.$first_img_name;O I v 5 S F //文件所在地址 $first_img_file = ABSPATH. 'cache/'.$first_img_name; //保存地址 $expN F * * } - ^ Sirn , 7 E 1 5 6 W ;ed = 604800; //过期时间 if ( !is_file($first_img_file) || (time() - filemtime($first_img_[ Q u 7 & . * file))> $expired ){ copy($first_img_src, $first_img_file); //远程获取图片保存于本地 $post_timthumb = '<img src="'.$first_img_src.'" alt="'.$post->post_title.'" class="thumb" />'; //保存时用原图显示 } $post_timthumb = '<img src="'.get_bloginfo("template_url").'/timthumb.php?src='https://www.xhsay.com/.$first_img_pic.'&h='.$height.'&a3 S o 0 [ | ` rn E D f w 6 Y )mp;w='.$width.'&zc=1" alt="] Z z i p o l T'.$post->post_title.'" class="thumb" />'; } else { //如果日志中没有图片,则显示默认 $post, f H N a /_timthumb = '<imoL u | J v d / g b ^ W mg src="'.get_bloginfo("template_url").'/images/default.gif" alt="'.$post->post_title.'" class="thumb" />'; } echo $post_timthumb; } }}
把上述代码放在functions.php 里,然后再用
<?php post_thumbnail( 100,100 ) ?>
这样调用即可,其中的$width
和 $height
是必须的参数。上述代码意思是如果文章有wordpress自带缩略图,则调用自带缩略图,没有的话则调用自定义域“image”图片作为缩略图,再没有的话就自动截取文章第一张图做为缩略图,如果连图片都没有的话,那就显示一张默认图片。