kilbot
8/19/2017 - 9:50 AM

Adding a product image to the WC REST API order output

Adding a product image to the WC REST API order output

<?php

// the code below goes in your functions.php file

function my_custom_prepare_shop_order_object( $response, $order, $request ) {
  if( !is_pos() ) {
    return $response; // early exit if not POS request
  }
  
  $data = $response->get_data();

  // cycle through line_items and add the thumbnail
  if( is_array( $data['line_items'] ) ) : foreach( $data['line_items'] as &$line_item ) :
    $thumb_id = get_post_thumbnail_id( $line_item['variation_id'] ? $line_item['variation_id'] : $line_item['product_id'] );
    $thumb_array = wp_get_attachment_image_src( $thumb_id, 'shop_thumbnail' );
    $line_item['featured_src'] = is_array($thumb_array) ? $image[0] : wc_placeholder_img_src();
  endforeach; endif;

  $response->set_data($data);
  return $response;
}

add_filter( 'woocommerce_rest_prepare_shop_order_object', 'my_custom_prepare_shop_order_object', 10, 3 );