I'm trying to display every key and value from WooCommerce get_formatted_meta_data
order meta details.
This is my code to generate the array:
$order = new WC_Order( $order_id );
foreach ( $order->get_items() as $item_id => $item ) {
$item_data = $item->get_data();
$item_meta_data = $item->get_meta_data();
$formatted_meta_data = $item->get_formatted_meta_data( ' ', true );
$array = json_decode(json_encode($formatted_meta_data), true);
$arrayx = array_values($array);
foreach($arrayx as $value) {
$result[]=array($value["display_key"], wp_strip_all_tags($value["display_value"]));
foreach ($result as $key => $value) {
$var_label = $key;
$var_value = $value;
}
}
}
And this is the array I managed to print using above function:
Array
(
[0] => Array
(
[0] => Color
[1] => Black
)
[1] => Array
(
[0] => Size
[1] => M
)
[2] => Array
(
[0] => Gift
[1] => Tes 2
)
)
Now I want to get each value in the array and want to display them like this (displayed in new line):
Color: Black
Size: M
Gift: Tes 2
etc
etc
etc (dynamically inserted by WooCommerce if any or added by other plugins)
This is what I have already tried:
$order = new WC_Order( $order_id );
foreach ( $order->get_items() as $item_id => $item ) {
$product_id = $item->get_product_id();
$quantity = $item->get_quantity();
$product_name = $item->get_name();
$item_data = $item->get_data();
$item_meta_data = $item->get_meta_data();
$formatted_meta_data = $item->get_formatted_meta_data( ' ', true );
$array = json_decode(json_encode($formatted_meta_data), true);
$arrayx = array_values($array);
$count=0;
foreach($arrayx as $value) {
$result[]=array($value["display_key"], wp_strip_all_tags($value["display_value"]));
foreach ($result as $key => $value) {
$var_label = $key;
$var_value = $value;
$metadata['count'] = "\r\n".$var_label[0].": ".$var_value[0]."";
$count++;
}
}
$formatted_product_name = wp_strip_all_tags(" *".$product_name."*");
$product_plus_meta = "*".$formatted_product_name."* ".$metadata['count']."";
$quantity = $item->get_quantity();
$output_content.= urlencode("".$quantity."x - ".$product_plus_meta."\r\n");
}
}
$output_content.="".$price."";
Using the above code, I could only fetch one value and key from the array (only the latest in the array) which is Gift => Tes 2
.
And the output is something like this:
1x - **Sample Product**
Gift: Tes 2
Price: $12.00
Instead of this:
1x - **Sample Product**
Color: Black
Size: M
Gift: Tes 2
Price: $12.00
How to get the full list of each existed array key and value and display all of them in new line like above sample?
Thank you very much in advance. Any help would be much appreciated.
$metadata['count']
, which is where you're saving one value only and then overwriting it with the next one. Did you mean $count? But then I'm not sure what the $metadata array is, and you'll need to change the way you display that later. Or you could just append to any existing$metadata['count']
value rather than overwriting.