上载。将csv文件复制到服务器上,然后迭代这些条目,为Woocommerce API创建适当的数组。
像这样的。
$path = $_SERVER[\'DOCUMENT_ROOT\'];
require_once( $path.\'/wp-load.php\' );
$filepath = site_url()."/data/mybatchfile.csv";
$handle = fopen($filepath, "r") or die("Error opening file");
$i = 0;
while(($line = fgetcsv($handle)) !== FALSE) {
if($i == 0) {
$c = 0;
foreach($line as $col) {
$cols[$c] = $col;
$c++;
}
} else if($i > 0) {
$c = 0;
foreach($line as $col) {
$prod_data[$i][$cols[$c]] = $col;
$c++;
}
}
$i++;
}
fclose($handle);
foreach ($prod_data as $prod_row){
$name = $prod_row["product_name"] // these are the column header names
//get all the rest of your vars here
$variation1SKU = $prod_row["first_variation_SKU"];
$variation1name = $prod_row["first_variation_name"];
$var1slug = strtolower(trim(preg_replace(\'/[^A-Za-z0-9-]+/\', \'-\', $variation1name)));
$variation1price = $prod_row["first_variation_price"];
$variation1color = $prod_row["first_variation_color"];
$variation1optname = $prod_row["first_variation_option_name"];
$variation2SKU = $prod_row["second_variation_SKU"];
$variation2name = $prod_row["second_variation_name"];
$var2slug = strtolower(trim(preg_replace(\'/[^A-Za-z0-9-]+/\', \'-\', $variation2name)));
$variation2price = $prod_row["second_variation_price"];
$variation2color = $prod_row["second_variation_color"];
$variation1optname = $prod_row["first_variation_option_name"];
$api = new WC_REST_Products_Controller();
$request = new WP_REST_Request (\'POST\', \'\', \'\');
$request->set_body_params( array (
\'name\' => $name,
\'slug\' => $slug,
\'type\' => \'simple\',
\'status\' => \'publish\',
\'regular_price\' => $price,
\'price\' => $price,
//\'sale_price\' => 40,
\'description\' => \'This is the description for the \'.$name.\' product\',
\'virtual\' => 1,
\'tax_status\' => \'none\', // or \'taxable\'
\'variations\' => array(
array(
\'sku\' => $variation1SKU,
\'regular_price\' => $variation1price,
\'attributes\' => array(
array(
\'id\' => date(\'YmdHis\', strtotime(\'+2 seconds\')),
\'slug\'=> $var1slug,
\'name\'=> $variation1name,
\'option\'=> $variation1optname,
)
)
),
array(
\'sku\' => $variation2SKU,
\'regular_price\' => $variation2price,
\'attributes\' => array(
array(
\'id\' => date(\'YmdHis\', strtotime(\'+2 seconds\')),
\'slug\'=> $var2slug,
\'name\'=> $variation2name,
\'option\'=> $variation2optname,
)
)
)
)
));
$response = $api->create_item( $request );
$id = $response->data[\'id\']; // the post id of the new item
}
这只是一个未经测试的示例代码,向您展示了使用Woocommerce和Wordpress的API创建产品的有效方法。您需要创建一个具有友好列标题的CSV文件,然后在上载之前将其保存为UTF-8。如果您有一些简单的产品和一些可变的产品,那么您需要引入一个值检查,比如对第一个变体的名称字段的变量进行检查。如果为空,则将请求主体设置为单向,如果填充了请求主体,则使用变体构建请求主体。这类事情。希望有帮助!
另外,woocommerce API允许您使用
$response = $api->update_item( $request );
然后通过在请求正文中输入要更新的项目来告诉它
\'id\' => $id,
然后,请求主体中的其他变量(如价格或描述)将得到更新。我发现这是一个非常宝贵的工具,可以动态修改产品,创建订单,将这些产品添加到新订单中,然后将价格恢复到其原始价值。这就是如何创建具有自定义价格的自定义订单,而不在订单上显示折扣商品。
我从以下线程获得的变体示例代码:https://stackoverflow.com/questions/37823867/woocommerce-api-create-new-product-with-variations