Woocommerce:在功能中更改产品类型 [英] Woocommerce: change Product Type in function

查看:56
本文介绍了Woocommerce:在功能中更改产品类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要在一个函数中将产品类型从 simple 更改为 variable .

I need to change the Product Type from simple to variable in a function.

我越接近这个,但不起作用.我需要代码第2行的帮助:

The closer I get is this, but not working. I need help with Line 2 of my code:

我必须使用 $ 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();

更新1 :我尝试过此方法,但不起作用:

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

推荐答案

我认为您必须在应用新术语之前删除旧的对象术语. wp_remove_object_terms 将删除旧的对象术语.

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

确保您的产品ID不为空.

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

这篇关于Woocommerce:在功能中更改产品类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆