kb_
kb_

Reputation: 187

Get WooCommerce product URL based featured_image in WP Rest API

I'm using the WP Rest API in a React app. I am trying to access the product featured image in the Rest API. It already comes with the featured_media id, for example: featured_media: 15195, but that doesn't really help me show the image. I have been trying to figure out how to add a field in the Rest API to return the product image URL.

Is there a way to do this, or a resource that would be helpful?

Upvotes: 2

Views: 2483

Answers (1)

Always Helping
Always Helping

Reputation: 14570

You have two options you can use - either you can modify you current product rest api URL to have the images url being returned to in one call or you can modify your functions.php by adding this code below:

Modify functions.php

//Register new route - fetch product and its image together in one request
function product_route() {
    register_rest_field( 
        'product',
        'featured_image_url',
        array(
            'get_callback'    => 'getImagesUrl',
            'update_callback' => null,
            'schema'          => null,
        )
    );
}

add_action( 'rest_api_init', 'product_route' );

//get images with URL
function getImagesUrl( $object, $field_name, $request ) {
    //get products image URL
    $product_img_url = wp_get_attachment_image_src( get_post_thumbnail_id( $object->id ), 'large' );
    
    //return image url
    return $product_img_url['0'];
}

You can use fetch in single request like this after adding the above code in to functions.php

fetch(state.source.api + "/wp/v2/product")
  .then((response) => response.json())
  .then((data) => {
    //setProducts(data); //set state
});

Using nested fetch API calls to get the product URL

If you want more about details product image URL then You can use the wordpress media url endpoint to get featured_image url of your woo-commerce products.

Add this code in your fetch request. First fetch all the products and featured_media then loop through it and get all the source_url - you can save the urls based on product id in a new array in your react State

fetch(state.source.api + "/wp/v2/product")
  .then((response) => response.json())
  .then((data) => {
    //setProducts(data); //set state
    //loop through each data to get featured_media number
    data.forEach((x) => {
      //get all urls using featured_media
        fetch(state.source.api + "/wp/v2/media/"+x.featured_media)
        .then((response) => response.json())
        .then((o) => {
          //get all urls OR store to react State
          console.log(o.source_url)
      });
    })
});

Upvotes: 3

Related Questions