Programmatically create product category and add thumbnail in woocommerce

Hereby my answer to my own post. I hope this is helpful to others too!

To create the category, I used an array with the data per category needed for the function wp_insert_term.

Then i looped trough that array,and used a fetch_media function that uploads the image found in the image-path given to that function, and returns an attachment ID.

I then call the wp_insert_term function, which i set as $cid, so that I can get the term_id value back from the returned array output.

With the returned $cid['term_id'] and the $thumb_id fetched from the fetch_media function, I can use the update_woocommerce_term_meta function, and update my thumbnail with the uploaded attachment.

The basic fetch_media function I’m using can be found here:
http://nlb-creations.com/2012/09/26/how-to-programmatically-import-media-files-to-wordpress/

I altered it so that the post_id was not required, because obviously, my terms (categories) aren’t posts.

$cats = array(
    array('thumb' => 'images/uploads/cat09.png','name' => 'Cat 9','description' => 'Cat 9 description','slug' => 'cat-9','parent' => 8),
    array('thumb' => 'images/uploads/cat10.png','name' => 'Cat 10','description' => 'Cat 10 description','slug' => 'cat-10','parent' => 8),
    array('thumb' => 'images/uploads/cat11.png','name' => 'Cat 11','description' => 'Cat 11 description','slug' => 'cat-11','parent' => 8),
);

foreach($cats as $data) {
    $thumb_id = fetch_media($data['thumb']);
    $cid = wp_insert_term(
        $data['name'], // the term 
        'product_cat', // the taxonomy
        array(
            'description'=> $data['description'],
            'slug' => $data['slug'],
            'parent' => $data['parent']
        )
    );

    if(!is_wp_error($cid)){
        $cat_id = isset( $cid['term_id'] ) ? $cid['term_id'] : 0;
        update_woocommerce_term_meta( $cat_id, 'thumbnail_id', absint( $thumb_id ) );
    }
}

Leave a Comment