因为您只是传递图像的位置,而不是图像本身。因此,您基本上是在本地计算机上告诉WordPress您的图像所在的位置。服务器将无法访问本地计算机上的文件。
首先将图像上传到WordPress,然后在Woocommerce导入脚本中传入图像ID,就可以解决这个问题。
使用以下脚本,可以执行以下操作:
\'images\' => [ file_or_url_to_wordpress_image(\'C:\\Users\\579\\Desktop\\2.1.jpg\') ]
需要添加到文件中的内容:
DEFINE(\'WORDPRESS_BASE_URL\', \'https://remote-wordpress-site.com\');
// Your WordPress username
DEFINE(\'WORDPRESS_LOGIN\', \'admin\');
// Create a new Application Password in dashboard /wp-admin/profile.php
DEFINE(\'WORDPRESS_APPLICATION_PASSWORD\', \'TBIg TthU rJG3 moMe Qjor Vtl2\');
/**
* Takes a file or a url and uploads it to WordPress
*/
function file_or_url_to_wordpress_image($image_path){
// If the input is a URl, we can process it
if (filter_var($image_path, FILTER_VALIDATE_URL)) {
return [\'src\'=>$image_path];
}
// Make sure the image exist
if (!file_exists($image_path)){return;}
// Load the image
$file = file_get_contents( $image_path );
// Get the filename
$filename = basename($image_path);
// Initiate curl.
$ch = curl_init();
curl_setopt( $ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt( $ch, CURLOPT_URL, WORDPRESS_BASE_URL .\'/wp-json/wp/v2/media/\' );
curl_setopt( $ch, CURLOPT_POST, 1 );
curl_setopt( $ch, CURLOPT_POSTFIELDS, $file );
curl_setopt( $ch, CURLOPT_HTTPHEADER, [
"Content-Disposition: form-data; filename=\\"$filename\\"",
\'Authorization: Basic \' . base64_encode( WORDPRESS_LOGIN. \':\' . WORDPRESS_APPLICATION_PASSWORD ),
] );
$result = curl_exec( $ch );
curl_close( $ch );
// Decode the response
$api_response = json_decode($result);
// Return the ID of the image that is now uploaded to the WordPress site.
return [\'id\' => $api_response];
}