Adding allot of categories to WordPress from XML feeds

i’m building a custom plugin for my internship that loads several XML product-feeds. Those feeds have ALLOT of categories and every feed names them slightly different, so i started normalising them with the help of an admin-UI where the admin can fill in new names for the categories.

This is how the categories array looks like after combining all feeds, removing duplicates, and the names are changed. (ofcourse in the real application this array is much longer)

Read More
Array
(
    [targetaudience] => Array
        (
            [Baby boys] => 
            [Baby girls] => 
            [Boys] => Boys
            [Boy] => Boys
            [Girls] => Girls
            [Girl] => Girls
            [Unisex] => 
        )

    [productgroup] => Array
        (
            [Pants short] => Pants
            [Pants long] => Pants
            [Trousers] => Pants
            [T-shirt] => T-shirts
            [Shirt] => T-shirts
            [Shirts] => T-shirts
            [T-shirt long-sleeve] => T-shirts
        )
);

This is the code to add the categories from the array to WordPress.

foreach($parent_categories as $parent_name => $child_categories) {

    //Create parent category
    $parent_id = wp_create_category($parent_name);


    //If parent-category was created successfully
    if($parent_id!=0) {         
        foreach($child_categories as $old_cat_name => $new_cat_name) {
            if($new_cat_name=='') {
                //Use old name
                wp_create_category($old_cat_name, $parent_id);
            } else {
                //Use new name
                wp_create_category($new_cat_name, $parent_id);                  
            }
        }
    }
}

What it does is it checks $parent_categories array for category names, if there’s a new name it will use that (array value), else it will just use the old name (array key).
I hope i made my intentions clear.
What goes wrong is when i execute the code it only adds the parent categories i.e.’targetaudience’ and ‘productgroup’, when i delete those parent-categories via the WordPress categories-page it deletes them and adds all the other categories right after. That can’t be normal behavior.

Any help is really appreciated!

EDIT : I checked the database, after the script is executed, all categories are added to the database. But when i check the WP-categories page it shows the parent-categories and allot of empty pages, it says ‘266 items’ and ’14 pages’ but those pages are empty. Only when i delete or edit any one category the rest appears. Sometimes the last parent-category isn’t even added although it is there when i echo it from the loop so something got to be going wrong when adding the category.

Related posts

Leave a Reply