WooCommerce 产品 SKU 检查不起作用
WooCommerce Product SKU checking is not working
我正在尝试从 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 方法。我知道你参考了我的(我会很快更新那个答案),那时 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;
}
请注意:我测试了个人 methods/functions 但我没有测试整个流程。其次,上面的代码示例中我没有处理图像部分,相信你会很容易处理的。
希望对您有所帮助!
参考:
- 这是 WooCommerce official doc
- 你也可以参考this article我已经详细解释了如何使用Product CRUD
我正在尝试从 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 方法。我知道你参考了我的
这是工作代码示例。
<?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;
}
请注意:我测试了个人 methods/functions 但我没有测试整个流程。其次,上面的代码示例中我没有处理图像部分,相信你会很容易处理的。
希望对您有所帮助!
参考:
- 这是 WooCommerce official doc
- 你也可以参考this article我已经详细解释了如何使用Product CRUD