Programmatically create product category and add thumbnail in woocommerce

I’m trying to create product-(sub)categories on a WordPress installation. The (sub)categories part is no problem at all, but I can’t seem to find a way to add the thumbnail image to the specific category.

In wp-admin, the field I want to fill asks for an attachment ID, so I tried uploading the image as attachment, without connecting it to a specific post. I then created my category, and tried the field names product_cat_thumbnail_id and thumbnail_id inside the wp_insert_term() function, and fill them with the attachment id. Just like the wp-admin function does, except wp-admin fills it with JavaScript after uploading, then saves it all when creating the category.

I’m not sure if I’m doing it wrong, I’m missing something obvious, or that it’s simply some kind of protected field that you are not allowed to fill.. (Which seems crazy to me)

Any ideas?

1 Answer
1

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