自动为WordPress设置内容首图为缩略图方法

来自:互联网
时间:2019-09-01
阅读:

有些网站的主题需要用到缩略图,但是如果每篇文章用手工设置缩略图太繁琐了。我们可以直接使用自动缩略图的方式,比如直接获取内容中的第一张图作为缩略图。在这篇文章中,麦子就介绍我们如何用脚本实现WordPress自动内容首图作为缩略图。

第一、代码脚本

function catch_that_image() {
global $post, $posts;
ob_start();
ob_end_clean();
preg_match('/<imgs[^<>]*?src=['"]([^'"<>]+?)['"][^<>]*?>/i', $post->post_content, $matche);
if($matche[1])
return $matche[1];
//否则取默认图片
return 'default.gif';
}

将代码添加到当前主题functions.php中。

第二、调用方式

<img src="<?php echo catch_that_image(); ?>" alt="<?php the_title(); ?>" title="<?php the_title(); ?>"  width="200px" height="200px" />

然后在缩略图的位置换成调用代码,这里数字代表尺寸,我们可以根据需要修改。

返回顶部
顶部