最近弄了一个瀑布流的主题,但要显示图片必须设在特色图片,不然首页就不显示,于是想怎么把文章中的图片自动设置为特色图片,免去每次都要设置的麻烦,只需要在functions.php和index.php中添加一也代码就可以实现。
1、打开functions.php将下面代码加入到文件开头
[cc lang=”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 = “/images/default.jpg”;}return $first_img;}
[/cc]
2、在index.php文件的内容代码前或后添加以下代码
在当前主题模板的index.php文件的内容代码前或后添加以下代码
<?php echo catch_that_image() ?>