WordPress为已发布的文章提取内容第一张图片设为特色图

编程入门 行业动态 更新时间:2024-10-07 10:25:55

WordPress为已发布的文章提取内容第一张图片<a href=https://www.elefans.com/category/jswz/34/1681478.html style=设为特色图"/>

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

本文发布于:2024-03-06 16:35:24,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1715810.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:设为   第一张   内容   色图   文章

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!