get_product_from_item($ item)在WooCommerce中弃用的替换

问题描述:

我试图修复unsupported SagePay plugin中的一些弃用函数。

如何替换WooCommerce中的以下代码片段?

foreach ($order->get_items() as $item) { 
if ($item['qty']) { 
    $product = $order->get_product_from_item($item); 

我可以看到,这是它的替代:

@Deprecated添加弃用通知在未来的版本。替换$item->get_product()

但只是将其更改为$product = $item->get_product();不起作用。我也试图改变该行:

$product = wc_get_product($item['id']);

但在结帐时会导致内部服务器错误。

您可以在WC_OrderWC_Order_Items对象这样使用WC_data get_data()方法:

// For testing only 
$order = wc_get_order(500); 

// Iterate though each order item 
foreach ($order->get_items() as $item_id => $item) { 

    // Get the WC_Order_Item_Product object properties in an array 
    $item_data = $item->get_data(); 

    if ($item['quantity'] > 0) { 
     // get the WC_Product object 
     $product = wc_get_product($item['product_id']); 
     // test output 
     print_r($product); 
    } 
} 

或者与WC_Order_Item_Product get_product_id()方法:

// For testing only 
$order = wc_get_order(500); 

// Iterate though each order item 
foreach ($order->get_items() as $item_id => $item) { 
    if($item->get_quantity() > 0){ 
     // Get the product id from WC_Order_Item_Product object 
     $product_id = $item->get_product_id(); 
     // get the WC_Product object 
     $product = wc_get_product($item['product_id']); 

     // test output 
     print_r($product); 
    } 
} 

这一切正在里面活动主题php文件。

当主题PHP文件测试,我可以$item->get_product();


相关答案得到WC_Product对象:How to get WooCommerce order details

+1

我最初使用'$用品 - > get_product( );'但是因为PhpStorm强调它是一种不存在的方法,所以我没有使用它。事实证明,这确实有效。我真的把最后一行改成'$ product = $ item-> get_product();'现在它完美地工作了。 –

+1

@LiamMcArthur我感到非常惊讶,它不工作......所以没有用新的WC方法更新的愚蠢的编辑...它开心工作。 – LoicTheAztec