Skip to content
Advertisement

How to set product brand when programatically importing WooCommerce product?

I am working on a script to import products from a plain text file that is provided to me by a 3rd party. I have successfuly imported the products by using WC_Product object, for instance:

JavaScript

The problem I’m facing is that I can’t seem to find a way to add the brand to the products. When importing from a csv file I managed to import the brand by using a code snippet that I found on the web that runs on the woocommerce_product_import_inserted_product_object hook:

JavaScript

I tried using wp_set_object_terms but I get an “invalid taxonomy” error. And I also tried different ways and none of them work and there’s no documentation about it.

These are some of the ways I tried:

JavaScript

Any ideas on how can I set the brand? I’m already clueless and got stuck there.

PS: I tried using both, id and brand name (string).

PS2: My script runs on add_action( 'init', function(){//...}) so everything should be available.

Thanks!

Advertisement

Answer

I finally managed to add the custom taxonomy to the product. The problem was that taxonomies were not registered during init hook. I changed it to wp_loaded hook instead. At that point plugins, theme, etc is ready. The method I used to set it is wp_set_post_terms.

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement