I am trying to create and update woocommerce products automatically from an API. I have created the starting point of the plugin and this is my method that gets the products from the external API and then loops through them and creates a simple product in woocoommerce.
It creates the products perfectly fine however if I run the code twice, the products do not get an update but a whole new batch of them are created (SKU are duplicated without any errors), it seems like the SKU is not recognized even though it exists and I can see it on the product's dashboard and on the frontend here is my code so far:
// 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']);
}
}
}
does anyone have any ideas why the SKUs are present but not recognized and the products just keep duplicating? thanks.