# 测试代码功能

- 连结：https://blog.guohao.asia/%e6%b5%8b%e8%af%95%e4%bb%a3%e7%a0%81%e5%8a%9f%e8%83%bd.html
- 发布时间：2025-01-02T08:21:43+08:00
- 作者：null

中文   英文   韩语   日语

# 测试代码功能

测试代码功能：自动获取文章内首张图片并设置为文章的特色图片，如果这个图片是外链图片
则自动下载回本地。

![测试代码功能](https://blog.guohao.asia/wp-content/themes/wordpress-theme-puock-
2.8.16/assets/img/z/load.svg "测试代码功能")

    ```language-default
    // 在文章保存之前的钩子函数中添加自动抓取特色图片的功能
    function auto_set_featured_image($post_id) {
        // 检查是否为新文章
        if (!wp_is_post_revision($post_id)) {
            // 获取文章内容
            $post_content = get_post_field('post_content', $post_id);

            // 使用正则表达式匹配第一个图片标签
            preg_match('/<img.+src=[\'"]([^\'"]+)[\'"].*>/i', $post_content, $matches);

            // 检查是否匹配到图片标签
            if ($matches && isset($matches[1])) {$image_url = $matches[1];

                // 检查图片是否为本地图片
                if (strpos($image_url, site_url()) === 0) {$image_path = str_replace(site_url(), ABSPATH, $image_url);

                    // 获取本地图片的附件 ID
                    $attachment_id = attachment_url_to_postid($image_path);

                    // 设置附件 ID 为特色图片
                    if ($attachment_id) {set_post_thumbnail($post_id, $attachment_id);
                    }
                } else {
                    // 如果图片是外链图片，则下载并保存为本地附件
                    $upload_dir = wp_upload_dir();
                    $image_name = basename($image_url);
                    $image_path = $upload_dir['path'] . '/' . $image_name;

                    // 下载图片
                    $image_data = file_get_contents($image_url);

                    // 保存图片为本地附件
                    if ($image_data !== false) {file_put_contents($image_path, $image_data);

                        // 添加图片到媒体库
                        $attachment = array('guid'           => $upload_dir['url'] . '/' . $image_name,
                            'post_mime_type' => 'image/jpeg', // 根据实际情况修改图片类型
                            'post_title'     => $image_name,
                            'post_content'   => '','post_status'=>'inherit'
                        );

                        $attachment_id = wp_insert_attachment($attachment, $image_path, $post_id);

                        // 设置附件 ID 为特色图片
                        if (!is_wp_error($attachment_id)) {set_post_thumbnail($post_id, $attachment_id);
                        }
                    }
                }
            }
        }
    }
    add_action('save_post', 'auto_set_featured_image');
    ```
