Woocommerce:在功能中更改产品类型

时间:2019-10-11 16:13:19

标签: function woocommerce hook-woocommerce

我需要在功能中将产品类型从style=@style/Widget.MaterialComponents.Button.OutlinedButton更改为simple

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

我必须使用variable

$product->save();

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

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

2 个答案:

答案 0 :(得分:2)

我认为您必须先删除旧的对象术语,然后再应用新的术语。 wp_remove_object_terms将删除旧的对象术语。

  

确保您的产品ID不为空。

这是一个经过验证的简单示例

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

答案 1 :(得分:0)

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

       }
    }
}

重新加载简单产品页面后,产品只是将其类型更改为变量。通过进入产品编辑屏幕进行检查并确认