Search code examples
javascriptwoocommercewoocommerce-rest-api

Unable to add products to corresponding categories/subcategories using WooCommerce API


`Hi, so I have some categories/subcategories(even multiple nested subcategories) added by Js to a woocommerce site. The issue is, that I try to assign the products (they have a category_path array of objects, including the id,name,url - for each product ) to it's corresponding category/subcategory when I try to post them, but the only thing that matches between them, is the name. I tried to assign the name only as I pass the categories property, but an ID is needed inside the post of the products, or else it doesnt save the products to a category, just add them uncategorized. Snippet of my code:

P.S: I know Im receiving back an array of names when I loop over the detailsData, and I have tried many ways, but I got stuck.`

const WooCommerce = new WooCommerceAPI({
  url: "https://X.X/",
  consumerKey: "ck_X",
  consumerSecret: "cs_X0",
  wpAPI: true,
  version: "wc/v3",
});

await createCategories(WooCommerce);

for (let i = 0; i < searchResults.products.length; i++) {
  const product = searchResults.products[i];
  const detailsData = await details(apiKey, product.id);

  const sections = detailsData.category_path;

  const productData = {
    name: product.title,
    type: "simple",
    categories: [
      {
        name: sections.name, 

      },
    ],
  };
  await WooCommerce.post("products", productData);
}

the name from the category_path is amtching the category/sbcategories name Im expecting to achieve the products in the cateogries they should be based on the matching name.


Solution

  • So , I saved all of my categories/subcategories into a json from the Woocommerce site, and basically add the products based on that to their corresponding category, its faster, as it doesnt have to run a loop after every product.