I need to change the Product Type from simple to variable in a function.
The closer I get is this, but not working. I need help with Line 2 of my code:
I must use $product->save();
// Line 1: GET THE PRODUCT
$product = wc_get_product( get_the_id() );
// Line 2: SET THE PRODUCT TYPE TO: 'variable'
wp_set_object_terms( $product, 'variable', 'product_type' );
// Line 2: (I also tried this) SET THE PRODUCT TYPE TO: 'variable'
$product->set_product_type( 'variable' );
// Line 3: SAVE THE PRODUCT
$product->save();
UPDATE 1: I tried with this, but not working:
add_action( 'template_redirect', 'save_product_on_page_load' );
function save_product_on_page_load() {
if ( get_post_type() === "product" ){
$product = wc_get_product( get_the_id() );
if ( $product->is_type('simple') ) {
echo $productId = $product->get_id();
wp_remove_object_terms( $productId, 'simple', 'product_type' );
wp_set_object_terms( $productId, 'variable', 'product_type', true );
$product->save();
}
}
}