I have an issue with uploading categories/subcategories to a woocommerce e-shop using their Woocommerce API. Im using Javascript to get the data from the backend and I don't have any other issue regarding other exports to the site, but when I try to upload a category (I'm getting a list of categories from the backend, which also has a hasSubcategory boolean, id, alias, name), but when I try to upload it to the site, I'm unable to pass the id for the category/subcategory, because it wont upload it. If I leave it without the ids, then I won't be able to set the products to their corresponding category(they include a category_path with the id to the categories/subcategories). Snippet of the category part: (I have tried so many things around it and deleted all of it so its jsut a short code). P.S: The function is being called! Thanks for any advice!
async function createSubcategories(apiKey, category, WooCommerce) {
const subCategories = await categories(apiKey, category);
for (let j = 0; j < subCategories.subcategories.length; j++) {
const values = subCategories.subcategories[j];
const subCategoryData = {
name: values.name,
*CANT INCLUDE* id: values.id
};
await WooCommerce.post("products/categories", subCategoryData);
}
}
I could add/set the categories without their values, but not exactly how I wanted it and it also jsut didn't make sense (without some values).
You should obtain real parent category id returned by WP API in the callback of WooCommerce.post
and
use it as the value of parent
key in your subCategoryData
object:
const WooCommerceAPI = require('woocommerce-api');
const apiKey = "***";
const apiSecret = "***";
const WooCommerce = new WooCommerceAPI({
url: '<URL>',
consumerKey: apiKey,
consumerSecret: apiSecret,
wpAPI: true,
version: 'wc/v3'
});
const categoriesData = [
{ name: "Category 1", id: 1, hasSubcategory: true, subcategories: [ { name: "Subcategory 1", id: 11 }, { name: "Subcategory 2", id: 12 } ] },
{ name: "Category 2", id: 2, hasSubcategory: false }
];
async function createCategories() {
for (let i = 0; i < categoriesData.length; i++) {
const category = categoriesData[i];
const categoryData = {
name: category.name
};
const createdCategory = await WooCommerce.post("products/categories", categoryData, function(err, data, res) {
err ? console.error(err) : (() => {
const parsedRes = JSON.parse(res);
if (category.hasSubcategory) {
createSubcategories(category, parsedRes.id);
}
})();
});
}
}
async function createSubcategories(category, parentCategoryId) {
for (let j = 0; j < category.subcategories.length; j++) {
const subCategory = category.subcategories[j];
const subCategoryData = {
name: subCategory.name,
parent: parentCategoryId
};
await WooCommerce.post("products/categories", subCategoryData);
}
}
createCategories( WooCommerce);