【发布时间】:2020-12-09 09:17:31
【问题描述】:
我需要向 woocomerce 网站添加库存。我目前有一个如下所示的数组:
[0] => Array
(
[name] => Lenovo 0A36307
[product_id] => 0
[type] => simple
[description] => Technical Specifications:
Manufacturer: Lenovo
Model: 0A36307
Model compatible Lenovo Thinkpad x220, x230
Excellent quality at better than new prices.
[regular_price] => 119.99
[old_price] => 50.00
[manage_stock] => 1
[stock] => 0
[weight] => 0
[has_variations] => 0
[image] => [.......]/s/files/1/0016/1133/3750/products/batterie_20lenovo_200a36307_20x230_fin_c23370c7-1d32-4403-90ff-f4e27a9522f7.jpg
[woo_cat_id] => 51
[woo_cat] => Laptop
[woo_sub_cat] => Lenovo
)
[...]
[woo_cat_id] 等于 wp_terms 中的 terme_id(我以为是类别 ID)
我开始循环上面的数组来添加项目。代码如下所示:
logger("Checking if ".$product['name']." exists or not");
$check_sku=get_product_by_sku($product['product_id']);
if (empty($check_sku) ){
logger("Product does not exists proceed with insert");
$item = [
'post_title' => $product['name'],
'post_status' => 'publish',
'post_type' => 'product',
'post_content' => $product['description']
];
$postId = wp_insert_post($item);
}else{
logger("Product exists proceed with update");
$id= $check_sku->get_id();
$my_post = array(
'ID' => $id,
'post_title' => $product['name'],
'post_status' => 'publish',
'post_type' => 'product',
'post_content' => $product['description']
);
$postId = wp_update_post( $my_post );
}
logger("Creating product meta");
update_post_meta( $postId, '_visibility', 'visible' );
update_post_meta( $postId, '_stock_status', 'instock');
update_post_meta( $postId, '_regular_price', $product['regular_price'] );
update_post_meta( $postId, '_price', $product['regular_price'] );
update_post_meta( $postId, '_weight', $product['weight'] );
update_post_meta( $postId, '_sku', $product['product_id'] );
update_post_meta( $postId, '_stock', $product['stock'] );
update_post_meta( $postId, '_manage_stock', 'yes' );
logger("Adding product to category: ".$product['woo_cat']." (".$product['woo_cat_id'].")");
wp_set_object_terms( $postId, $product['woo_cat_id'], 'product_cat' );
产品已添加,但它以某种方式使用 [woo_cat_id] 作为名称创建了一个类别,而不是将其与现有类别相关联。
您也可以在上图中看到,品牌还有一个子类别。如何通过名称验证父 [woo_cat] 是否存在子类别 [woo_sub_cat],如果不创建则关联它?
使用 wp_set_object_terms() 我错了吗?或者还有什么我可以使用的吗? https://developer.wordpress.org/reference/functions/wp_set_object_terms/
【问题讨论】:
标签: php wordpress woocommerce