2个获取WordPress内容第一张图作为缩略图的方法

目前,我们在使用WordPress程序的时候,较多的会用到图文排版自媒体主题,但是这个有一个特点,如果有些主题内容中我们没有设定缩略图就显得空空的,其实这个时候我们也可以用自动获取内容中的第一张图作为缩略图。这里,麦子整理2个方法,如果我们有需要的可以设置。

1、获取内容第一张图(没有设置默认图)

这个方法有个缺点,万一内容也没有图,那就无法获取到。

function wp_content_image($content){
    if ( $content === false ) $content = get_the_content();
    preg_match_all('|<img.*?src=[\'"](.*?)[\'"].*?>|i', $content, $images);
    if($images){      
        return $images[1][0];
    }else{
        return false;
    }
}

如果需要调用:

<img src="<?php echo wp_content_image(get_the_content()); ?>">

我们还需要修改调出的位置。

2、获取内容第一张图(设置默认图)

上面的缺点就是没有默认图,我们要设置一个默认图。

function wp_content_image() {
	global $post;
	$first_img = '';
	ob_start();
	ob_end_clean();
	$output = preg_match_all('/<img*.+src=[\'"]([^\'"]+)[\'"].*>/iU', wp_unslash($post->post_content), $matches);
	if(empty($output)){ 
		$first_img = "默认图URL";
	}else {
		$first_img = $matches [1][0];
	}
	return $first_img;
}

调用:

<?php echo wp_content_image(); ?>

如果有需要的话我们尽可能用第二个方法。

4.7/5 - (8 votes)
© 版权声明
THE END
喜欢就支持一下吧
点赞10 分享