【问题标题】:Change the product type of an existing product in WooCommerce 3+在 WooCommerce 3+ 中更改现有产品的产品类型
【发布时间】:2020-07-06 15:32:55
【问题描述】:

我需要在创建后使用我的子主题中的功能更改 woocommerce 产品类型,我已经尝试过:

 wp_set_object_terms($product_id, 'variable', 'product_type', true);

我的方法在创建后被触发了,但是类型仍然没有改变?

【问题讨论】:

  • 你应该在你的问题中添加你完整的钩子函数代码,因为你的实际代码是不可测试的...... “你的问题应该更新以包括所需的行为、特定的问题或错误,以及重现问题所需的最短代码”.
  • 我在获取产品后进行了测试并将其保存为代码工作我认为问题是插件挂钩中存在异步调用
  • 使用wp_set_object_terms(),由于多种原因并不总是有效,请参阅:stackoverflow.com/questions/58345045/… ... 下面的答案基于您在后端保存产品时使用的the save() 函数

标签: php wordpress woocommerce type-conversion product


【解决方案1】:

从 WooCommerce 3 开始,要从现有产品更改产品类型,您可以使用以下方法:

/**
 * Change product type.
 *
 * @param int     $product_id       - The product id.
 * @param string  $new_product_type - The new product type
 */
 
// Get the correct product classname from the new product type
$product_classname = WC_Product_Factory::get_product_classname( $product_id, $new_product_type );

// Get the new product object from the correct classname
$new_product       = new $product_classname( $product_id );

// Save product to database and sync caches
$new_product->save();

在所有情况下都经过测试和工作,因为 wp_set_object_terms() 不能很好地工作,原因有很多,请参阅 this older related thread。新产品将保留其所有现有数据。

有用的参考:WC_Meta_Box_Product_Data save() method

【讨论】:

  • 您的解决方案效果很好,但是创建后 woocommerce 的常规选项卡有一个问题,我不知道为什么?似乎该产品不是现有产品的副本
  • 还将 $product_classname 更改为 $classname
  • 我已经更新了代码……我已经测试了我的代码,产品保留了新产品类型中可以使用的所有数据。
  • 好的,我接受请将 $product_classname 更改为 $classname
  • @MoradAngel “可下载”产品选项不是产品类型,而是产品属性,因此与此问题无关。创建时,您可以根据需要设置所有库存属性……现在,当我将产品类型从现有的简单产品更改为可变产品时,库存设置仍然相同。
猜你喜欢
  • 2018-10-02
  • 2020-02-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-11-12
  • 2021-05-08
  • 2019-06-20
  • 1970-01-01
相关资源
最近更新 更多