Get order item meta data in an unprotected array i

2020-02-07 05:25发布

问题:

Is there another method to return meta values for custom attributes that doesn't return a protected array

foreach ($order->get_items() as $item_key => $item_values) {
    $item_id = $item_values->get_id();

    $item_meta_data = $item_values->get_meta_data();

    var_dump($item_meta_data); 

}

It outputs:

object(WC_Meta_Data)#3433 (2) {
    ["current_data":protected]=>
    array(3) {
      ["id"]=>
      int(4690)
      ["key"]=>
      string(14) "pa_second-half"
      ["value"]=>
      string(11) "nutty-butty"
    }

I've also tried this

$item_meta_data = $item_values->get_data();

$item_meta_data['key']

Which returns NULL.

回答1:

Updated

To get order items meta data in an unprotected array you can use WC_Order_Item method get_formatted_meta_data() instead.

The WC_Order_Item method get_formatted_meta_data() has 2 optional arguments:

  • $hideprefix to hide the prefix meta key (default is "_")
  • $include_all including all meta data, not only custom meta data (default is false)

So in the order items foreach loop:

foreach ( $order->get_items() as $item_id => $item ) {
    // Get all meta data in an unprotected array of objects
    $meta_data = $item->get_formatted_meta_data('_', true);

    // Raw output (testing)
    echo '<pre>'; var_dump($meta_data); echo '</pre>';
}

You will get an unprotected array of accessible objects with like:

  [4690]=>
  object(stdClass)#0000 (4) {
    ["key"]=>
    string(14) "pa_second-half"
    ["value"]=>
    string(11) "nutty-butty"
    ["display_key"]=>
    string(11) "Second half"
    ["display_value"]=>
    string(12) "Nutty butty"
  }

Now you can directly get the value from the meta key using the WC_Data method get_meta() in the order items foreach loop.

So for pa_second-half meta key:

foreach ( $order->get_items() as $item_id => $item ) {
    $meta_data = $item->get_formatted_meta_data();

    // Get the meta data value
    $meta_value = $item->get_meta("pa_second-half");

    echo $meta_value; // Display the value
}

And it will display: nutty-butty

Related thread: Get Order items and WC_Order_Item_Product in Woocommerce 3