5

I am getting a WooCommerce order product meta_data like this...

$item_meta_data = $item_values->get_meta_data();

This gives me the following...

WC_Meta_Data Object
(
    [current_data:protected] => Array
        (
            [id] => 8795
            [key] => Option 1
            [value] => Yes
        )

    [data:protected] => Array
        (
            [id] => 8795
            [key] => Option 1
            [value] => Yes
        )

)

I am confused about the data that is returned, I want to check if Option 1 is set, I have tried to get the key like this...

foreach($item_meta_data as $meta_data_item) {
    echo $meta_data_item['key'];
}

But this is not working as it is not an array, anyone any ideas?

fightstarr20
  • 11,682
  • 40
  • 154
  • 278
  • 2
    Perhaps consider using the [methods provided by this object](https://docs.woocommerce.com/wc-apidocs/class-WC_Order_Item.html) – Mark Baker Dec 28 '17 at 13:53
  • Have you tried maybe casting it as an array/object first using the `(array)$item_meta_data`or `(object)$item_meta_data`? – cchoe1 Dec 28 '17 at 13:53
  • I had looked at the available methods but hadn't been able to make it do what I wanted. Perhaps it is my lack of understanding of the documenation. Will have a further read – fightstarr20 Dec 28 '17 at 14:01

2 Answers2

5

There is a magic method in WC_Meta_Data class named __get .

So you can access protected properties. For example:

$item_meta_data->key
LugiHaue
  • 2,702
  • 1
  • 15
  • 13
  • That gives me an error... Call to a member function get_data() on array – fightstarr20 Dec 28 '17 at 14:11
  • @fightstarr20 Same thing happend to me. It's because you have an array with one element in it. So in that case `$item_meta_data[0]->key` would work, - but you should probably refactor your code a bit (sinces `$item_meta_data` is an array of item_meta_data's). – Zeth Aug 14 '20 at 13:30
0

You can access all the data with $item_meta_data->get_data() or one specific item with $item_meta_data->id or $item_meta_data->key or $item_meta_data->value.

Philipp Maurer
  • 2,480
  • 6
  • 18
  • 25
Priidik Vaikla
  • 744
  • 4
  • 13