WordPress非正则获取文章第一张图片

作者: 站长 上传时间: 浏览: N/A 下载: N/A 格式: N/A 评分: N/A

网上流传的WordPress获取文章第一张图片作为缩略图的方法都是采用正则匹配抓取来实现的,代码如下:

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)){
$first_img = '/images/default.jpg';
}
return $first_img;
}

有人说这种方式效率太低,所以我写了第二种方法,首先通过get_children()函数来获取文章的第一张图片ID:

function get_first_image_ID($postID = '') {
global $post;
if( ! $postID ) $postID = $post->ID;
$thumbnail_id = '';
$args = array(
'numberposts' => 1,
'order'=> 'ASC',
'post_mime_type' => 'image/jpeg',
'post_parent' => $postID,
'post_status' => null,
'post_type' => 'attachment'
);
$attachments = get_children( $args );
if($attachments){
$thumbnail_id = key($attachments);
}
return $thumbnail_id;
}

以上函数如果在主循环中使用,不需要传递文章ID。

然后通过图片ID获取图片地址:

$thumbnail_src = wp_get_attachment_image_src($thumbnail_id, $size);
$img_url = $thumbnail_src[0];

$size参数指定缩略图版本,也就是图片大小。下面是输出缩略图的完整函数:

function bzg_thumbnail($size='post-thumbnails') {
global $post;
$width = '';
$height = '';
$img_url = get_bloginfo('template_url') . '/images/default-thumbnail.png';
if( has_post_thumbnail() ) {
$post_thumbnail_id = get_post_thumbnail_id( $post->ID );
} else {
$post_thumbnail_id = get_first_image_ID($post->ID);
}
if($post_thumbnail_id) {
$thumbnail_src = wp_get_attachment_image_src($post_thumbnail_id, $size);
$img_url = $thumbnail_src[0];
$width = ' width="' . $thumbnail_src[1] . '"';
$height = ' height="' . $thumbnail_src[2] . '"';
}
echo '<a href="' . get_permalink($post->ID) . '">';
echo '<img src="' . $img_url . '"' . $width . $height . ' alt="' . $post->post_title . '" />';
echo '</a>';
}

当指定了特色图像时,缩略图将输出特色图像,否则获取文章第一张图片作为缩略图,如果文章没有上传任何图片,则使用主题images目录里的default-thumbnail.png图片作为缩略图。

用本文方法获取缩略图,可以选择小尺寸版本图片,而正则的方式是输出原图,会对文章列表页访问速度造成一定影响。