WordPress主题Sahifa添加自动缩略图功能
前段时间发布了一篇博文《WordPress自适应博客主题Sahifa介绍与中英文多版本下载》介绍了一款优质wordpress主题sahifa,有读者使用后询问我如何添加首页自动截取文章图片作为缩略图,接下来我简单介绍一下方法。
打开你主题function.php函数模板,添加如下代码
if ( function_exists('add_theme_support') ) add_theme_support('post-thumbnails'); function catch_first_image() { global $post, $posts; $first_img = ''; ob_start(); ob_end_clean(); $output = preg_match_all('/<img.+src=[\'"]([^\'"]+)[\'"].*>/i', $post->post_content, $matches); $first_img = $matches [1] [0]; if(empty($first_img)){ $random = mt_rand(1, 20); echo get_bloginfo ( 'stylesheet_directory' ); echo '/images/random/tb'.$random.'.jpg'; } return $first_img; }
这部分代码功能是首先正则表达式法截取文章内图片,如果没有则显示随机图片(需要在主题images目录下新建random文件夹,里面放上20张随机图片,命名为tb1.jpg,tb2.jpg...tb20.jpg,图片分辨率140x100)。
然后找到loop.php,定位
xxx
,把xxx原内容替换为
ID, 'thumbnail', true) ) : ?> ID, 'thumbnail', true); ?>![]()
![]()
这样,首页文章循环就会自动获取文章缩略图,如果无特色图片就截取第一张图片,如果没有图片则显示随机图片。