Duke Yin's Technology database

获取特色图像如果为空则获取第一张图

WordPress主题制作过程中经常要获得特色图像的URL以用来裁切或者呈现,但是有时候日志中不包含特色图像,比较好的方法是建立一个方程获得文章内容的第一张特色图像。

获得第一张图的方程在网上有很多,但是缺点是每次必须要用if去判断,有特色图像如何,没有特色图像如何。

所以为何我们不将判断的工作直接放进方程里,让这个方程去获取特色图像,没有的话就调用第一张图呢?

/** Get First image */
function get_first_image() {
global $post, $posts;
$featured_img_url = get_the_post_thumbnail_url(get_the_ID(),'full');
if(empty($featured_img_url)){
$first_img = '';
ob_start();
ob_end_clean();
if($output = preg_match_all('//i', $post->post_content, $matches)){
$first_img = $matches [1] [0];
}else{
$first_img = '';
};
}else{
$first_img= $featured_img_url;
}
return $first_img;
}

把如上这组方程放入functions.php,然后在想调用的地方直接用 get_first_image() 就能直接输出特色图像的URL,如果没有特色图像,第一张图的URL将被输出。

 

例如

$first_img = get_first_image(); // 将特色图或第一张图存进变量
$title = get_the_title(); // 获得文章或页面标题
if ( !empty($first_img) ) { // 如果特色图或第一张图不为空
$blogthumburl = aq_resize( $first_img, 1170, 500, true, true, true ); //进行裁切并存入变量
echo '
'; //继续输出
}else{//如果特色图和第一张图都为空,则执行下面的内容
}

有些人会在get_first_image()这个方程中增加一个判断,当全部为空时候输出一张默认图像,我认为是不恰当的,因为有时候页面的呈现上只需要文字,太多的默认图像,显得非常呆板。

另外,这个方程有个缺点,就是当文章中没有<img>标签,插入的是Wordpress相册的话,是无法获取相册的第一张图的,有待改进。

发布评论

评论

标注 * 的为必填项。