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


function catch_that_image() {
global $post, $posts;
$first_img = '';<br> ob_start();<br> ob_end_clean();<br> $output = preg_match_all('/<img.+src=\'"[\'"].*>/i', $post->post_content, $matches);
$first_img = $matches1;
if(empty($first_img)) {<br> $first_img = "/path/to/default.png?imageMogr2/format/webp";
}
return $first_img;
}

第二、调出部分

if ( get_the_post_thumbnail($post_id) != '' ) {
echo '';
the_post_thumbnail();
echo '
';
} else {
echo '';
echo ' echo catch_that_image();
echo '" alt="" />';
echo '
';
}

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


  1. \'"

扫描二维码,在手机上阅读!