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)){ //Defines a default image
$first_img = "/images/default.jpg";
}
return $first_img;
}
然后我在循环中调用它,如下所示
<img src=”<?php catch_that_image(); ?>” />
:方法是,如果我在同一篇文章中放置画廊,它将不起作用。我很困惑,因为帖子的输出仍然呈现 img 标记,而我的假设是 catch_that_image() 应该捕获该标记?难道我的想法不正确吗?有更好的方法来处理这个问题吗?
On my homepage, I'm trying to output the first image of each post, and I'm able to successfully do that using this code in my 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;
}
and then I call it in my loop like this:
<img src=”<?php catch_that_image(); ?>” />
The problem with this method is that it won't work if I place a gallery in that same post. I'm confused because the output of the post still renders the img markup, and my assumption is that catch_that_image() should snag that markup? Is my thinking incorrect? Is there a better way to handle this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
该图库使用 WordPress 短标签放置在您的帖子中。当应用用于转换短标签的过滤器时,短标签被转换为HTML图像标签。
以下方法可能有效,但我不确定:
请告诉我这是否有用或者它是否为您指明了正确的方向!
法典链接:
http://codex.wordpress.org/Gallery_Shortcode
http://codex.wordpress.org/Function_Reference/apply_filters
http: //codex.wordpress.org/Function_Reference/do_shortcode
The gallery is placed inside your post using a WordPress short-tag. The shorttag is transformed into HTML-image tags when the filter for transforming the shorttag is applied.
The following might work, but I am not sure:
Please let me know if this was useful or if it was pointing you into the right direction!
Codex Links:
http://codex.wordpress.org/Gallery_Shortcode
http://codex.wordpress.org/Function_Reference/apply_filters
http://codex.wordpress.org/Function_Reference/do_shortcode