JPashs
JPashs

Reputation: 13886

Woocommerce: change Product Type in function

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();
       }
    }
}

Upvotes: 3

Views: 3966

Answers (3)

Harriet
Harriet

Reputation: 11

For anyone else coming across this issue, creating the product using the related type's WooCommerce class and then saving it appears to change the type. See the code below:

$new_type = 'variable'

$classname = WC_Product_Factory::get_product_classname($product_id, $new_type);
$product = new $classname($wooProduct->get_id());

$product->save()

This is a slightly modified version of part of the code from WC_Meta_Box_Product_Data::save()

Upvotes: 1

mujuonly
mujuonly

Reputation: 11861

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') ) { 
           $productId = $product->get_id();  
           wp_remove_object_terms( $productId, 'simple', 'product_type', true );
           wp_set_object_terms( $productId, 'variable', 'product_type', true );

       }
    }
}

After reloading the simple product page, the product simply changed it's type to variable. Checked and confirmed by going to product edit screen

Upvotes: 0

Firefog
Firefog

Reputation: 3174

I think you have to remove your old object term before apply new one. wp_remove_object_terms will remove the old object term.

make sure your product ID is not null.

Here is a simple example it worked and tested

function woo_set_type_function(){
   $product_id = 18; //your product ID
   wp_remove_object_terms( $product_id, 'simple', 'product_type' );
   wp_set_object_terms( $product_id, 'variable', 'product_type', true );
}
add_action('init', 'woo_set_type_function'); //init is for testing purpose only

Upvotes: 4

Related Questions