我正在尝试使用Woocommerce API将另一张图片添加到产品中。
但是,API会覆盖现有的图像。我尝试了没有ID,没有标题,唯一ID等的问题。
是否有一种方法可以使其附加新图像而不接触现有图像?
{"images": [
{
"title": "temp1",
"position": 3,
"src": "https://www.example.com/myimage.jpg"
}]}
事实证明,如果您使用图像的内部帖子ID作为ID标签,则可以使用现有图像:
{“图像”: [{“ id”:587}] } 这将覆盖现有图像。
因此,如果我想出一种方法来获取产品的所有图像ID,则可以将它们全部重新添加,并将新图像附加到末尾...
请参阅:WooCommerce API creates images in media even if they exist
答案 0 :(得分:0)
因此,当我想添加一个图像时,我无法弄清楚如何阻止woocommerce覆盖所有图像,因此我编写了将新图像添加到图像列表中的代码。
//GET CURRENT IMAGE IDs FOR A PRODUCT AND BUILD JSON OF THEM
$product_id = '652';
$product = new WC_product($product_id);
$attachment_ids = $product->get_gallery_image_ids();
array_unshift($attachment_ids, get_post_thumbnail_id($product_id));
//BUILD JSON OF EXISTING IMAGE IDS
foreach( $attachment_ids as $attachment_id ) {
$json_images .= '{"id":' . $attachment_id . '}';
$json_images .= ($i<count($attachment_ids) ? ',' : '');
}
echo "<br>" . $json_images;
//POST AN IMAGE TO AN AUCTION
$host = 'https://beta.blohbloh.com/wp-json/wc/v3/products/' . $product_id;
$consumer_key='ck_2364';
$consumer_secret='cs_12ce';
//NEEDS TO INCLUDE ALL PREVIOUS IMAGE IDS IN JSON FORMAT
$payload = '{"images": [';
$payload .= $json_images;
$payload .= '{"src":';
//sample image to append
$payload .= '"https://somesite.com/someimage.jpg"';
$payload .= '}]}';
$process = curl_init($host);
curl_setopt($process, CURLOPT_HTTPHEADER, array('Content-Type: application/json', $additionalHeaders));
curl_setopt($process, CURLOPT_HEADER, 1);
curl_setopt($process, CURLOPT_USERPWD, $consumer_key . ":" . $consumer_secret);
curl_setopt($process, CURLOPT_TIMEOUT, 30);
//curl_setopt($process, CURLOPT_POST, 1);
//curl_setopt($process, CURLOPT_POSTFIELDS, $payload);
curl_setopt($process, CURLOPT_CUSTOMREQUEST, "PUT");
curl_setopt($process, CURLOPT_POSTFIELDS,$payload);
curl_setopt($process, CURLOPT_RETURNTRANSFER, TRUE);
$return = curl_exec($process);
curl_close($process);