Since WooCommerce 3, to change the product type from an existing product, you can use the following:
/**
* Change product type.
*
* @param int $product_id - The product id.
* @param string $new_product_type - The new product type
*/
// Get the correct product classname from the new product type
$product_classname = WC_Product_Factory::get_product_classname( $product_id, $new_product_type );
// Get the new product object from the correct classname
$new_product = new $product_classname( $product_id );
// Save product to database and sync caches
$new_product->save();
Tested and works in all cases, because wp_set_object_terms()
, doesn't works well for many reasons, see this older related thread. The new product will keep all its existing data.
Useful reference: WC_Meta_Box_Product_Data
save()
method
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…