调用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>
';
}
根据需要调用在模板输入文章的页面中。
声明:本文内容由网友自发贡献,本站不承担相应法律责任。对本内容有异议或投诉,请联系2913721942#qq.com核实处理,我们将尽快回复您,谢谢合作!
若转载请注明出处: 调用WordPress文章中第一张图片作为缩略图
本文地址: https://pptw.com/jishu/666600.html