只是为了确保:您有一个没有WooCommerce的本地环境,您想在WooCommerce Wordpress站点中创建产品,并确保您提供的图像上载到Wordpress站点。
1。安装库
确保您在本地环境中安装了
WooCommerce REST API PHP Library.
composer require automattic/woocommerce
2。创建脚本创建一个名为my_import_file.php
touch my_import_file.php
使用您最喜欢的编辑器(或任何编辑器)编辑该文件。
使用Vim
vim my_import_file.php
使用
Visual Studio Code (如果您有
shell command installed)
code my_import_file.php
您需要:
您的文件应类似于以下内容:
<?php
/**
* Settings
*/
// Your Wordpress site URL
DEFINE(\'WORDPRESS_BASE_URL\', \'https://enter-your-wordpress-url-here\');
// Your WordPress username
DEFINE(\'WORDPRESS_LOGIN\', \'enter-your-wordpress-username-here\');
// Create a new Application Password in dashboard /wp-admin/profile.php
DEFINE(\'WORDPRESS_APPLICATION_PASSWORD\', \'enter-your-application-password-here\');
// Create a new REST API key from your wordpress installation
// https://docs.woocommerce.com/document/woocommerce-rest-api/
DEFINE(\'WOOCOMMERCE_CONSUMER_KEY\', \'enter-your-woocomemrce-consumer-key-here\');
DEFINE(\'WOOCOMMERCE_CONSUMER_SECRET\', \'enter-your-woocomemrce-consumer-secret-here\');
// Load composers autoload
require __DIR__ . \'/vendor/autoload.php\';
// Use the WooComerce client
use Automattic\\WooCommerce\\Client;
// Initiate the WooCommerce client
$woocommerce = new Client(
WORDPRESS_BASE_URL,
WOOCOMMERCE_CONSUMER_KEY,
WOOCOMMERCE_CONSUMER_SECRET,
[
\'version\' => \'wc/v3\',
]
);
// An array of all the images you want to upload. They can be local files or URL\'s.
// Any non existing images will be filtered out.
$images = array(
"/Users/admin/Documents/nice-image-of-me.jpg",
"http://demo.woothemes.com/woocommerce/wp-content/uploads/sites/56/2013/06/T_2_back.jpg",
"string that is invalid"
);
// Define the product you want to create
$data = [
\'name\' => \'Premium Quality\',
\'type\' => \'simple\',
\'regular_price\' => \'21.99\',
\'description\' => \'Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Vestibulum tortor quam, feugiat vitae, ultricies eget, tempor sit amet, ante. Donec eu libero sit amet quam egestas semper. Aenean ultricies mi vitae est. Mauris placerat eleifend leo.\',
\'short_description\' => \'Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas.\',
\'categories\' => [
[
\'id\' => 9
],
[
\'id\' => 14
]
],
\'images\' => prepare_array_of_images_for_wordpress($images)
];
// Create the product
$result = $woocommerce->post(\'products\', $data);
// Print the result
print_r($result);
/**
* Takes an array of images, strings or URL\'s and prepares for import.
*/
function prepare_array_of_images_for_wordpress(array $array_of_images){
// Create empty array
$images_to_upload = array();
// Loop through the input, and process each entry
foreach($array_of_images as $image){
$images_to_upload[] = file_or_url_to_wordpress_image($image);
}
// Remove any unsucessful images from the array.
return array_filter($images_to_upload);
}
/**
* Takes a file or a url and uploads it to WordPress
* Returns the image ID from the WordPress media gallery.
*/
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->id];
}
如果要手动指定每个图像,请替换此行:
\'images\' => prepare_array_of_images_for_wordpress($images)
具有
\'images\' => [
[
\'id\' => file_or_url_to_wordpress_image(\'path-to-image\'),
\'other_option\' => \'value\'
],
[
\'src\' => file_or_url_to_wordpress_image(\'url-to-image\'),
\'other_option\' => \'value\'
],
]
确保您使用
\'id\'
如果是指上传的图像,以及
\'src\'
当它是URL时。
3。在浏览器中或从命令行使用以下命令运行脚本:
php my_import_file.php
它应该输出如下内容:
stdClass Object
(
[id] => 736
[name] => Premium Quality
[slug] => premium-quality
[permalink] => https://localhost/p/uncategorized/premium-quality/
[date_created] => 2021-06-12T18:01:08
[date_created_gmt] => 2021-06-12T18:01:08
[date_modified] => 2021-06-12T18:01:08
[date_modified_gmt] => 2021-06-12T18:01:08
[type] => simple
[status] => publish
[featured] =>
[catalog_visibility] => visible
[description] => Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Vestibulum tortor quam, feugiat vitae, ultricies eget, tempor sit amet, ante. Donec eu libero sit amet quam egestas semper. Aenean ultricies mi vitae est. Mauris placerat eleifend leo.
[short_description] => Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas.
[sku] =>
[price] => 21.99
[regular_price] => 21.99
[sale_price] =>
[date_on_sale_from] =>
[date_on_sale_from_gmt] =>
[date_on_sale_to] =>
[date_on_sale_to_gmt] =>
[on_sale] =>
[purchasable] => 1
[total_sales] => 0
[virtual] =>
[downloadable] =>
[downloads] => Array
(
)
[download_limit] => -1
[download_expiry] => -1
[external_url] =>
[button_text] =>
[tax_status] => taxable
[tax_class] =>
[manage_stock] =>
[stock_quantity] =>
[backorders] => no
[backorders_allowed] =>
[backordered] =>
[low_stock_amount] =>
[sold_individually] =>
[weight] =>
[dimensions] => stdClass Object
(
[length] =>
[width] =>
[height] =>
)
[shipping_required] => 1
[shipping_taxable] => 1
[shipping_class] =>
[shipping_class_id] => 0
[reviews_allowed] => 1
[average_rating] => 0
[rating_count] => 0
[upsell_ids] => Array
(
)
[cross_sell_ids] => Array
(
)
[parent_id] => 0
[purchase_note] =>
[categories] => Array
(
[0] => stdClass Object
(
[id] => 27
[name] => Mat
[slug] => mat
)
)
[tags] => Array
(
)
[images] => Array
(
[0] => stdClass Object
(
[id] => 734
[date_created] => 2021-06-12T18:01:07
[date_created_gmt] => 2021-06-12T18:01:07
[date_modified] => 2021-06-12T18:01:07
[date_modified_gmt] => 2021-06-12T18:01:07
[src] => https://localhost/wp-content/uploads/2021/06/nice-image-of-me.jpg
[name] => nice-image-of-me
[alt] =>
)
[1] => stdClass Object
(
[id] => 735
[date_created] => 2021-06-12T18:01:08
[date_created_gmt] => 2021-06-12T18:01:08
[date_modified] => 2021-06-12T18:01:08
[date_modified_gmt] => 2021-06-12T18:01:08
[src] => https://localhost/wp-content/uploads/2021/06/T_2_back-3.jpg
[name] => T_2_back-3.jpg
[alt] =>
)
)
[attributes] => Array
(
)
[default_attributes] => Array
(
)
[variations] => Array
(
)
[grouped_products] => Array
(
)
[menu_order] => 0
[price_html] => <span class="woocommerce-Price-amount amount"><bdi>21,99 <span class="woocommerce-Price-currencySymbol">€</span></bdi></span>
[related_ids] => Array
(
[0] => 143
[1] => 687
[2] => 17
[3] => 712
[4] => 688
)
[meta_data] => Array
(
)
[stock_status] => instock
[brands] => Array
(
)
[_links] => stdClass Object
(
[self] => Array
(
[0] => stdClass Object
(
[href] => https://localhost/wp-json/wc/v3/products/736
)
)
[collection] => Array
(
[0] => stdClass Object
(
[href] => https://localhost/wp-json/wc/v3/products
)
)
)
)