首页 > 解决方案 > 在 Woocommerce 中访问和显示订单商品元数据

问题描述

在 Woocommerce 中,我试图显示订单项目对象的结果并访问它:

$product_meta = $item->get_meta_data();
print_r ($product_meta);

这就是我想要拉的:

在此处输入图像描述

编辑:这是我使用的输出$item->get_formatted_meta_data( '', true )

在此处输入图像描述

标签: phpwordpresswoocommerceprotectedorders

解决方案


要获取所有订单商品元数据,您将使用带有特定参数的WC_Order_Item get_formatted_meta_data()方法,这样:

// Accessible non protected Order item meta data
$item_meta_data = $item->get_formatted_meta_data( '', true );

// Formatted raw Output
echo '<pre>'; print_r($item_meta_data); echo '</pre>';

要访问某些订单项目属性,您可以使用任何WC_Order_Item_Product方法,例如:

$item->get_product(); // Get the WC_Product object

$item->get_product_id(); // Get the Product ID

$item->get_variation_id(); // Get the Variation ID

$item->get_name(); // Get the Product name

$item->get_quantity(); // Get the item quantity 

// and so on …

然后,如果您需要访问特定的“自定义”订单项目数据值,您将使用WC_Data get_meta()方法

$custom_value = $item->get_meta("_custom_key");

请参阅:在 Woocommerce 3 中获取订单商品和 WC_Order_Item_Product


更新 (显示您所需的自定义订单商品元数据)

您可以通过以下方式访问和显示您需要的数据:

if( $lessons = $item->get_meta('lessons') ) {
    echo '<p>Lessons: '.$lessons.'</p>';
}

if( $tour_guide = $item->get_meta('tour guide') ) {
    echo '<p>Tour Guide: '.$tour_guide.'</p>';
}

我希望这现在有效。


推荐阅读