在Woocommerce中以编程方式设置或更新产品运输类别

时间:2019-01-27 16:20:09

标签: php wordpress woocommerce product custom-taxonomy

早安, 我一直试图找出如何使用php以编程方式选择运输类别。我正在使用表单从前端创建woocommerce产品,并在表单提交时创建了该产品,但是我可以选择任何一种运输类。下面的屏幕快照显示了从前端创建的产品上的运输类别设置,带有检查元素选项卡,显示了运输类别的ID(作为值)

woocommerce shipping classes

我正在使用以下代码选择手机的运费类别

$pShipping_Class = 25; //Where 25 is the id/value for Phone Shipping Fee Class
update_post_meta( $product_id, 'product_shipping_class', $pShipping_Class );

update_post_meta适用于所有其他字段,即使我创建的自定义下拉字段也可以使用update_post_meta( $product_id, '_list_of_stores', 'custom-order' );从我创建的自定义下拉字段中选择值custom-order,但是当我尝试相同的运输方法时类,它不起作用。不知道我在做什么错。

请指出正确的方向。我如何使用php更新运输类别。我已经有ID和子弹了。

谢谢

更新:我意识到,当我手动选择“电话运输费”并点击“更新产品”按钮时。它添加了selected属性(即selected =“ selected”),请参见下面的屏幕截图;

woocommerce shipping class selected

请我如何进行此更新/选择任何运输类别(通过ID或Slug),因为需要即时更新运输类别以向用户提供他们创建并添加到的产品的运输费率购物车。

1 个答案:

答案 0 :(得分:1)

  

运输类不由产品的后期元数据管理。它们由自定义分类法管理,因此您不能使用update_post_meta()功能

在Woocommerce中,运输类由自定义分类法 product_shipping_class 管理,您将需要使用wp_set_post_terms()函数使其以编程方式工作,例如:

$shipping_class_id = 25; // the targeted shipping class ID to be set for the product

// Set the shipping class for the product
wp_set_post_terms( $product_id, array($shipping_class_id), 'product_shipping_class' );

或者从Woocommerce 3开始,您可以通过以下方式使用WC_Product CRUD method set_shipping_class_id()

$shipping_class_id = 25; // the targeted shipping class ID to be set for the product

$product = wc_get_product( $product_id ); // Get an instance of the WC_Product Object

$product->set_shipping_class_id( $shipping_class_id ); // Set the shipping class ID 

$product->save(); // Save the product data to database
相关问题