/** * Changes product type. * * @see https://wpcodebook.com/woocommerce-change-product-type-programmatically/ * @see https://developer.wordpress.org/reference/functions/wp_set_object_terms/ * @see https://github.com/woocommerce/woocommerce/blob/8.1.0/plugins/woocommerce/includes/data-stores/class-wc-product-data-store-cpt.php#L1727 * @see https://github.com/woocommerce/woocommerce/blob/8.1.0/plugins/woocommerce/includes/data-stores/class-wc-product-data-store-cpt.php#L853 * @see https://github.com/woocommerce/woocommerce/blob/8.1.0/plugins/woocommerce/includes/class-wc-post-data.php#L137 * * @param string $new_type Product type to change to, e.g., `variable`, `simple`, etc. */ function wpcodebook_update_product_type( $product, $new_type ) { $old_type = $product->get_type(); $product_id = $product->get_id(); wp_set_object_terms( $product_id, $new_type, 'product_type' ); $cache_key = WC_Cache_Helper::get_cache_prefix( 'product_' . $product_id ) . '_type_' . $product_id; $product_type = wp_cache_set( $cache_key, $new_type, 'products' ); if ( $old_type !== $new_type ) { do_action( 'woocommerce_product_type_changed', $product, $old_type, $new_type ); } }