Kol*_*zzy 2 php wordpress product custom-taxonomy woocommerce
美好的一天,我一直在试图弄清楚如何使用 php 以编程方式选择运输类。我正在使用表单从前端创建 woocommerce 产品,并在表单提交时创建产品,但我可以选择任何运输类别。下面的屏幕截图显示了从前端创建的产品上的运输类别设置,其中检查元素选项卡显示了运输类别的 id(作为值)
我正在使用以下代码选择电话运费等级
$pShipping_Class = 25; //Where 25 is the id/value for Phone Shipping Fee Class
update_post_meta( $product_id, 'product_shipping_class', $pShipping_Class );
Run Code Online (Sandbox Code Playgroud)
update_post_meta 适用于所有其他字段,即使是我创建的自定义下拉字段,我可以用来update_post_meta( $product_id, '_list_of_stores', 'custom-order' );从我创建的自定义下拉字段中选择值 custom-order 但是当我为运输类尝试相同的事情时,它不起作用。不知道我做错了什么。
请指出我正确的方向。我如何使用 php 更新运输类。我已经有了 ID 和 slug。
谢谢
更新:我意识到当我手动选择电话运费并点击更新产品按钮时。它添加了 selected 属性(即 selected="selected" ),见下面的截图;
请我如何进行此更新/选择任何运输类别(通过 ID 或 slug),因为运输类别需要即时更新,以便为用户提供他们创建并添加到购物车的产品的运费。
运输类别不由产品的后期元数据管理。它们由自定义分类法管理 ,因此您不能使用
update_post_meta()function。
在 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' );
Run Code Online (Sandbox Code Playgroud)
或者从 Woocommerce 3 开始,您可以这样使用WC_Product CRUD 方法 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
Run Code Online (Sandbox Code Playgroud)