我正在尝试通过 API 自动创建和更新 woocommerce 产品。我已经创建了插件的起点,这是我从外部 API 获取产品的方法,然后循环它们并在 woocoommerce 中创建一个简单的产品。
它创建的产品完美无缺,但是如果我运行代码两次,产品不会获得更新,但会创建一批全新的产品(SKU 重复且没有任何错误),似乎 SKU 无法识别即使它存在并且我可以在产品的仪表板上看到它,并且在前端这是我到目前为止的代码:
// Activating the function when the plugin is activated
public function __construct()
{
add_action( 'activated_plugin', array($this, 'add_products_from_api') );
}
public function add_products_from_api() {
// API products url
$url = 'https://example.com/products';
// Retreiving the products body from api and decoding the json
$external_products = wp_remote_retrieve_body(wp_remote_get($url));
$products = json_decode($external_products, true);
// Products found
if (!empty($products)) {
foreach ($products as $product) {
// check if SKU already exists
$product_id = wc_get_product_id_by_sku($product['id']);
if (!$product_id) {
$post = [
'post_author' => '',
'post_content' => $product['description'],
'post_status' => "publish",
'post_title' => wp_strip_all_tags($product['title']),
'post_name' => $product['title'],
'post_parent' => '',
'post_type' => "product",
];
// Create product
$product_id = wp_insert_post($post);
// Set product type
wp_set_object_terms($product_id, 'simple', 'product_type');
update_post_meta($product_id, '_sku', $product['id']);
update_post_meta($product_id, '_price', $product['price']);
update_post_meta($product_id, '_manage_stock', "yes");
update_post_meta($product_id, '_stock', $product['rating']['count']);
}
else {
// Product already exists
$post = [
'ID' => $product_id,
'post_title' => $product['title'],
'post_content' => $product['description'],
];
$post_id = wp_update_post($post, true);
if (is_wp_error($post_id)) {
$errors = $post_id->get_error_messages();
foreach ($errors as $error) {
echo $error;
}
}
}
update_post_meta($product_id, '_stock', $product['rating']['count']);
update_post_meta($product_id, '_price', $product['price']);
}
}
}
有人知道为什么 SKU 存在但未被识别并且产品不断重复吗?谢谢。
最佳答案
简短的回答是,如果您只需将 if(!$product_id )
替换为 if (empty($product_id ))
即可解决问题。
但正确且有效的答案是,当您在 WooCommer 中创建产品时,我将建议使用 WooCommerce 原生 CRUD 方法。我知道你已经引用了我的old answer (我很快就会更新该答案)当时 WooCommer 确实有一个用于创建产品的内置方法,因此我们必须使用 WP 方法。
这是工作代码示例。
<?php
// Activating the function when the plugin is activated
public function __construct()
{
add_action( 'activated_plugin', array($this, 'add_products_from_api') );
}
public function add_products_from_api() {
// API products url
$url = 'https://fakestoreapi.com/products';
// Retreiving the products body from api and decoding the json
$external_products = wp_remote_retrieve_body(wp_remote_get($url));
$products = json_decode($external_products, true);
// Products found
if (!empty($products)) {
foreach ($products as $product) {
// check if SKU already exists
$productID = wc_get_product_id_by_sku($product['id']);
// Product Do not exists
if (empty($productID)) {
$productID = $this->wh_createOrUpdateProduct($product);
}
// Product exists with the given SKU
else {
$productID = $this->wh_createOrUpdateProduct($product, $productID);
}
// echo $productID;
}
}
}
protected function wh_createOrUpdateProduct($product, $productId = 0){
$objProduct = new WC_Product($productId);
$objProduct->set_sku($product['id']); //Set product SKU.
$objProduct->set_name($product['title']); //Set product name.
$objProduct->set_description($product['description']); //Set product description.
$objProduct->set_description($product['price']); //Set product price.
// getting product cat ID from name
$productCatID = $this->wh_getProductCatID($product['category']);
$objProduct->set_category_ids([$productCatID]); //Set product category ID.
$objProduct->set_average_rating($product['rating']['rate']); //Set avg. rating of the product.
$objProduct->set_review_count($product['rating']['count']); //Set total rating of the product.
$objProduct->set_manage_stock(true); //Set true if you want WooCommerce to manage your stock
$objProduct->set_stock_quantity($product['rating']['count']); //Set product stock qty.
$objProduct->set_status('publish'); //Set product status
$productID = $objProduct->save(); //Saving the data to create new product, it will return product ID.
return $productID;
}
protected function wh_getProductCatID($catName) {
$productCatDetails = wp_insert_term($catName, 'product_cat');
if (is_wp_error($productCatDetails)) {
if ($productCatDetails->get_error_code() == 'term_exists') {
$productCatID = $productCatDetails->get_error_data();
}
// TO DO: for other error code need to handle it
} else {
$productCatID = $productCatDetails['term_id'];
}
return $productCatID;
}
请注意:我已经测试了各个方法/函数,但尚未测试整个流程。其次,上面的代码示例中我没有处理图像部分,相信你能够轻松处理。
希望这有帮助!
引用:
- 这是 WooCommerce official doc
- 您还可以引用this article我已经详细解释了如何使用产品 CRUD
关于php - WooCommerce 产品 SKU 检查不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71494588/