Saeed Arianmanesh
Saeed Arianmanesh

Reputation: 1428

WooCommerce REST API - how to get product resized images url?

all images in wordpress will auto resize and save in uploads folder like this:

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)

for faster loading I need smaller size of product image in rest api like this one:

sample_product_image-300x189.png

but woocommerce rest api just send me original largest file (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
            },

how can I get smaller image urls in wc rest api?

btw I found this plugin for wordpress rest api that is not working for woocommerce.

Upvotes: 3

Views: 3769

Answers (1)

Saeed Arianmanesh
Saeed Arianmanesh

Reputation: 1428

found a solution here. Just need to add this filter to your theme's 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);

Also if you need only 1 special size you can remove second foreach and manually initialize $size to 'thumbnail' , 'medium' , 'medium_large' or 'large'

Upvotes: 13

Related Questions