在制作WordPress主题时,想要实现自动调用文章中的第一张图片作为缩略图,于是找到了一个自动调用文章第一张图片的方法。方法非常简单,建议为调用代码添加<div>
等,以方便对其样式(如:大小)进行自定义设置。
将以下代码添加到你的主题模板的function.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)){ //Defines a default image $first_img = "这里添加默认图片的路径,文章中没有图片时显示"; } return $first_img; }
把以下代码添加到你想要显示图片的位置,即可实现自动调用文章中第一张图片
<img src="<?php%20echo%20catch_that_image()%20?>" alt="" />
评论前必须登录!
注册