![](/img/trans.png)
[英]Replace product “on backorder” to a custom field value in Woocommerce
[英]Read and update a custom field in woocommerce_product_on_backorder hook
我在 Woocommerce 變體產品中有一個自定義字段,我嘗試在有延期交貨的地方更新該字段。 這是代碼
add_action( 'woocommerce_product_on_backorder', 'reduce_second_stock' );
function reduce_second_stock( $array ){
$temp = get_post_meta($array['product']->ID, 'second_stock', true);
update_post_meta( $array['product']->ID, 'second_stock', $temp - $array['quantity'] );
}
自定義字段稱為second_stock
,它只是一個數字。 我試圖做的是根據該訂單的缺貨數量減少該數字。
但是,即使產品的常規庫存更新,我的自定義字段也保持不變。
有了這個鈎子, $array['product']
就是WC_Product
對象,所以要獲取產品 ID,你需要使用相關的方法get_id()
...由於 WooCommerce 3 和CRUD 對象,你可以直接使用WC_Data
方法get_meta()
, update_meta_data()
和save()
在WC_Product
對象上,例如:
add_action( 'woocommerce_product_on_backorder', 'reduce_second_stock' );
function reduce_second_stock( $array ){
if( $original_stock = $array['product']->get_meta('second_stock') ) {
$array['product']->update_meta_data( 'second_stock', ( $original_stock - $array['quantity'] ) );
$array['product']->save();
}
}
代碼位於活動子主題(或活動主題)的 function.php 文件中。 它應該工作。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.