【问题标题】:Woocommerce: change Product Type in functionWoocommerce:在功能中更改产品类型
【发布时间】:2020-02-09 04:55:37
【问题描述】:

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

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

我必须使用$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:我试过了,但没有用:

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

【问题讨论】:

  • 您能否发布您收到的错误,以便我们弄清楚为什么它不起作用?

标签: function woocommerce hook-woocommerce


【解决方案1】:

我认为您必须先删除旧的对象术语,然后再应用新的对象术语。 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

【讨论】:

  • 我尝试使用刚刚在 UPDATE 1 下方添加的代码,但无法正常工作。
  • 你可以尝试初始化模板重定向
  • 同时删除 === 并使其 == 检查帖子类型
【解决方案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 );

       }
    }
}

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-01-24
    • 2018-10-02
    • 1970-01-01
    • 2019-11-12
    • 1970-01-01
    相关资源
    最近更新 更多