调用WordPress文章中第一张图片作为缩略图

以前我们在选择WordPress图文主题的比较少,如今是比较多见的。所以,一般主题中都自带可以自定义缩略图,或者是自动获取第一张文章中的图片作为缩略图。但是也有的时候我们可能需要调用文章中的图片作为缩略图。比如在企业网站模板设置的时候需要手动设置这样的功能。

第一、Functions.php代码部分

function catch_that_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)) {
$first_img = "/path/to/default.png";
}
return $first_img;
}

第二、调出部分

if ( get_the_post_thumbnail($post_id) != '' ) {

echo '<a href="'; the_permalink(); echo '" class="thumbnail-wrapper">';
the_post_thumbnail();
echo '</a>';

} else {

echo '<a href="'; the_permalink(); echo '" class="thumbnail-wrapper">';
echo '<img src="';
echo catch_that_image();
echo '" alt="" />';
echo '</a>';

}

根据需要调用在模板输入文章的页面中。

本文出处:老蒋部落 » 调用WordPress文章中第一张图片作为缩略图 | 欢迎分享( 公众号:老蒋朋友圈 )

公众号 「老蒋朋友圈」获取站长新知 / 加QQ群 【1012423279】获取商家优惠推送