不乱于心,不困于情。
不畏将来,不念过往。如此,安好。

调用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>’;

}

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

赞(0) 打赏
未经允许不得转载:seo优化_前端开发_渗透技术 » 调用WordPress文章中第一张图片作为缩略图

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

微信扫一扫打赏