订单完成后获取自定义字段值 woocommerce hook

Getting custom field value after order completed woocommerce hook

我已将名为 'pin_type' 的自定义字段添加到所有产品。

该字段有字符串值“single”或“multi”等。 我在 function.php 中使用 'woocommerce_order_status_completed' 挂钩来做一些事情。

我只是无法获得显示任何内容的自定义 'pin_type' 值。我使用 phpMyadmin 在 wp 数据库中搜索 pin_item,每个产品 pin_item 似乎都在 wp_postmeta table 中 'meta_key' 列下,值在 'meta_value'列。

如何根据订单中的产品获取价值?

add_action( 'woocommerce_order_status_completed', 'pincodeactions', 10, 1);

function pincodeactions( $order_id ) {
     $order = wc_get_order( $order_id );
     $order_id  = $order->get_id();
     $price = $order->get_total();
     $billing_email = $order->get_billing_email();
     $paid_date = date('Y-m-d h:m:s', strtotime($order->get_date_paid()));
     //$pin_type = $order->get_meta('pin_type'); //not working: Returns empty string
     $pin_type = get_post_meta( $this->order->get_id(), 'pin_type', true ); //ERROR: Using $this when not in object context
     echo pin_type

我找到了答案:

我的工作代码:

add_action( 'woocommerce_order_status_completed', 'pincodeactions', 10, 1);

function pincodeactions( $order_id ) {
     $order = wc_get_order( $order_id );
     $order_id  = $order->get_id();
     $price = $order->get_total();
     $billing_email = $order->get_billing_email();
     $paid_date = date('Y-m-d h:m:s', strtotime($order->get_date_paid()));
     
     //Get pin type
     $order = wc_get_order($order_id);
     $items = $order->get_items();
     
     foreach ($items as $item) {
        $product_id = $item['product_id'];
        $pin_type = get_post_meta($product_id, 'pin_type', true);
        
        if (empty($pin_type)){
            $pin_type = 'test';
        }
     }