如何抓取亚马逊S3格式图片?WordPress media_sideload_image不识别该URL
问题描述
我从Booking Engine API获取到如下格式的图片URL:
https://platform.s3.us-west-2.amazonaws.com/listing/31767-84007-dwBVIaLkhsGzpK4sfxaS-T07Gd-EXAd78l8lsJpeuYM-618cf68ce2350
无法获取其他格式结果。当前使用WordPress平台,media_sideload_image函数不认可该URL为有效链接,请问如何抓取此图片?
解决方案
1. 绕过URL扩展名校验
media_sideload_image会默认检查URL是否包含图片扩展名(如.jpg、.png),你的S3链接无后缀,因此被判定无效。可以用以下两种方式解决:
方法一:添加伪造扩展名参数
在URL末尾拼接查询参数,模拟图片扩展名,让函数识别为有效图片链接:
$image_url = 'https://platform.s3.us-west-2.amazonaws.com/listing/31767-84007-dwBVIaLkhsGzpK4sfxaS-T07Gd-EXAd78l8lsJpeuYM-618cf68ce2350?ext=jpg'; // 替换$post_id为实际文章ID media_sideload_image($image_url, $post_id, '房源图片');
方法二:手动下载后上传
跳过函数的URL校验,直接获取图片内容再上传到媒体库:
$image_url = 'https://platform.s3.us-west-2.amazonaws.com/listing/31767-84007-dwBVIaLkhsGzpK4sfxaS-T07Gd-EXAd78l8lsJpeuYM-618cf68ce2350'; $post_id = 123; // 替换为实际文章ID // 获取图片响应 $response = wp_remote_get($image_url); if (is_wp_error($response)) { error_log('获取图片失败:' . $response->get_error_message()); return; } $image_content = wp_remote_retrieve_body($response); if (empty($image_content)) { error_log('图片内容为空'); return; } // 创建临时文件 $temp_path = wp_tempnam('booking_image'); file_put_contents($temp_path, $image_content); // 验证图片类型 $file_info = wp_check_filetype($temp_path); if (!$file_info['type'] || !str_starts_with($file_info['type'], 'image/')) { unlink($temp_path); error_log('非图片类型文件'); return; } // 上传到媒体库 $attachment_args = array( 'post_mime_type' => $file_info['type'], 'post_title' => 'API获取的房源图片', 'post_status' => 'inherit' ); $attach_id = wp_insert_attachment($attachment_args, $temp_path, $post_id); // 生成图片元数据 require_once ABSPATH . 'wp-admin/includes/image.php'; $attach_meta = wp_generate_attachment_metadata($attach_id, $temp_path); wp_update_attachment_metadata($attach_id, $attach_meta); // 清理临时文件 unlink($temp_path);
2. 修改WordPress的校验规则
通过钩子拦截文件校验逻辑,直接信任目标S3域名的链接:
add_filter('wp_handle_sideload_prefilter', function($file_data) { $target_domain = 'platform.s3.us-west-2.amazonaws.com/listing/'; if (str_contains($file_data['url'], $target_domain)) { // 强制标记为图片类型(可根据实际返回的MIME调整) $file_data['type'] = 'image/jpeg'; } return $file_data; });
内容的提问来源于stack exchange,提问作者braudyp
相关产品推荐
相关产品推荐

