skip to Main Content

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

2

Answers


  1. 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
    
    Login or Signup to reply.
  2. 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

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search