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,这个可以在指定范围内随机缩略图。

THE END
請多多支持
相关推荐
评论 抢沙发
头像
欢迎您留下宝贵的见解!
提交
头像

昵称

取消
昵称表情图片

    暂无评论内容