WooCommerce REST API - 如何获取产品调整大小的图片网址?

Sae*_*esh 1 woocommerce-rest-api

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)
Run Code Online (Sandbox Code Playgroud)

为了更快地加载,我需要在rest api中使用较小尺寸的产品图像,如下所示:

sample_product_image-300x189.png
Run Code Online (Sandbox Code Playgroud)

但是 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
            },
Run Code Online (Sandbox Code Playgroud)

如何在 wc rest api 中获得较小的图像 url?

顺便说一句,我发现这个wordpress rest api插件不适用于 woocommerce。

Sae*_*esh 9

这里找到了解决方案。只需要将此过滤器添加到您主题的 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);
Run Code Online (Sandbox Code Playgroud)

此外,如果你只需要1米特殊的尺寸,你可以删除第二的foreach和手动初始化$size'thumbnail''medium''medium_large''large'