设为特色图"/>
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为已发布的文章提取内容第一张图片设为特色图
发布评论