WordPress 主题提取文章内的第一张图片显示为特色图片和略缩图

欧美的主题有一个不合适亚州人写作使用习惯的问题,就是每发布一篇文章都要特意去设定一张“特色图片”,这样才会在博客列表中显示文章的配图,可是这样太不方便了。以下这个办法适用于和匹配大量的国外主题解决特色图片的显示问题。只需要把以下的代码放入主题 functions.php 文件的合适位置即可:

 

#Wordpress 主题提取文章内的第一张图片显示为特色图片和略缩图
function set_existing_posts_first_image_as_featured_image() {
    $args = array(
        'post_type' => 'post',
        'posts_per_page' => -1 // 获取所有文章
    );

    $posts = get_posts($args);

    foreach ($posts as $post) {
        setup_postdata($post);

        $post_content = get_post_field('post_content', $post->ID);

		// 从文章内容中匹配第一张图片
		if (preg_match('/<img.+src=[\'"]([^\'"]+)[\'"].*>/i', $post_content, $matches)) {
			$first_image_url = $matches[1];
			// 获取图片的ID
			$attachment_id = attachment_url_to_postid($first_image_url);

			if ($attachment_id) {
				// 将图片设置为特色图
				set_post_thumbnail($post->ID, $attachment_id);
			}
		}
    }
    wp_reset_postdata();
}
set_existing_posts_first_image_as_featured_image();

这样会自动匹配文章里面的img标签,并且根据img的src属性查找媒体id,最后设为文章特色图片。
这个代码加上之后运行一次,最好就把代码删掉,不然会极大影响网站运行速度。

又或者加下面这段代码也可以:

/*自动获取wordpress日志中的第一张图片作为缩略图*/
function get_content_first_image($content){
    if ( $content === false ) $content = get_the_content();
 
    preg_match_all('|<img.*?src=[\'"](.*?)[\'"].*?>|i', $content, $images);
 
    if($images){      
        return $images[1][0];
    }else{
        return false;
    }
}

如果动手能力不强的话,为了防止出各种BUG,建议直接用插件吧,我推荐的插件是:

1、XO Featured Image Tools,这个会自动获取第一张图为缩略图。

2、WP Random Post Thumbnails,这个可以在指定范围内随机缩略图。

給TA打賞
共{{data.count}}人
人已打賞
WordPress教程

把B2的POST文章列表的发布日期*年前改为*年*月*日

2025-5-17 13:20:15

WordPress插件

WordPress评论回复自动加@

2019-2-15 14:08:45

0 Reply AAuthor MManager
    暫無討論,說說你的看法吧
搜索