Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.3k views
in Technique[技术] by (71.8m points)

php - Get all order item meta data in an unprotected array in WooCommerce 3

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...