当前位置:首页WP教程WordPress非正则获取文章第一张图片

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

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

网上流传的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图片作为缩略图。

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

给TA打赏
共{{data.count}}人
人已打赏
WP教程

微信公众平台测试账号申请方法

2023-3-8 22:10:02

WP教程

WordPress主循环The Loop

2023-3-8 22:10:06

0 条回复 A文章作者 M管理员
    暂无讨论,说说你的看法吧
购物车
优惠劵
有新私信 私信列表
搜索