Change the product type of an existing product in WooCommerce 3+

偶尔善良 提交于 2020-07-09 05:24:43

问题


I need to change the woocommerce product type after creation with a function in my child theme i have tried this :

 wp_set_object_terms($product_id, 'variable', 'product_type', true);

My method is triggered after creation but the type still unchanged ?


回答1:


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



来源:https://stackoverflow.com/questions/62759419/change-the-product-type-of-an-existing-product-in-woocommerce-3

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!