【发布时间】:2011-11-08 00:08:30
【问题描述】:
在我的主页上,我正在尝试输出每个帖子的第一张图片,并且我可以在我的 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)){ //Defines a default image
$first_img = "/images/default.jpg";
}
return $first_img;
}
然后我在循环中这样调用它:
<img src=”<?php catch_that_image(); ?>” />
这种方法的问题是,如果我在同一个帖子中放置一个画廊,它将无法工作。我很困惑,因为帖子的输出仍然呈现 img 标记,我的假设是 catch_that_image() 应该抓住那个标记?我的想法不正确吗?有没有更好的方法来处理这个问题?
【问题讨论】:
标签: image wordpress function loops