我试图在主博客页面上检索并显示帖子的第一张图片... 但唯一出现的是该图像的链接,而不是图像本身! 不确定有什么问题!...
这是用于尝试此操作的代码。
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;
}
感谢您提供任何帮助...以下是指向问题页面的链接:http://wordpress-dev.designer17.com/blog/(底部帖子)
答案 0 :(得分:2)
获得图片网址后,只要您计划直接从该功能显示图片,您只需返回带有src中网址的img html标记:
return '<img src="' . $first_img . '">';
答案 1 :(得分:0)
我使用这个获取第一张图片的解决方案,它在我的本地主机上完美运行但是当我将它复制到我的实时主机时,它失败并出现下标错误。因此,我将其修改为以下工作。
function catch_that_image() {
global $post, $posts;
$first_img = '';
ob_start();
ob_end_clean();
if (preg_match_all('/<img.+src=[\'"]([^\'"]+)[\'"].*>/i', $post->post_content, $matches) == 0) {
//Define a default image
$first_img = get_stylesheet_directory_uri() . "/images/default-image.jpg";
} else {
$first_img = $matches [1] [0];
}
return $first_img;
}