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?

3
  • 2
    Perhaps consider using the methods provided by this object Commented Dec 28, 2017 at 13:53
  • Have you tried maybe casting it as an array/object first using the (array)$item_meta_dataor (object)$item_meta_data? Commented Dec 28, 2017 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 Commented Dec 28, 2017 at 14:01

2 Answers 2

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
Sign up to request clarification or add additional context in comments.

2 Comments

That gives me an error... Call to a member function get_data() on array
@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).
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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.