wordpress自动保存远程图片代码

wordpress自动保存远程图片代码,直接放到functions,保存的图片命名为时间戳+5个随机字母,用接口发布和后台编辑器发布都能保存,可以配合转换webp插件把图片转换成wepb。另外还将第一张图片设置为特色图像

//自动保存远程图片
function wp_auto_save_remote_images_and_update_post($new_status, $old_status, $post) {
    if ('publish' === $new_status && 'publish' !== $old_status) {
        $post_id = $post->ID;
        $content = $post->post_content;
        $upload_dir = wp_upload_dir();
        $img_pattern = '/<img.*?src="(http:\/\/|https:\/\/[^"]*)".*?>/i';

        if (preg_match_all($img_pattern, $content, $matches)) {
            $content_updated = false;
            $first_image_attached = false;

            foreach ($matches[1] as $img_url) {
                // 获取远程图片
                $response = wp_remote_get($img_url);

                if (!is_wp_error($response) && wp_remote_retrieve_response_code($response) === 200) {
                    $file_contents = wp_remote_retrieve_body($response);
                    $filetype = wp_check_filetype($img_url);

                    // 生成新的文件名
                    $random_string = substr(str_shuffle("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"), 0, 5);
                    $timestamp = time();
                    $file_name = $timestamp . '' . $random_string . '.' . $filetype['ext'];

                    // 使用WordPress内置上传功能
                    require_once(ABSPATH . 'wp-admin/includes/file.php');
                    $tmp_file = wp_tempnam($file_name);
                    file_put_contents($tmp_file, $file_contents);
                    $file = array(
                        'name' => $file_name,
                        'tmp_name' => $tmp_file,
                    );
                    $uploaded_file = wp_handle_sideload($file, array('test_form' => false));

                    if (!isset($uploaded_file['error'])) {
                        $local_file_url = $uploaded_file['url'];

                        // 将文件添加到媒体库
                        $attachment = array(
                            'guid' => $local_file_url,
                            'post_mime_type' => $filetype['type'],
                            'post_title' => $post->post_title,
                            'post_content' => '',
                            'post_status' => 'inherit',
                        );
                        $attach_id = wp_insert_attachment($attachment, $uploaded_file['file'], $post_id);
                        require_once(ABSPATH . 'wp-admin/includes/image.php');
                        $attach_data = wp_generate_attachment_metadata($attach_id, $uploaded_file['file']);
                        wp_update_attachment_metadata($attach_id, $attach_data);

                        // 替换文章内容中的图片地址
                        $content = str_replace($img_url, $local_file_url, $content);
                        $content_updated = true;

                        // 如果这是第一张图片,则将其设置为特色图像
                        if (!$first_image_attached) {
                            set_post_thumbnail($post_id, $attach_id);
                            $first_image_attached = true;
                        }
                    }
                }
            }

            if ($content_updated) {
                // 移除 transition_post_status 动作,避免无限循环
                remove_action('transition_post_status', 'wp_auto_save_remote_images_and_update_post', 10);

                // 更新文章内容到数据库
                wp_update_post(
                    array(
                        'ID' => $post_id,
                        'post_content' => $content,
                    ),
                    true
                );

                // 重新添加 transition_post_status 动作
                add_action('transition_post_status', 'wp_auto_save_remote_images_and_update_post', 10, 3);
}
}
}
}

add_action('transition_post_status', 'wp_auto_save_remote_images_and_update_post', 10, 3);

给TA打赏
共{{data.count}}人
人已打赏
WP笔记

WordPress如何提取某一时间段浏览量最多的文章

2023-2-26 11:15:08

WP笔记

利用chatgpt在wordpress发布文章的时候根据标题提取关键词

2023-3-25 15:33:02

0 条回复 A文章作者 M管理员
    暂无讨论,说说你的看法吧
个人中心
购物车
优惠劵
今日签到
有新私信 私信列表
搜索