我们在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 = "/images/default.jpg"; //默认图片地址需自己设置
- }
- return $first_img;
- }
在需要调用到文章第一张的地方调用该函数:
- <?php echo catch_that_image() ?>