Create product categories and subcategories

I have script which creates product categories for me. I’m migrating a WordPress website to a new one, so I exported the categories in a CSV and write an simple plugin to import that file.
The file looks like:

| ”Term ID” | Name | Slug | Term URI | Parent Term ID | Description | Display Type | Image |
|———–|—————-|—————-|————————————————————-|—————-|————-|————–|——————————————————————|
| 10233 | Uncategorized | uncategorized | https://[DOMAIN]/product-categorie/uncategorized/ | | | | |
| 10000 | Category | category | https://[DOMAIN]/product-categorie/category/ | | | | |
| 10151 | Sub Category 1 | sub-category-1 | https://[DOMAIN]/product-categorie/category/sub-category-1/ | 10000 | | | https://[DOMAIN]/wp-content/uploads/2015/12/[CATEGORY_IMAGE].jpg |
| 10150 | Sub Category 2 | sub-category-2 | https://[DOMAIN]/product-categorie/category/sub-category-2/ | 10000 | | | |

Currently I’m creating the categories like with this loop:

$file = fopen($_FILES[‘file’][‘tmp_name’], “r”);

$i =1;
while (($getData = fgetcsv($file, 10000, “,”)) !== FALSE) {
if($i > 1){ //skip first row
//”Term ID”,”Name”,”Slug”,”Term URI”,”Parent Term ID”,”Description”,”Display Type”,”Image”
$newterm = wp_insert_term($getData[1], ‘product_cat’);

if(is_wp_error($newterm)){
echo “<strong><font color=’blue’>Categorie for line “. $i . ” isn’t created (“. $getData[0] . “,” . $getData[1] .”,”. $getData[2].”)!</font></strong><br>”;
}else{
$id = $newterm[‘term_id’];
}
}
$i++;
}

So every category is created without checking for sub categories. How can I subcategories to a category? I know the loop through the file must be fixed then because I need some data from the ‘Parent Term ID’ number.

Read more here:: Create product categories and subcategories

Leave a Reply

Your email address will not be published. Required fields are marked *