WordPress 通过指定文章ID获取该文章的第一张图片

百度了一堆都不太好用,主要是我要在自定义文章类型(custom_type)的文章中调用默认文章类型(post)的第一张图片。其实我是为了扩充版面,让内容看起来不至于空虚,所以调用任意一张都可以。

Google了一下,找到了,这里记录一下。

1
2
3
4
5
6
7
8
9
10
11
12
function get_first_image( $post_id ) {
    $attach = get_children( array(
        'post_parent'    => $post_id,
        'post_type'      => 'attachment',
        'post_mime_type' => 'image',
        'order'          => 'DESC',
        'numberposts'    => 1
    ) );
    if( is_array( $attach ) && is_object( current( $attach ) ) ) {
        return current( $attach )->guid;
    }
}

调用的时候可以这样

1
<?php echo get_first_image($postid) ?>

这里的$postid就是你要指定的ID。

我参考自这里:https://wordpress.stackexchange.com/questions/60245/get-the-first-image-from-post-content-eg-hotlinked-images

更新:

发现用起来有点问题,因为需要调用的文章里面有另外一个图片字段,结果影响了需要获取的结果,调用的时候调用到了单独的图片字段,还是需要从文章内容中正则获取可能更妥当,更新代码

1
2
3
4
5
6
7
8
9
10
11
12
// Get URL of first image in a post
function catch_that_image($my_postid) {
global $post;
$first_img = '';
  ob_start();
  ob_end_clean();
            $output = preg_match_all('/<img.+src=[\'"]([^\'"]+)[\'"].*>/i',  get_post_field('post_content', $my_postid), $matches);

$first_img = $matches [1] [0];

return $first_img;
} ?>

调用:

1
2
3
<div class="thumbnail">
   <?php echo catch_that_image($loop->ID) ?>
</div>

Leave a Reply

You must be logged in to post a comment.

RSS feed for comments on this post. TrackBack URL