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:
//new product $objProduct = new WC_Product(); $objProduct->set_status("publish"); $objProduct->set_catalog_visibility('visible'); $objProduct->set_sku($product[SKU]); //and so on //edit existing product $product_id = wc_get_product_id_by_sku($product[SKU]); $objProduct = wc_get_product( $product_id ); $objProduct->set_status("publish"); //...
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:
public function process_import( $object, $data ) { if( isset( $data['product_brand'] ) ){ wp_delete_object_term_relationships( $object->get_id(), 'product_brand' ); $brands = explode( ',', $data['product_brand'] ); foreach( $brands as $brand ) wp_set_object_terms( $object->get_id(), $brand, 'product_brand', true ); } return $object; }
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:
$objProduct->set_attributes(['product_brand' => $brandId]); $objProduct->set_attributes(['product_brand' => array($brandId) ]); $objProduct->set_meta_data(['product_brand' => $brandId]); $objProduct->set_meta_data(['product_brand' => array($brandId) ]); $objProduct->set_prop('product_brand', $brandId); $objProduct->set_prop('product_brand', array($brandId));
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
.