【问题标题】:WordPress: snag first image from a galleryWordPress:从图库中获取第一张图片
【发布时间】: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


    【解决方案1】:

    图库使用 WordPress 短标签放置在您的帖子中。当应用用于转换短标签的过滤器时,短标签将被转换为 HTML 图像标签。

    以下方法可能有效,但我不确定:

    function catch_that_image() {
    global $post, $posts;
    $first_img = '';
    ob_start();
    ob_end_clean();
    
    
    $transformed_content = apply_filters('the_content',$post->post_content);
    
    
    $output = preg_match_all('/<img.+src=[\'"]([^\'"]+)[\'"].*>/i', $transformed_content, $matches);
    $first_img = $matches [1] [0];
    
    if(empty($first_img)){ //Defines a default image
    $first_img = "/images/default.jpg";
    }
    return $first_img;
    }
    

    请让我知道这是否有用或是否为您指明了正确的方向!

    法典链接:

    http://codex.wordpress.org/Gallery_Shortcode

    http://codex.wordpress.org/Function_Reference/apply_filters

    http://codex.wordpress.org/Function_Reference/do_shortcode

    【讨论】:

    • 它渲染图片的文本路径而不是图片本身有什么解决办法?
    • 我的错误是我试图在没有图像标签的情况下获得它:P 无论如何,谢谢,但现在我想添加我的自定义尺寸。知道该怎么做吗?
    • 您也可以尝试通过帖子中的图片附件获取图片。也许这个讨论是有帮助的。 wordpress.org/support/topic/… 也许您可以进行自定义数据库查询,以检查帖子附加了哪个图像。您可以获取图像,并使用其附件 ID 传递大小。
    猜你喜欢
    • 2011-12-28
    • 1970-01-01
    • 2016-05-18
    • 2013-07-27
    • 2013-03-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-06-22
    相关资源
    最近更新 更多