我正在尝试创建一个从 WooCommerce 中的产品中检索库存数量的函数。如果我注释掉以下行代码运行,但如果我把它留在我得到一个白屏: $product = is_a( $product, 'WC_Product' ) ?$product : wc_get_product($product_id);
有什么想法我在这里做错了吗?
function wc_get_variable_product_stock_quantity( $output = 'raw', $product_id = 0 ){
global $wpdb, $product;
// Get the product ID (can be defined)
$product_id = $product_id > 0 ? $product_id : get_the_id();
// Check and get the instance of the WC_Product Object
$product = is_a( $product, 'WC_Product' ) ? $product : wc_get_product($product_id);
$stock_quantity = $product->get_stock_quantity();
return $stock_quantity;
}
编辑(更新):
我的最终目标是在订单状态更改完成后汇总所有变体的库存数量,然后将总数写入父产品的库存数量,以便总库存数量始终是最新的。
我上面的过度简化示例实际上应该类似于下面的代码,主要基于“从 Woocommerce 中的可变产品获取所有变体的总库存”答案代码,并进行了轻微的更改(请参阅附加的 SQL 语句):
function wc_get_variable_product_stock_quantity( $output = 'raw', $product_id = 0 ){
global $wpdb, $product;
// Get the product ID (can be defined)
$product_id = $product_id > 0 ? $product_id : get_the_id();
// Check and get the instance of the WC_Product Object
$product = is_a( $product, 'WC_Product' ) ? $product : wc_get_product($product_id);
// Get the stock quantity sum of all product variations (children)
$stock_quantity = $wpdb->get_var("
SELECT SUM(pm.meta_value)
FROM {$wpdb->prefix}posts as p
JOIN {$wpdb->prefix}postmeta as pm ON p.ID = pm.post_id
WHERE p.post_type = 'product_variation'
AND p.post_status = 'publish'
AND p.post_parent = '$product_id'
AND pm.meta_key = '_stock'
AND pm.meta_value IS NOT NULL
");
return $stock_quantity;
}
// Update stock totals for parent product when order status changes to completed...
function mysite_woocommerce_order_status_completed( $order_id ) {
// For each item in the order, calculate the total stock quantity for all variations and write the total to the parent products's stock quantity
$order = wc_get_order( $order_id );
$order_id = $order->get_id();
$log_txt = '';
$items = $order->get_items();
foreach($items as $k=>$val){
$product_id = $val[‘product_id’];
$total_stock_quantity = wc_get_variable_product_stock_quantity( 'raw', $product_id );
$log_txt .= 'Product ID:'.$val['product_id'].', Name: '.$val['name'].', Total Stock: '.$total_stock_quantity.'\n<br>';
// Next: add code to write the stock total to the parent product
}
}
add_action( 'woocommerce_order_status_completed', 'mysite_woocommerce_order_status_completed', 10, 1 );