wordpress中的所有图片都会自动调整大小并保存在上传文件夹中,如下所示:
sample_product_image-100x100.png
sample_product_image-150x150.png
sample_product_image-180x113.png
sample_product_image-300x189.png
...
sample_product_image-555x349.png
sample_product_image-600x378.png
sample_product_image.png (original large file)
为了加快加载速度我需要在休息api中使用较小尺寸的产品图像:
sample_product_image-300x189.png
但是woocommerce rest api只是发给我原始最大的文件(sample_product_image.png):
"images": [
{
"id": 7291,
"date_created": "2018-06-12T03:17:03",
"date_created_gmt": "2018-06-11T13:47:03",
"date_modified": "2018-06-12T03:17:03",
"date_modified_gmt": "2018-06-11T13:47:03",
"src": "http://example.com/wp-content/uploads/2018/06/sample_product_image.png",
"name": "sample_product_image",
"alt": "",
"position": 0
},
如何在wc rest api中获取较小的图片网址?
btw我发现this plugin用于wordpress rest api,这对于woocommerce不起作用。
答案 0 :(得分:1)
找到了解决方案here。 只需要将此过滤器添加到主题的function.php
中function prepare_product_images($response, $post, $request) {
global $_wp_additional_image_sizes;
if (empty($response->data)) {
return $response;
}
foreach ($response->data['images'] as $key => $image) {
$image_urls = [];
foreach ($_wp_additional_image_sizes as $size => $value) {
$image_info = wp_get_attachment_image_src($image['id'], $size);
$response->data['images'][$key][$size] = $image_info[0];
}
}
return $response;
}
add_filter("woocommerce_rest_prepare_product_object", "prepare_product_images", 10, 3);
此外,如果您只需要1个特殊尺寸,则可以删除第二个foreach并手动将$size
初始化为'thumbnail'
,'medium'
,'medium_large'
或'large'