为wordpress文章添加缩略图
Wordpress在网站首页以文章摘要加缩略图形式显示文章列表非常常见,那么如何无插件实现该功能,让wordpress自动抓取文章缩略图。缩略图可以来自featured图片,也可以来自文章内图片,还可以在前两者均无时随机显示一些图片,接下来就介绍如何修改主题模板实现该功能。
第一步:添加功能函数
找到使用的主题模板的functions.php文件在<?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('//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-20,jpg格式
第二步:指定位置调用函数
找到index.php文件即首页文件,找到the_content();或相似的代码在它之前添加如下代码:
第三步:添加缩略图样式CSS代码:
具体样式需要根据网站内容调整,如下作为示例
.home-thumb{margin:5px 15px 5px 5px;width:140px;height:100px;border:3px solid #eee;float:left;overflow:hidden;} .home-thumb img{max-height:186px;max-width:186px}