WordPress: 获取文章的第一张图片

介绍了如何在 WordPress 中获取文章的第一张图片。有时候我们给文章设置了特色图片(或称缩略图),有的时候没有,有的时候文章中甚至一副图片都没有。某些情况下,比如在图片式的相关文章或者热门文章之类的推荐阅读,为了给文章配个图就需要用到这样的方法了。

将下面的函数放到主题的 functions.php 文件中(如果没有就自己创建一个),然后在需要的时候调用这个函数来获得相应图片的 url 地址。在调用该函数的时候记得将文章的 $id 传递过去。

function catch_the_image( $id ) {
// global $post, $posts;
$first_img = '';

// 如果设置了缩略图
$post_thumbnail_id = get_post_thumbnail_id( $id );
if ( $post_thumbnail_id ) {
    $output = wp_get_attachment_image_src( $post_thumbnail_id, 'large' );
    $first_img = $output[0];
}
else { // 没有缩略图,查找文章中的第一幅图片
    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)){ // 既没有缩略图,文中也没有图,设置一幅默认的图片
        $first_img = "http://yourdomain.tld/images/default.jpg";
    }
}

return $first_img;
}

该函数返回的是图片的 url 地址。©

本文发表于水景一页。永久链接:<https://cnzhx.net/blog/get-the-first-image-of-a-post-in-wordpress/>。转载请保留此信息及相应链接。

8 条关于 “WordPress: 获取文章的第一张图片” 的评论

时间过去太久,评论已关闭。
如果您有话要说,请到讨论区留言并给出此文章链接。
谢谢您的理解 :-)