wordpress缩略图调用,没有缩略图则提前第一张,否则显示随机图片
wordpress自带缩略图标签为:
<?php the_post_thumbnail(); ?>
但是这仅支持设置过特色图像的文章,如果文章没有设置过特色图像,或者文章中根本不存在图片的情况怎么处理呢?
第一步:
修改主题目录下的functions.php文件,插入
// 自动缩略图
function catch_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, 10);
echo 'http://img.el0310.com/files/images/thumbnail'.$random.'.jpg';
}
return $first_img;
}第二步:
在需要显示缩略图的地方插入
<?php if (has_post_thumbnail()) { the_post_thumbnail('thumbnail', array('alt' => get_the_title()));
} else { ?>
<img src="<?php echo catch_image() ?>!200X150" alt="<?php the_title(); ?>" />
<?php } ?>如果页面模板中经常需要插入缩略图,觉得上面第二步的代码太长。
可以在主题目录下新建 inc目录,在此目录下增加thumbnail.php.内容为:
<?php if (has_post_thumbnail()) { the_post_thumbnail('thumbnail', array('alt' => get_the_title()));
} else { ?>
<img src="<?php echo catch_image() ?>!200X150" alt="<?php the_title(); ?>" />
<?php } ?>然后,在需要插入缩略图的地方调用此文件即可,调用方法为:
<?php get_template_part( 'inc/thumbnail' ); ?>
<< 上一篇
下一篇 >>